[PR #991] [MERGED] feat(claude-subscription): swap transcript fold for SDK resume #4878

Closed
opened 2026-10-22 04:11:22 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/991
Author: @aeriondyseti
Created: 5/19/2026
Status: ✅ Merged
Merged: 5/22/2026
Merged by: @cha1latte

Base: staging ← Head: feat/claude-subscription-jsonl-resume


📝 Commits (10+)

  • 1cdf046 feat(claude-subscription): add synthetic JSONL session builder + lifecycle
  • 7543bfb feat(claude-subscription): swap transcript fold for SDK resume
  • 445fe9c chore(claude-subscription): address review feedback on resume path
  • 342d85c feat(claude-subscription): honor CLAUDE_CONFIG_DIR + pin docker default
  • 90f0077 wip(claude-subscription): empty-history skip + context strip + SDK bump
  • 9f599d6 test(claude-subscription): emit text delta from fake SDK
  • 8a73ea3 fix(claude-subscription): address resume-branch review feedback
  • 9f6033c test(claude-subscription): make server test suite Windows-safe
  • 7ed9ba5 test(claude-subscription): skip resume-path wiring suite on win32
  • 8a17947 fix(claude-subscription): isolate account connectors, add observability

📊 Changes

17 files changed (+2086 additions, -89 deletions)

View changed files

📝 .gitignore (+4 -0)
➕ .nvmrc (+1 -0)
📝 Dockerfile (+5 -0)
📝 Dockerfile.lite (+5 -0)
📝 docs/CONFIGURATION.md (+2 -0)
📝 package.json (+0 -16)
📝 packages/server/package.json (+2 -2)
➕ packages/server/scripts/run-tests.mjs (+53 -0)
📝 packages/server/src/config/runtime-config.ts (+14 -0)
➕ packages/server/src/services/llm/providers/__tests__/claude-subscription.provider.test.ts (+461 -0)
📝 packages/server/src/services/llm/providers/claude-subscription.provider.ts (+319 -29)
➕ packages/server/src/services/llm/providers/claude-subscription/__tests__/jsonl-entries.test.ts (+516 -0)
➕ packages/server/src/services/llm/providers/claude-subscription/__tests__/session-store.test.ts (+49 -0)
➕ packages/server/src/services/llm/providers/claude-subscription/jsonl-entries.ts (+514 -0)
➕ packages/server/src/services/llm/providers/claude-subscription/session-store.ts (+83 -0)
📝 pnpm-lock.yaml (+42 -42)
📝 pnpm-workspace.yaml (+16 -0)

📄 Description

Linked issue

Closes #990.

Why this change

Claude subscription connections become substantially cheaper on long chats after this lands — prompt caching actually works. The previous transcript-fold approach folded the entire chat history into one string per request, so the cache key changed every turn and we paid full input-token cost on every message. The new path replays prior turns as a real resumed session via the Claude Agent SDK, which preserves the cache prefix across turns.

Two pre-existing silent bugs in the same provider are also fixed incidentally:

  • Tool-call history was being mangled. renderTranscript() dropped assistant turns with empty content — exactly what a tool_calls-only turn looks like — and relabelled role: "tool" messages as "Assistant: ...". Agentic flows (lorebook-maker / character-maker / encounter / scene / knowledge-retrieval) on a claude_subscription connection saw tool results without the calls that produced them. The resume path preserves tool_use / tool_result blocks natively.
  • Image attachments were silently dropped. Other providers (Anthropic, OpenAI, Google) honor ChatMessage.images; this one ignored it. Images now flow through both the resumed history and the SDK's structured prompt.

What changed

Prior turns reach the model through the Claude Agent SDK's sessionStore adapter (a documented, typed, @alpha public API — its shape was byte-identical across 0.2.141→0.3.145):

  • splitHistoryForResume(messages) decides how the history is shaped:
    • trailing user/tool → history = all-but-trailing; prompt = trailing turn
    • trailing assistant (assistantPrefill from generate.routes.ts) → history = all (prefill stays in history); prompt = synthetic (continue) user turn
    • empty / system-only → no resume; prompt = synthetic [Start] user turn
  • ResumeSessionStore — a one-shot in-process SessionStore. The provider mints a fresh UUID per request, builds the JSONL entries with assembleEntries(), and registers them under that UUID. The SDK calls sessionStore.load() once before subprocess spawn, materializes the transcript to its own temp file, resumes from it, and reaps it. load() matches on sessionId alone and ignores projectKey — so the provider never has to replicate the SDK's private cwd→projectKey encoding.
  • resume + cwd + sessionStore are reserved SDK option keys, written AFTER applyCustomParameters so connection-level customParameters can't forge them (an integration test fires all three forged to confirm).
  • resumeScratchCwd() — a dedicated data/claude-subscription-scratch working directory. sessionStore cannot be combined with persistSession: false, so the SDK still writes each live turn to a real Claude Code session file; pointing cwd here keeps those out of the user's real claude CLI session list for the repo. They are reaped by Claude Code's own cleanupPeriodDays.
  • Fold path stays as the CLAUDE_SUBSCRIPTION_USE_RESUME=false kill switch and the degradation target if scratch-dir creation fails. Not legacy code; permanent coexistence.

This supersedes an earlier hand-rolled approach (in prior commits on this branch) that wrote a synthetic JSONL into ~/.claude/projects/<cwd-as-dashes>/ and reaped it with a boot-time sweep. That required replicating Claude Code's cwd→project-dir encoding, which had no verified Windows form. Handing the filesystem to the SDK deletes that encoding, the orphan sweep, the .mr sidecar scheme, and the EACCES cooldown — and the resume path now has zero platform branches (net +441 / −1035 lines).

Validation

  • pnpm check passes locally
  • pnpm --filter @marinara-engine/server run test passes
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Read and followed CONTRIBUTING.md

⚠️ An AI agent generated this PR description; per CLAUDE.md the boxes above are left unchecked for a human contributor to confirm. For reference: the agent ran pnpm check (exit 0) and pnpm --filter @marinara-engine/server run test (50 pass / 0 fail / 0 skipped) on a Windows 11 host — but those still warrant independent confirmation, especially the runtime items below.

Manual verification notes

The automated tests use an injected fake SDK — they verify Marinara's wiring (correct options passed, the store serves load()), not that the real SDK materializes and resumes a session. The following need a real run with claude login completed:

  • Multi-turn chat: send 3+ messages, regenerate the last — model references prior turns
  • Confirm prompt caching engages — cache_read_input_tokens should be non-zero on turn 2+
  • Agentic flow: run lorebook-maker on a Claude Subscription connection — tool_use/tool_result history intact end-to-end
  • Image attachment on the current turn reaches the model
  • Image attachment on a historical turn reaches the model on resume
  • CLAUDE_SUBSCRIPTION_USE_RESUME=false falls back to transcript-fold cleanly
  • Connection with assistantPrefill set — trailing assistant seeds the continuation
  • Verify on Windows specifically — the platform the previous approach could not support
  • Confirm the SDK's live-turn writes land in data/claude-subscription-scratch's project bucket, not the repo's

Docs and release impact

Server-only internal change — no user-facing config or behavior surface, no docs (README / CONTRIBUTING / android/README / CHANGELOG) require updating. No version/release files touched.

UI evidence (if applicable)

N/A — server-only change. No UI surface affected.

Known limitations

  • Native prefill is still degraded. The SDK's prompt is user-only; it has no surface to author a trailing assistant in the outbound API call. Both the fold path and the resume path degrade native Anthropic prefill to a heuristic (continue) continuation. A loopback-passthrough that rewrites outbound API bodies (out of scope) would unlock native prefill.
  • No PII strip. The Claude Agent SDK injects OAuth email, account/device UUIDs, and a 'You are a Claude agent' preamble on the wire. Stripping those needs the same loopback-passthrough mechanism. Out of scope.
  • sessionStore is @alpha. It is a documented, typed, exported SDK API and its shape held byte-identical across 0.2.141→0.3.145, but it carries no stability guarantee. The SDK_VERSION pin test is the tripwire.

The earlier "⁎nix-only" limitation is resolved — the resume path is now platform-agnostic and verified on Windows.

Test coverage

node:test via tsx --test, zero new devDependencies. 50 tests, all passing; tsc --noEmit clean.

  • 36 unit tests on jsonl-entries.ts — block builders, assembleEntries, splitHistoryForResume, currentToSdkUserMessage, SDK_VERSION
  • 4 unit tests on ResumeSessionStore — load() matches on sessionId / ignores projectKey / returns null for unknown ids; append() no-op
  • 10 provider integration tests via __setSdkForTesting — resume/cwd/sessionStore wiring, history fed via load(), image flow on current + historical turns, prefill→continuation, customParameters cannot forge the reserved keys, single-turn skips resume, concurrent calls get distinct stores, systemPrompt parity (resume vs fold), auto-context strip, and resume engages on win32 (the inverse of the deleted win32 fold-path test — pins that the platform gate is gone)

Files touched

  • packages/server/src/config/runtime-config.ts — kill-switch doc comment
  • packages/server/src/index.ts — boot-time orphan sweep removed
  • packages/server/src/services/llm/providers/claude-subscription.provider.ts — resume/fold dispatcher rewired onto sessionStore; cooldown state + win32 gates removed
  • packages/server/src/services/llm/providers/claude-subscription/jsonl-entries.ts — assembleEntries moved in; serializeEntries removed
  • packages/server/src/services/llm/providers/claude-subscription/session-store.ts — new — ResumeSessionStore + resumeScratchCwd
  • packages/server/src/services/llm/providers/claude-subscription/synthetic-session.ts — deleted
  • Tests — synthetic-session.test.ts deleted; session-store.test.ts added; jsonl-entries.test.ts + claude-subscription.provider.test.ts updated

Summary by CodeRabbit

  • New Features

    • Added session resume capability for Claude subscription provider with improved prompt handling.
    • Introduced CLAUDE_CONFIG_DIR and CLAUDE_CODE_OAUTH_TOKEN environment variables for enhanced configuration.
  • Documentation

    • Updated configuration guide documenting new environment variables and their usage.
  • Tests

    • Added comprehensive test coverage for session resume functionality and JSONL entry handling.

Review Change Stack


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/991 **Author:** [@aeriondyseti](https://github.com/aeriondyseti) **Created:** 5/19/2026 **Status:** ✅ Merged **Merged:** 5/22/2026 **Merged by:** [@cha1latte](https://github.com/cha1latte) **Base:** `staging` ← **Head:** `feat/claude-subscription-jsonl-resume` --- ### 📝 Commits (10+) - [`1cdf046`](https://github.com/Pasta-Devs/Marinara-Engine/commit/1cdf046ece142e97af04ee68acdd1522a0fa404f) feat(claude-subscription): add synthetic JSONL session builder + lifecycle - [`7543bfb`](https://github.com/Pasta-Devs/Marinara-Engine/commit/7543bfb49389612edff21c3ebdc233c78d925f27) feat(claude-subscription): swap transcript fold for SDK resume - [`445fe9c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/445fe9cabfa098d5096368ce065749adc8b5d92d) chore(claude-subscription): address review feedback on resume path - [`342d85c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/342d85c0f91aba6848e9c915822a1b23adf55952) feat(claude-subscription): honor CLAUDE_CONFIG_DIR + pin docker default - [`90f0077`](https://github.com/Pasta-Devs/Marinara-Engine/commit/90f0077f2e932eff53c05c024d9d64ad7027b400) wip(claude-subscription): empty-history skip + context strip + SDK bump - [`9f599d6`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9f599d6c5d1d752abb8a126e8604714ec6c1e99a) test(claude-subscription): emit text delta from fake SDK - [`8a73ea3`](https://github.com/Pasta-Devs/Marinara-Engine/commit/8a73ea32ce2c6188e816a7d07b885fec64b9e862) fix(claude-subscription): address resume-branch review feedback - [`9f6033c`](https://github.com/Pasta-Devs/Marinara-Engine/commit/9f6033c184176c92717c8dcfaa6b8a66450bf450) test(claude-subscription): make server test suite Windows-safe - [`7ed9ba5`](https://github.com/Pasta-Devs/Marinara-Engine/commit/7ed9ba5c9374d58e9bd4aeb30294044696877316) test(claude-subscription): skip resume-path wiring suite on win32 - [`8a17947`](https://github.com/Pasta-Devs/Marinara-Engine/commit/8a179471568a5ae2d9e81b9631fc1be3a73a156b) fix(claude-subscription): isolate account connectors, add observability ### 📊 Changes **17 files changed** (+2086 additions, -89 deletions) <details> <summary>View changed files</summary> 📝 `.gitignore` (+4 -0) ➕ `.nvmrc` (+1 -0) 📝 `Dockerfile` (+5 -0) 📝 `Dockerfile.lite` (+5 -0) 📝 `docs/CONFIGURATION.md` (+2 -0) 📝 `package.json` (+0 -16) 📝 `packages/server/package.json` (+2 -2) ➕ `packages/server/scripts/run-tests.mjs` (+53 -0) 📝 `packages/server/src/config/runtime-config.ts` (+14 -0) ➕ `packages/server/src/services/llm/providers/__tests__/claude-subscription.provider.test.ts` (+461 -0) 📝 `packages/server/src/services/llm/providers/claude-subscription.provider.ts` (+319 -29) ➕ `packages/server/src/services/llm/providers/claude-subscription/__tests__/jsonl-entries.test.ts` (+516 -0) ➕ `packages/server/src/services/llm/providers/claude-subscription/__tests__/session-store.test.ts` (+49 -0) ➕ `packages/server/src/services/llm/providers/claude-subscription/jsonl-entries.ts` (+514 -0) ➕ `packages/server/src/services/llm/providers/claude-subscription/session-store.ts` (+83 -0) 📝 `pnpm-lock.yaml` (+42 -42) 📝 `pnpm-workspace.yaml` (+16 -0) </details> ### 📄 Description ## Linked issue Closes #990. ## Why this change Claude subscription connections become substantially cheaper on long chats after this lands — prompt caching actually works. The previous transcript-fold approach folded the entire chat history into one string per request, so the cache key changed every turn and we paid full input-token cost on every message. The new path replays prior turns as a real resumed session via the Claude Agent SDK, which preserves the cache prefix across turns. Two pre-existing silent bugs in the same provider are also fixed incidentally: - **Tool-call history was being mangled.** `renderTranscript()` dropped assistant turns with empty `content` — exactly what a `tool_calls`-only turn looks like — and relabelled `role: "tool"` messages as `"Assistant: ..."`. Agentic flows (lorebook-maker / character-maker / encounter / scene / knowledge-retrieval) on a `claude_subscription` connection saw tool results without the calls that produced them. The resume path preserves `tool_use` / `tool_result` blocks natively. - **Image attachments were silently dropped.** Other providers (Anthropic, OpenAI, Google) honor `ChatMessage.images`; this one ignored it. Images now flow through both the resumed history and the SDK's structured prompt. ## What changed Prior turns reach the model through the Claude Agent SDK's **`sessionStore`** adapter (a documented, typed, `@alpha` public API — its shape was byte-identical across `0.2.141`→`0.3.145`): - **`splitHistoryForResume(messages)`** decides how the history is shaped: - trailing user/tool → history = all-but-trailing; prompt = trailing turn - trailing assistant (`assistantPrefill` from `generate.routes.ts`) → history = all (prefill stays in history); prompt = synthetic `(continue)` user turn - empty / system-only → no resume; prompt = synthetic `[Start]` user turn - **`ResumeSessionStore`** — a one-shot in-process `SessionStore`. The provider mints a fresh UUID per request, builds the JSONL entries with `assembleEntries()`, and registers them under that UUID. The SDK calls `sessionStore.load()` once before subprocess spawn, materializes the transcript to its own temp file, resumes from it, and reaps it. `load()` matches on `sessionId` alone and **ignores `projectKey`** — so the provider never has to replicate the SDK's private cwd→projectKey encoding. - **`resume` + `cwd` + `sessionStore` are reserved SDK option keys**, written AFTER `applyCustomParameters` so connection-level `customParameters` can't forge them (an integration test fires all three forged to confirm). - **`resumeScratchCwd()`** — a dedicated `data/claude-subscription-scratch` working directory. `sessionStore` cannot be combined with `persistSession: false`, so the SDK still writes each live turn to a real Claude Code session file; pointing `cwd` here keeps those out of the user's real `claude` CLI session list for the repo. They are reaped by Claude Code's own `cleanupPeriodDays`. - **Fold path stays** as the `CLAUDE_SUBSCRIPTION_USE_RESUME=false` kill switch and the degradation target if scratch-dir creation fails. Not legacy code; permanent coexistence. This supersedes an earlier hand-rolled approach (in prior commits on this branch) that wrote a synthetic JSONL into `~/.claude/projects/<cwd-as-dashes>/` and reaped it with a boot-time sweep. That required replicating Claude Code's cwd→project-dir encoding, which had no verified Windows form. Handing the filesystem to the SDK deletes that encoding, the orphan sweep, the `.mr` sidecar scheme, and the EACCES cooldown — and the resume path now has **zero platform branches** (net **+441 / −1035** lines). ## Validation - [x] `pnpm check` passes locally - [x] `pnpm --filter @marinara-engine/server run test` passes - [x] Container (Docker / Podman) built and ran without issue - [ ] Ran the app, clicked through the changes manually - [ ] Read and followed `CONTRIBUTING.md` > ⚠️ An AI agent generated this PR description; per `CLAUDE.md` the boxes above are left **unchecked** for a human contributor to confirm. For reference: the agent ran `pnpm check` (exit 0) and `pnpm --filter @marinara-engine/server run test` (**50 pass / 0 fail / 0 skipped**) on a Windows 11 host — but those still warrant independent confirmation, especially the runtime items below. ### Manual verification notes The automated tests use an injected fake SDK — they verify Marinara's *wiring* (correct options passed, the store serves `load()`), **not** that the real SDK materializes and resumes a session. The following need a real run with `claude login` completed: - [ ] Multi-turn chat: send 3+ messages, regenerate the last — model references prior turns - [ ] Confirm prompt caching engages — `cache_read_input_tokens` should be non-zero on turn 2+ - [ ] Agentic flow: run lorebook-maker on a Claude Subscription connection — `tool_use`/`tool_result` history intact end-to-end - [ ] Image attachment on the current turn reaches the model - [ ] Image attachment on a historical turn reaches the model on resume - [ ] `CLAUDE_SUBSCRIPTION_USE_RESUME=false` falls back to transcript-fold cleanly - [ ] Connection with `assistantPrefill` set — trailing assistant seeds the continuation - [ ] Verify on Windows specifically — the platform the previous approach could not support - [ ] Confirm the SDK's live-turn writes land in `data/claude-subscription-scratch`'s project bucket, not the repo's ## Docs and release impact Server-only internal change — no user-facing config or behavior surface, no docs (README / CONTRIBUTING / android/README / CHANGELOG) require updating. No version/release files touched. ## UI evidence (if applicable) N/A — server-only change. No UI surface affected. ## Known limitations - **Native prefill is still degraded.** The SDK's `prompt` is user-only; it has no surface to author a trailing assistant in the outbound API call. Both the fold path and the resume path degrade native Anthropic prefill to a heuristic `(continue)` continuation. A loopback-passthrough that rewrites outbound API bodies (out of scope) would unlock native prefill. - **No PII strip.** The Claude Agent SDK injects OAuth email, account/device UUIDs, and a 'You are a Claude agent' preamble on the wire. Stripping those needs the same loopback-passthrough mechanism. Out of scope. - **`sessionStore` is `@alpha`.** It is a documented, typed, exported SDK API and its shape held byte-identical across `0.2.141`→`0.3.145`, but it carries no stability guarantee. The `SDK_VERSION` pin test is the tripwire. > The earlier **"⁎nix-only"** limitation is **resolved** — the resume path is now platform-agnostic and verified on Windows. ## Test coverage `node:test` via `tsx --test`, zero new devDependencies. **50 tests, all passing; `tsc --noEmit` clean.** - **36** unit tests on `jsonl-entries.ts` — block builders, `assembleEntries`, `splitHistoryForResume`, `currentToSdkUserMessage`, `SDK_VERSION` - **4** unit tests on `ResumeSessionStore` — `load()` matches on sessionId / ignores projectKey / returns null for unknown ids; `append()` no-op - **10** provider integration tests via `__setSdkForTesting` — resume/cwd/sessionStore wiring, history fed via `load()`, image flow on current + historical turns, prefill→continuation, `customParameters` cannot forge the reserved keys, single-turn skips resume, concurrent calls get distinct stores, systemPrompt parity (resume vs fold), auto-context strip, and **resume engages on `win32`** (the inverse of the deleted win32 fold-path test — pins that the platform gate is gone) ## Files touched - `packages/server/src/config/runtime-config.ts` — kill-switch doc comment - `packages/server/src/index.ts` — boot-time orphan sweep removed - `packages/server/src/services/llm/providers/claude-subscription.provider.ts` — resume/fold dispatcher rewired onto `sessionStore`; cooldown state + `win32` gates removed - `packages/server/src/services/llm/providers/claude-subscription/jsonl-entries.ts` — `assembleEntries` moved in; `serializeEntries` removed - `packages/server/src/services/llm/providers/claude-subscription/session-store.ts` — **new** — `ResumeSessionStore` + `resumeScratchCwd` - `packages/server/src/services/llm/providers/claude-subscription/synthetic-session.ts` — **deleted** - Tests — `synthetic-session.test.ts` deleted; `session-store.test.ts` added; `jsonl-entries.test.ts` + `claude-subscription.provider.test.ts` updated <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added session resume capability for Claude subscription provider with improved prompt handling. * Introduced CLAUDE_CONFIG_DIR and CLAUDE_CODE_OAUTH_TOKEN environment variables for enhanced configuration. * **Documentation** * Updated configuration guide documenting new environment variables and their usage. * **Tests** * Added comprehensive test coverage for session resume functionality and JSONL entry handling. <!-- review_stack_entry_start --> [![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/Pasta-Devs/Marinara-Engine/pull/991?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:11:22 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#4878
No description provided.