Files
paperclip/packages/db/scripts/clean-poisoned-claude-sessions.ts
T
Danial Jawaid 8ee3987d12 adapter-claude-local: recover from poisoned previous_message_id 400 (detect + clearSession) (#5972)
## Thinking Path

> - Paperclip's `claude_local` adapter persists Claude Code session
jsonls under `~/.claude/projects/…/{sessionId}.jsonl` and resumes them
on the next heartbeat
> - When Claude Code injects `<synthetic>` placeholder assistant
messages (after rate-limit, max-turn exhaustion, or transient-upstream
failures) those placeholders get UUID-format `message.id`s rather than
`msg_…`-format ids
> - On the next `--resume`, Claude Code passes that UUID as
`previous_message_id` and Anthropic's API rejects it with a 400:
``diagnostics.previous_message_id: must be the `id` from a prior
/v1/messages response (starts with `msg_`)``
> - The adapter had a session-rotation fallback only for "unknown
session" errors, so the poisoned session was `--resume`-d indefinitely
and the agent flipped between `idle` and `error` every heartbeat
> - Even worse, the *result* event of the failing run still carried a
`session_id`, and the adapter was persisting that id into the
issue-scoped session store (`agentTaskSessions`). So even after we
detected the 400, every subsequent continuation re-loaded the same
poisoned id and hit the same 400 again — the issue was permanently
stranded
> - We observed this on multiple agents in our deployment; the only
manual fix was to rename the `.jsonl`, which is not a viable long-term
workaround
> - This PR detects the 400, runs the same session-rotation fallback the
unknown-session path uses **and** stops persisting the poisoned id, so
the next attempt starts genuinely fresh

## Linked Issues or Issue Description

No external GitHub issue is linked. Describing the problem inline
following the bug-report template:

**What happened:** `claude_local` agents flipped between `idle` and
`error` on every heartbeat because the persisted session jsonl carried a
synthetic UUID `previous_message_id` (from `<synthetic>` assistant
placeholders injected after rate-limit/max-turn/upstream errors).
Anthropic's API rejected every `--resume` with a 400:
``diagnostics.previous_message_id: must be the `id` from a prior
/v1/messages response (starts with `msg_`)``.

**Expected behavior:** When the persisted session is poisoned and
unrecoverable, the adapter should rotate to a fresh session — the same
fallback path already used for unknown-session errors — and stop
re-persisting the poisoned `session_id`.

**Actual behavior:** The session-rotation fallback only matched the
"unknown session" pattern, so the poisoned session was `--resume`-d
forever. The result event of the failing run still carried `session_id`,
which was being persisted into `agentTaskSessions`, so every subsequent
continuation reloaded the same poisoned id and hit the same 400.

**Reproduction:** Inject any flow that causes Claude Code to emit a
`<synthetic>` placeholder (rate-limit, max-turn exhaustion, transient
upstream failure). The next `--resume` will fail with the 400 and the
agent will not self-recover.

**Scope of fix:** Add a `previous_message_id` 400 detector; route it
through the existing unknown-session fallback; drop the poisoned
`sessionId` and emit `clearSession: true` so the heartbeat service wipes
the persisted row; best-effort delete the local poisoned `.jsonl`.

## What Changed

Two commits:

1. **`adapter-claude-local: auto-rotate session on previous_message_id
400 (synthetic-msg poisoning)`** — detector + execute-time rotation
2. **`adapter-claude-local: guard against persisting poisoned
sessionId`** — validate-before-persist + `clearSession`

Combined diff:

- `parse.ts`: new `isClaudePoisonedPreviousMessageIdError(parsed)`
matching ``/diagnostics\.previous_message_id.*starts with `msg_`/i``
against `parsed.result` and `extractClaudeErrorMessages(parsed)`
- `parse.ts`: `isClaudeTransientUpstreamError()` excludes the new error
from transient classification so it isn't masked as retryable upstream
noise
- `execute.ts`: expand the resume-fallback branch so it triggers on both
`isClaudeUnknownSessionError` and the new
`isClaudePoisonedPreviousMessageIdError`, with a distinct log line
(`"returned a poisoned message-id"` vs `"is unavailable"`)
- `execute.ts`: for local (non-remote) execution targets, best-effort
delete the poisoned `~/.claude/projects/.../{sessionId}.jsonl` before
retrying so the file can't be accidentally resumed by an out-of-band
caller. The `fs.unlink` and follow-up log call are in separate try/catch
blocks so a closed log stream cannot mask a successful unlink (and vice
versa)
- `execute.ts` / `toAdapterResult`: when a result carries the poisoned
400, **drop** `sessionId`/`sessionParams`/`sessionDisplayId` (return
`null`) and emit `clearSession: true` so the heartbeat service's
`resolveNextSessionState` wipes the persisted row. The result also
surfaces `errorCode: "claude_poisoned_previous_message_id"` for
observability
- `docs/adapters/claude-local.md`: runbook entry — symptom,
auto-recovery flow, on-call checklist
- Tests:
- 4 new `parse.test.ts` cases covering positive detection in `result`
and `errors[]`, negative cases, and non-transient classification
- 3 new `claude-local-execute.test.ts` cases: (a) fresh run reports the
poisoned error → sessionId dropped + `clearSession: true`; (b) recovery
retry also reports the poisoned error → same guards apply; (c)
session-rotation success on retry

## Verification

```bash
pnpm --filter @paperclipai/adapter-claude-local exec vitest run src/server/parse.test.ts
pnpm --filter @paperclipai/server exec vitest run src/__tests__/claude-local-execute.test.ts
```

Both suites green locally. This patch is also currently running as a
hot-patch over the published `2026.513.0` adapter on the reporting
deployment — sessions that previously looped indefinitely now
self-recover on the first heartbeat after the 400 surfaces.

## Risks

- Low risk. The detector is conservative (regex over `result` +
`errors[]` only) and the rotation reuses the existing unknown-session
fallback path
- The local-only `fs.unlink` of the poisoned `.jsonl` is wrapped in
`try/catch` and ignored on failure — strictly an optimization; the
server-side session clear is the authoritative reset
- Remote execution targets (`executionTargetIsRemote`) skip the disk
cleanup because the file lives on a remote host that we can't safely
reach from the adapter
- The `clearSession: true` + nulled session fields path is a no-op on
healthy runs; it only fires when the new detector matches, so existing
successful continuations are unaffected
- No DB schema changes, no public API changes, no new dependencies

## Model Used

- Provider: Anthropic Claude
- Model: `claude-opus-4-7` (Opus 4.7)
- Context window: 1M
- Capabilities: extended reasoning, tool use, code execution
- Role: implemented the detector, expanded the fallback branch, added
the persist-guard + `clearSession`, wrote the unit + integration tests,
validated locally, and applied the equivalent hot-patch to the deployed
`2026.513.0` install while this PR is in review

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for similar or duplicate PRs and linked
them — closed #2295, #2361, #3572, #5438 as duplicates of this canonical
fix; complementary fixes #4838 (heartbeat_timer reset) and #4932 (gemini
context-overflow rotation) target different code paths
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots — N/A, adapter-only change
- [x] I have updated relevant documentation
(`docs/adapters/claude-local.md` runbook entry)
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Danial Jawaid <danial.jawaid@gmail.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
Co-authored-by: Devin Foley <devin@paperclip.ing>
2026-06-09 15:45:47 -07:00

463 lines
15 KiB
TypeScript

#!/usr/bin/env tsx
/**
* One-shot cleaner for `agent_task_sessions` rows whose persisted `claude_local`
* session is poisoned by a non-`msg_*` `previous_message_id`.
*
* The poison shape: the Claude CLI keeps an on-disk JSONL transcript keyed by
* sessionId at `<claude-config-dir>/projects/<encoded-cwd>/<sessionId>.jsonl`.
* If the last `assistant` entry has a `message.id` that does NOT start with
* `msg_`, every subsequent `--resume` against /v1/messages 400s with
* `diagnostics.previous_message_id` and the issue is permanently stranded
* until the persisted session is dropped. See RED-877 / RED-978 / RED-991 for
* the upstream adapter fix; this script retroactively heals rows that were
* stranded BEFORE that adapter shipped.
*
* Usage:
* tsx packages/db/scripts/clean-poisoned-claude-sessions.ts \
* --config /path/to/paperclip/config.json \
* [--claude-config-dir ~/.claude] \
* [--dry-run] [--json]
*
* Or in a Paperclip checkout shell:
* pnpm --filter @paperclipai/db exec tsx scripts/clean-poisoned-claude-sessions.ts --dry-run
*
* Exits 0 on success even when nothing was healed. Idempotent.
*/
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { and, eq, isNotNull, sql } from "drizzle-orm";
import { createDb } from "../src/client.js";
import { agentTaskSessions } from "../src/schema/index.js";
const CLAUDE_ADAPTER_TYPE = "claude_local";
export type SessionClassification =
| { kind: "healthy"; lastAssistantId: string }
| { kind: "poisoned"; lastAssistantId: string }
| { kind: "missing_jsonl"; jsonlPath: string }
| { kind: "no_assistant_entries" }
| { kind: "skipped_remote" }
| { kind: "skipped_no_session_id" }
| { kind: "unreadable_jsonl"; error: string };
export interface ClaudeSessionRowInput {
sessionId: string | null;
cwd: string | null;
isRemote: boolean;
}
/**
* Pure classifier — given JSONL text, returns whether the session is poisoned.
* A session is "poisoned" iff its last `assistant` entry has a `message.id`
* that does not start with `msg_`. Sessions with zero assistant entries are
* left alone (they can be resumed safely from scratch).
*/
export function classifyJsonlText(text: string): SessionClassification {
let lastAssistantId: string | null = null;
for (const rawLine of text.split(/\r?\n/)) {
const line = rawLine.trim();
if (!line) continue;
let obj: unknown;
try {
obj = JSON.parse(line);
} catch {
continue;
}
if (!obj || typeof obj !== "object") continue;
const entry = obj as Record<string, unknown>;
if (entry.type !== "assistant") continue;
const msg = entry.message;
if (!msg || typeof msg !== "object") continue;
const id = (msg as Record<string, unknown>).id;
if (typeof id === "string" && id.length > 0) {
lastAssistantId = id;
}
}
if (lastAssistantId === null) {
return { kind: "no_assistant_entries" };
}
if (lastAssistantId.startsWith("msg_")) {
return { kind: "healthy", lastAssistantId };
}
return { kind: "poisoned", lastAssistantId };
}
export function encodeClaudeCwd(cwd: string): string {
// Mirrors `effectiveExecutionCwd.replace(/[^a-zA-Z0-9-]/g, "-")` from the
// claude-local adapter (`packages/adapters/claude-local/src/server/execute.ts`).
return cwd.replace(/[^a-zA-Z0-9-]/g, "-");
}
export function resolveClaudeConfigDir(env: NodeJS.ProcessEnv = process.env, override?: string): string {
if (override && override.trim().length > 0) return path.resolve(override);
const fromEnv = env.CLAUDE_CONFIG_DIR;
if (typeof fromEnv === "string" && fromEnv.trim().length > 0) {
return path.resolve(fromEnv);
}
return path.join(os.homedir(), ".claude");
}
export function jsonlPathFor(input: { claudeConfigDir: string; cwd: string; sessionId: string }): string {
return path.join(
input.claudeConfigDir,
"projects",
encodeClaudeCwd(input.cwd),
`${input.sessionId}.jsonl`,
);
}
export function classifyRow(
row: ClaudeSessionRowInput,
opts: { claudeConfigDir: string; readJsonl: (filePath: string) => string | null },
): SessionClassification & { jsonlPath?: string } {
if (!row.sessionId) return { kind: "skipped_no_session_id" };
if (row.isRemote) return { kind: "skipped_remote" };
if (!row.cwd) return { kind: "skipped_no_session_id" };
const jsonlPath = jsonlPathFor({
claudeConfigDir: opts.claudeConfigDir,
cwd: row.cwd,
sessionId: row.sessionId,
});
let text: string | null;
try {
text = opts.readJsonl(jsonlPath);
} catch (error) {
return {
kind: "unreadable_jsonl",
error: error instanceof Error ? error.message : String(error),
jsonlPath,
};
}
if (text === null) {
return { kind: "missing_jsonl", jsonlPath };
}
const classification = classifyJsonlText(text);
return { ...classification, jsonlPath };
}
interface CliArgs {
configPath: string | null;
claudeConfigDir: string | null;
dryRun: boolean;
json: boolean;
databaseUrl: string | null;
deleteMissing: boolean;
}
function parseArgs(argv: string[]): CliArgs {
const args: CliArgs = {
configPath: null,
claudeConfigDir: null,
dryRun: false,
json: false,
databaseUrl: null,
deleteMissing: false,
};
for (let i = 0; i < argv.length; i++) {
const token = argv[i];
switch (token) {
case "--config":
args.configPath = argv[++i] ?? null;
break;
case "--claude-config-dir":
args.claudeConfigDir = argv[++i] ?? null;
break;
case "--database-url":
args.databaseUrl = argv[++i] ?? null;
break;
case "--dry-run":
args.dryRun = true;
break;
case "--json":
args.json = true;
break;
case "--delete-missing-jsonl":
args.deleteMissing = true;
break;
case "--help":
case "-h":
process.stdout.write(USAGE);
process.exit(0);
break;
default:
if (token.startsWith("--")) {
throw new Error(`Unknown flag: ${token}`);
}
}
}
return args;
}
const USAGE = `Usage:
tsx packages/db/scripts/clean-poisoned-claude-sessions.ts [flags]
Flags:
--config <path> Path to paperclip config.json (defaults to
$PAPERCLIP_HOME/instances/default/config.json or
the standard locations).
--database-url <url> Override DB connection string entirely.
--claude-config-dir <path> Override Claude CLI config dir (default:
$CLAUDE_CONFIG_DIR or ~/.claude).
--dry-run Report poisoned rows but do not delete.
--delete-missing-jsonl Also delete rows whose sessionId references a
JSONL that no longer exists on disk.
--json Emit a single JSON summary on stdout instead of
human-readable lines.
-h, --help Print this usage.
`;
function readDatabaseUrlFromConfig(configPath: string): string {
const raw = fs.readFileSync(configPath, "utf8");
const parsed = JSON.parse(raw) as {
database?: {
mode?: string;
embeddedPostgresPort?: number;
connectionString?: string;
};
};
if (parsed.database?.mode === "postgres" && parsed.database.connectionString) {
return parsed.database.connectionString;
}
const port = parsed.database?.embeddedPostgresPort ?? 54329;
return `postgres://paperclip:paperclip@127.0.0.1:${port}/paperclip`;
}
function defaultConfigPath(): string | null {
const candidates: string[] = [];
const home = os.homedir();
if (process.env.PAPERCLIP_HOME) {
candidates.push(path.join(process.env.PAPERCLIP_HOME, "config.json"));
}
candidates.push(path.join(home, ".paperclip", "instances", "default", "config.json"));
for (const candidate of candidates) {
if (fs.existsSync(candidate)) return candidate;
}
return null;
}
function readJsonlSafe(filePath: string): string | null {
try {
return fs.readFileSync(filePath, "utf8");
} catch (error) {
if (error && typeof error === "object" && "code" in error && (error as { code: string }).code === "ENOENT") {
return null;
}
throw error;
}
}
interface Row {
id: string;
agentId: string;
taskKey: string;
sessionDisplayId: string | null;
sessionParamsJson: Record<string, unknown> | null;
}
function extractSessionParams(row: Row): ClaudeSessionRowInput {
const params = row.sessionParamsJson ?? {};
const sessionId =
typeof params.sessionId === "string" && params.sessionId.length > 0
? (params.sessionId as string)
: null;
const cwd =
typeof params.cwd === "string" && params.cwd.length > 0 ? (params.cwd as string) : null;
const isRemote =
"remoteExecution" in params &&
params.remoteExecution !== null &&
typeof params.remoteExecution === "object";
return { sessionId, cwd, isRemote };
}
interface HealedPair {
rowId: string;
agentId: string;
taskKey: string;
sessionId: string | null;
lastAssistantId: string | null;
jsonlPath: string | null;
reason: "poisoned" | "missing_jsonl";
}
async function main(argv: string[]): Promise<void> {
const args = parseArgs(argv);
const configPath = args.configPath ?? defaultConfigPath();
const databaseUrl =
args.databaseUrl ??
process.env.DATABASE_URL ??
(configPath ? readDatabaseUrlFromConfig(configPath) : null);
if (!databaseUrl) {
throw new Error(
"Unable to resolve database URL. Pass --database-url or --config <paperclip config.json>.",
);
}
const claudeConfigDir = resolveClaudeConfigDir(process.env, args.claudeConfigDir ?? undefined);
const db = createDb(databaseUrl);
const closableDb = db as typeof db & {
$client?: { end?: (options?: { timeout?: number }) => Promise<void> };
};
const summary = {
scanned: 0,
poisoned: 0,
missingJsonl: 0,
noAssistantEntries: 0,
healthy: 0,
skippedRemote: 0,
skippedNoSession: 0,
unreadable: 0,
deleted: 0,
dryRun: args.dryRun,
healedPairs: [] as HealedPair[],
skippedRemotePairs: [] as Array<{ rowId: string; agentId: string; taskKey: string }>,
};
const log = (line: string) => {
if (!args.json) process.stdout.write(`${line}\n`);
};
try {
const rows: Row[] = await db
.select({
id: agentTaskSessions.id,
agentId: agentTaskSessions.agentId,
taskKey: agentTaskSessions.taskKey,
sessionDisplayId: agentTaskSessions.sessionDisplayId,
sessionParamsJson: agentTaskSessions.sessionParamsJson,
})
.from(agentTaskSessions)
.where(
and(
eq(agentTaskSessions.adapterType, CLAUDE_ADAPTER_TYPE),
isNotNull(agentTaskSessions.sessionParamsJson),
),
);
log(
`Scanning ${rows.length} claude_local rows; claudeConfigDir=${claudeConfigDir}; dryRun=${args.dryRun}`,
);
const toDelete: HealedPair[] = [];
for (const row of rows) {
summary.scanned += 1;
const input = extractSessionParams(row);
const classification = classifyRow(input, {
claudeConfigDir,
readJsonl: readJsonlSafe,
});
switch (classification.kind) {
case "healthy":
summary.healthy += 1;
break;
case "no_assistant_entries":
summary.noAssistantEntries += 1;
break;
case "skipped_remote":
summary.skippedRemote += 1;
summary.skippedRemotePairs.push({
rowId: row.id,
agentId: row.agentId,
taskKey: row.taskKey,
});
break;
case "skipped_no_session_id":
summary.skippedNoSession += 1;
break;
case "unreadable_jsonl":
summary.unreadable += 1;
log(
`[warn] unreadable jsonl for row=${row.id} agent=${row.agentId} task=${row.taskKey} error=${classification.error}`,
);
break;
case "missing_jsonl": {
summary.missingJsonl += 1;
if (args.deleteMissing) {
toDelete.push({
rowId: row.id,
agentId: row.agentId,
taskKey: row.taskKey,
sessionId: input.sessionId,
lastAssistantId: null,
jsonlPath: classification.jsonlPath ?? null,
reason: "missing_jsonl",
});
} else {
log(
`[skip] missing jsonl (use --delete-missing-jsonl to clear) row=${row.id} agent=${row.agentId} task=${row.taskKey} jsonl=${classification.jsonlPath}`,
);
}
break;
}
case "poisoned":
summary.poisoned += 1;
toDelete.push({
rowId: row.id,
agentId: row.agentId,
taskKey: row.taskKey,
sessionId: input.sessionId,
lastAssistantId: classification.lastAssistantId,
jsonlPath: classification.jsonlPath ?? null,
reason: "poisoned",
});
break;
}
}
if (toDelete.length === 0) {
log("No poisoned rows found.");
} else {
log(`Found ${toDelete.length} rows to clear:`);
for (const pair of toDelete) {
log(
` - row=${pair.rowId} agent=${pair.agentId} task=${pair.taskKey} sessionId=${pair.sessionId} reason=${pair.reason} lastAssistantId=${pair.lastAssistantId ?? "n/a"}`,
);
}
}
if (!args.dryRun && toDelete.length > 0) {
// Single-statement delete with ids list; safer than a per-row loop and
// avoids races against concurrent heartbeat writes that might re-touch
// the same (agentId, taskKey).
const ids = toDelete.map((pair) => pair.rowId);
const result = await db
.delete(agentTaskSessions)
.where(sql`${agentTaskSessions.id} IN (${sql.join(ids.map((id) => sql`${id}`), sql`, `)})`)
.returning({ id: agentTaskSessions.id });
summary.deleted = result.length;
log(`Deleted ${result.length} rows.`);
}
summary.healedPairs = toDelete;
if (args.json) {
process.stdout.write(`${JSON.stringify(summary, null, 2)}\n`);
} else {
log("--- Summary ---");
log(
`scanned=${summary.scanned} healthy=${summary.healthy} poisoned=${summary.poisoned} missingJsonl=${summary.missingJsonl} noAssistantEntries=${summary.noAssistantEntries} skippedRemote=${summary.skippedRemote} skippedNoSession=${summary.skippedNoSession} unreadable=${summary.unreadable} deleted=${summary.deleted} dryRun=${summary.dryRun}`,
);
}
} finally {
await closableDb.$client?.end?.({ timeout: 5 }).catch(() => undefined);
}
}
// Allow `import { ... } from "./clean-poisoned-claude-sessions.js"` from tests
// without triggering the CLI side-effect. Node sets `import.meta.main` on
// direct invocation; fall back to argv[1] comparison for older runtimes.
const invokedDirectly =
typeof process !== "undefined" &&
Array.isArray(process.argv) &&
process.argv[1] !== undefined &&
path.resolve(process.argv[1]) === path.resolve(new URL(import.meta.url).pathname);
if (invokedDirectly) {
main(process.argv.slice(2)).catch((error) => {
process.stderr.write(
`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`,
);
process.exit(1);
});
}