Files
PaperClipAI/server/src/__tests__/adapter-session-codecs.test.ts
T
b8fb81dee9 fix(gemini-local): treat token-overflow as a fresh-session signal (#4932)
## Thinking Path

The same 2026-04-30 audit that produced PR #4118 (`Invalid session`
regex extension) and the ENOTFOUND classifier (#4931) identified a third
stuck-session pattern: **13 failures in 7 days, all on a single agent
(Ernest)**, with stderr matching:

```
_ApiError: {"error":{"code":400,"message":"The input token count exceeds
the maximum number of tokens allowed 1048576","status":"INVALID_ARGUMENT"}}
  at ChatCompressionService.compress
```

The root cause is that gemini-cli's `ChatCompressionService` blew the 1M
token context limit **during its compression step itself**. Resuming the
same session ID will hit the same wall on the next attempt — the session
is effectively dead the same way it is when "Invalid session identifier"
fires (PR #4118).

## What Changed

Extends the `isGeminiUnknownSessionError` regex in `parse.ts` with two
phrases:
- `exceeds\s+the\s+maximum\s+number\s+of\s+tokens`
- `input\s+token\s+count\s+exceeds`

Both trigger the **existing** fresh-session retry path in
`execute.ts:596` — no new code path. Same extension pattern as PR #4118.

## Verification

- `npx vitest run --project @paperclipai/adapter-gemini-local` → 14/14
pass (11 in `parse.test.ts` + 3 existing in `execute.remote.test.ts`)
- 2 new tests cover the token-overflow patterns
- `pnpm --filter @paperclipai/adapter-gemini-local typecheck` → clean
- Audit query against `heartbeat_runs.stderr_excerpt` confirms regex
matches all 13 occurrences

## Stacking

This PR is stacked on top of #4931 (the ENOTFOUND classifier) which adds
the `parse.test.ts` file. If #4931 merges first, this PR's diff is just
the regex + 2 tests. If this PR is reviewed first, please merge #4931
first to avoid touching the same test scaffolding twice.

## Risks

- **Low.** Single-line regex extension. No new code paths.
- The session-reset path is well-trodden (PR #4118 in flight).
- If a non-Gemini caller produces a stderr containing "exceeds the
maximum number of tokens" by coincidence, they would trigger one
unnecessary fresh-session retry. Not plausible in the gemini-cli output
context where this stderr is sourced.

## Model Used

Claude Opus 4.7 (1M context), Anthropic SDK via Claude Code CLI.

## Checklist

- [x] Thinking path traces from audit data to single-line regex change
- [x] Model specified
- [x] No duplicate of planned core work
- [x] Tests pass locally
- [x] Tests added (2 new)
- [x] N/A — server-side regex
- [x] Internal pattern; no docs change
- [x] Risks documented
- [x] Will address Greptile + reviewer comments before merge
- [x] I searched the GitHub PR list for similar PRs and confirmed this
is not a duplicate (related: #4118 covers the "Invalid session
identifier" regex; this PR extends the same regex with token-overflow
phrases)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Devin Foley <devin@paperclip.ing>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-06-10 19:10:29 -07:00

242 lines
7.0 KiB
TypeScript

import { describe, expect, it } from "vitest";
import { sessionCodec as claudeSessionCodec } from "@paperclipai/adapter-claude-local/server";
import { sessionCodec as codexSessionCodec, isCodexUnknownSessionError } from "@paperclipai/adapter-codex-local/server";
import {
sessionCodec as cursorSessionCodec,
isCursorUnknownSessionError,
} from "@paperclipai/adapter-cursor-local/server";
import {
sessionCodec as geminiSessionCodec,
isGeminiSessionUnrecoverableError,
} from "@paperclipai/adapter-gemini-local/server";
import {
sessionCodec as opencodeSessionCodec,
isOpenCodeUnknownSessionError,
} from "@paperclipai/adapter-opencode-local/server";
import { sessionCodec as acpxSessionCodec } from "@paperclipai/adapter-acpx-local/server";
describe("adapter session codecs", () => {
it("normalizes claude session params with cwd", () => {
const parsed = claudeSessionCodec.deserialize({
session_id: "claude-session-1",
folder: "/tmp/workspace",
prompt_bundle_key: "bundle-1",
});
expect(parsed).toEqual({
sessionId: "claude-session-1",
cwd: "/tmp/workspace",
promptBundleKey: "bundle-1",
});
const serialized = claudeSessionCodec.serialize(parsed);
expect(serialized).toEqual({
sessionId: "claude-session-1",
cwd: "/tmp/workspace",
promptBundleKey: "bundle-1",
});
expect(claudeSessionCodec.getDisplayId?.(serialized ?? null)).toBe("claude-session-1");
});
it("normalizes codex session params with cwd", () => {
const parsed = codexSessionCodec.deserialize({
sessionId: "codex-session-1",
cwd: "/tmp/codex",
});
expect(parsed).toEqual({
sessionId: "codex-session-1",
cwd: "/tmp/codex",
});
const serialized = codexSessionCodec.serialize(parsed);
expect(serialized).toEqual({
sessionId: "codex-session-1",
cwd: "/tmp/codex",
});
expect(codexSessionCodec.getDisplayId?.(serialized ?? null)).toBe("codex-session-1");
});
it("normalizes opencode session params with cwd", () => {
const parsed = opencodeSessionCodec.deserialize({
sessionID: "opencode-session-1",
cwd: "/tmp/opencode",
});
expect(parsed).toEqual({
sessionId: "opencode-session-1",
cwd: "/tmp/opencode",
});
const serialized = opencodeSessionCodec.serialize(parsed);
expect(serialized).toEqual({
sessionId: "opencode-session-1",
cwd: "/tmp/opencode",
});
expect(opencodeSessionCodec.getDisplayId?.(serialized ?? null)).toBe("opencode-session-1");
});
it("normalizes cursor session params with cwd", () => {
const parsed = cursorSessionCodec.deserialize({
session_id: "cursor-session-1",
cwd: "/tmp/cursor",
});
expect(parsed).toEqual({
sessionId: "cursor-session-1",
cwd: "/tmp/cursor",
});
const serialized = cursorSessionCodec.serialize(parsed);
expect(serialized).toEqual({
sessionId: "cursor-session-1",
cwd: "/tmp/cursor",
});
expect(cursorSessionCodec.getDisplayId?.(serialized ?? null)).toBe("cursor-session-1");
});
it("normalizes gemini session params with cwd", () => {
const parsed = geminiSessionCodec.deserialize({
session_id: "gemini-session-1",
cwd: "/tmp/gemini",
});
expect(parsed).toEqual({
sessionId: "gemini-session-1",
cwd: "/tmp/gemini",
});
const serialized = geminiSessionCodec.serialize(parsed);
expect(serialized).toEqual({
sessionId: "gemini-session-1",
cwd: "/tmp/gemini",
});
expect(geminiSessionCodec.getDisplayId?.(serialized ?? null)).toBe("gemini-session-1");
});
it("preserves acpx session params required for compatibility checks", () => {
const parsed = acpxSessionCodec.deserialize({
sessionKey: "paperclip:company:agent:task:fingerprint",
runtimeSessionName: "runtime-session-1",
acpxRecordId: "record-1",
acpSessionId: "acp-session-1",
agentSessionId: "agent-session-1",
agent: "claude",
cwd: "/tmp/acpx",
mode: "persistent",
stateDir: "/tmp/acpx-state",
configFingerprint: "fingerprint",
workspaceId: "workspace-1",
repoUrl: "https://example.com/repo.git",
repoRef: "main",
remoteExecution: {
environmentId: "environment-1",
leaseId: "lease-1",
},
});
expect(parsed).toMatchObject({
sessionKey: "paperclip:company:agent:task:fingerprint",
runtimeSessionName: "runtime-session-1",
acpxRecordId: "record-1",
acpSessionId: "acp-session-1",
agentSessionId: "agent-session-1",
agent: "claude",
cwd: "/tmp/acpx",
mode: "persistent",
stateDir: "/tmp/acpx-state",
configFingerprint: "fingerprint",
workspaceId: "workspace-1",
repoUrl: "https://example.com/repo.git",
repoRef: "main",
remoteExecution: {
environmentId: "environment-1",
leaseId: "lease-1",
},
});
expect(acpxSessionCodec.serialize(parsed)).toEqual(parsed);
expect(acpxSessionCodec.getDisplayId?.(parsed)).toBe("runtime-session-1");
});
});
describe("codex resume recovery detection", () => {
it("detects unknown session errors from codex output", () => {
expect(
isCodexUnknownSessionError(
'{"type":"error","message":"Unknown session id abc"}',
"",
),
).toBe(true);
expect(
isCodexUnknownSessionError(
"",
"thread 123 not found",
),
).toBe(true);
expect(
isCodexUnknownSessionError(
'{"type":"result","ok":true}',
"",
),
).toBe(false);
});
});
describe("opencode resume recovery detection", () => {
it("detects unknown session errors from opencode output", () => {
expect(
isOpenCodeUnknownSessionError(
"",
"NotFoundError: Resource not found: /Users/test/.local/share/opencode/storage/session/proj/ses_missing.json",
),
).toBe(true);
expect(
isOpenCodeUnknownSessionError(
"{\"type\":\"step_finish\",\"part\":{\"reason\":\"stop\"}}",
"",
),
).toBe(false);
});
});
describe("cursor resume recovery detection", () => {
it("detects unknown session errors from cursor output", () => {
expect(
isCursorUnknownSessionError(
"",
"Error: unknown session id abc",
),
).toBe(true);
expect(
isCursorUnknownSessionError(
"",
"chat abc not found",
),
).toBe(true);
expect(
isCursorUnknownSessionError(
"{\"type\":\"result\",\"subtype\":\"success\"}",
"",
),
).toBe(false);
});
});
describe("gemini resume recovery detection", () => {
it("detects unknown session errors from gemini output", () => {
expect(
isGeminiSessionUnrecoverableError(
"",
"unknown session id abc",
),
).toBe(true);
expect(
isGeminiSessionUnrecoverableError(
"",
"checkpoint latest not found",
),
).toBe(true);
expect(
isGeminiSessionUnrecoverableError(
"{\"type\":\"result\",\"subtype\":\"success\"}",
"",
),
).toBe(false);
});
});