Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Create conversation adapters for importing AI chat history from different tools (Claude Code, Cursor, Warp, Codex, etc.). Covers the adapter.Adapter interface, caching strategies, incremental parsing, watch/FD management, and performance standards. Use when creating a new adapter, modifying adapter behavior, or debugging adapter performance issues. See references/ for Cursor DB and Warp SQLite schema details.
.claude/skills/marcus-create-adapter/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-14 | ✗→✓ | ▲ Improved | 134% | 0% |
| case-03 | ✗→✓ | ▲ Improved | 66% | 0% |
| case-01 | ✗→✓ | ▲ Improved | 71% | 0% |
| case-02 | ✗→✓ | ▲ Improved | 166% | 0% |
| case-04 | ✗→✓ | ▲ Improved | 114% | 0% |
Adapters are the largest performance risk in Sidecar. Conversations refresh on watch events in a hot path that runs continuously during active sessions:
watch event -> coalescer -> session refresh -> adapter.Sessions() -> metadata parsingIf an adapter does full directory scans and full-file reparses on every change, CPU and FD usage spike quickly.
Study these before writing a new adapter:
internal/adapter/claudecode - Incremental JSONL parsing, targeted refreshinternal/adapter/codex - Directory cache, two-pass metadata parsing, global watch scopeinternal/adapter/cursor - SQLite/WAL-aware cache invalidation, FD-safe DB accessinternal/adapter/pi - Global scope, JSONL, CWD-based filtering, session classification, message prefix strippingAll adapters implement adapter.Adapter:
gotype Adapter interface { ID() string Name() string Icon() string Detect(projectRoot string) (bool, error) Capabilities() CapabilitySet Sessions(projectRoot string) ([]Session, error) Messages(sessionID string) ([]Message, error) Usage(sessionID string) (*UsageStats, error) Watch(projectRoot string) (<-chan Event, io.Closer, error) }
Every session from Sessions() must set:
ID, NameAdapterID, AdapterName, AdapterIconCreatedAt, UpdatedAtMessageCount, FileSizeFileSize is used for dynamic debounce and huge-session auto-reload protection.
Treat source identity separately from lineage. Use the source's durable thread/session ID for Session.ID; parent, root, fork, or lineage IDs describe relationships and must not collapse distinct sessions. Decode metadata fields defensively when the source has emitted multiple shapes over time (for example, a string in one version and an object in another).
Set Session.Path only when Sidecar should use tiered file watching for that adapter:
Path to absolute file path — this opts into TieredWatcher with HOT/COLD/FROZEN tiersWatch() with WAL-aware invalidation; do not set Path unless tiered watching covers your write surfaceFROZEN tier: File-based sessions with Path set automatically benefit from the FROZEN tier. Sessions unchanged for 24 hours (FrozenThreshold) are excluded from cold polling entirely — zero syscalls. They unfreeze when promoted to HOT (e.g., user selects the session). This is critical for adapters with thousands of session files; without it, pollColdSessions() does one os.Stat() per file every 30 seconds.
Minimum cache keys:
path + size + modTimepath + size + modTimeUse bounded LRU behavior for every cache and index. Prune stale paths. Assume caches evict independently: a hit in one cache must restore any derived state required by another, or the authoritative source must remain available so eviction cannot change results such as aggregate usage or ID-to-path resolution.
For JSONL/event-log adapters:
When incremental metadata parse is impractical:
When the source owns a metadata index, prefer its read-only index over scanning large event logs. Probe the schema and required columns before use, open it read-only with bounded/FD-safe access, and fall back to event-log discovery when it is missing, locked, or incompatible. The source index is an adapter seam, not a second source of truth to mutate.
Resolve project path once per Sessions() call (Abs/EvalSymlinks), reuse for all matches.
Never return cache-owned slices/maps directly. Copy message/session structures to avoid mutation bugs.
For SQLite adapters:
mode=ro)SetMaxOpenConns(1), SetMaxIdleConns(0)Messages() callUsage and similar cumulative facts may arrive as repeated totals or deltas. Define the source semantics, retain the authoritative aggregate across incremental parsing, and include all components the source exposes. Do not reconstruct a partial aggregate from whichever message cache entry survived eviction.
Do not watch per-session files when directory-level watch gives equivalent signals.
If adapter watches a global path (same location regardless of worktree):
gofunc (a *Adapter) WatchScope() adapter.WatchScope { return adapter.WatchScopeGlobal }
This prevents duplicate watchers across worktrees.
Watch events should include session ID for targeted refresh (avoids full reloads).
select { case ch <- evt: default: }File-based adapters that set Session.Path get TieredWatcher's three-tier system (HOT → COLD → FROZEN). Sessions unchanged for 24h are frozen and cost zero polling overhead. This is the primary defense against CPU spikes with thousands of session files. If your adapter has file-based sessions, always set Path — the FROZEN tier scales automatically.
All watcher paths must close cleanly on plugin stop. No goroutine or FD leaks.
Tiered watching of known Session.Path values handles cheap appends, but it cannot discover a project's first session or a new time-partitioned directory. Global file adapters may need both known-file watching and one adapter-native discovery watcher. Watch creation at every directory level that can appear later (including month/year rollover), and keep discovery project-filtered.
Do not assume a new file's basename is its session ID. If identity lives in metadata, implement SessionPathResolver so watch events carry the same durable ID returned by Sessions().
Some global adapters maintain caches and indexes across calls. Consumers must serialize calls to a stateful adapter, make gate admission and work lifecycle/epoch cancellable, and reject stale results after project switches or shutdown. A slow Sessions() result must remain observable and eventually load (with a visible loading state); never time it out, silently discard it, and leave its goroutine running. Global targeted refresh must admit only sessions already belonging to the current project; unknown IDs require a project-filtered discovery pass.
Adapters must provide rich structured content for Conversation Flow UI.
Map source records to:
Message.Role, Message.Content, Message.ContentBlocksMessage.ToolUses (legacy compatibility)Message.ThinkingBlocks (if available)Message.Model when availableUse consistent ToolUseID for tool_use and tool_result blocks. If incremental parsing is used, preserve pending tool-link state across cache updates.
gotype TargetedRefresher interface { SessionByID(sessionID string) (*Session, error) }
Reduces refresh from O(N sessions) to O(1). Implement when adapter can resolve a session directly.
Implement when source format allows discovery of sessions beyond current git worktrees.
Implement when a file path alone does not encode the source's durable session ID. Tiered and discovery watchers use it to turn new or changed paths into targeted refresh events.
Implement for global sources that must discover the first matching session even when Sessions() initially returns no known files. Share only one global watcher per adapter, and ensure its events trigger a project-filtered load before any session is admitted.
Detect(): return (false, nil) for missing data directoriesSessions(): skip corrupt/unreadable entries and continue; hard-fail only on systemic errorsMessages(): return nil, nil for missing session files; fail on parse errorsWatch(): return (nil, nil, err) when watch setup failsconsumer timeout into a false empty history
New adapters should meet these performance targets:
Messages() full parse (~1MB): under 50msMessages() incremental append: under 10msMessages() cache hit: under 1msSessions() on 50 session files: under 50msAlso benchmark realistic source shapes: hundreds or thousands of indexed sessions, a large live- scale transcript, cache hits, and incremental appends. Record fixture size and session/event count with the result so a tiny synthetic benchmark cannot hide discovery or parsing regressions.
Required tests for every new adapter:
Detect()/Sessions()Sessions() sorted by UpdatedAt descAdapter*, FileSize, Path when applicable)ContentBlocks tool-use/result ID parity, not only legacy ToolUsesSessionIDRun tests:
bashgo test ./internal/adapter/<adapter> -run . go test ./internal/adapter/<adapter> -bench . -benchmem
adapter.Adapter contract implementedSessions() sets required identity and timestamp fieldsFileSize populated for every sessionPath strategy explicit and correct for adapter typeContentBlocks include text/tool/thinking dataToolUseID parity)Abs/EvalSymlinks in per-session loopsWatchScopeProviderSessionIDSessionPathResolverregister.go and main importMessages() pathFileSize-driven)Adapters can classify sessions by setting SessionCategory on adapter.Session. The conversations plugin supports category filtering (f menu: i/r/s keys) and a quick toggle (C key).
Defined in internal/adapter/adapter.go:
adapter.SessionCategoryInteractive — user-initiated interactive sessionsadapter.SessionCategoryCron — automated/scheduled sessionsadapter.SessionCategorySystem — system/gateway sessionsSessionCategory if the adapter has meaningful categories. Don't set it if all sessions are the same typeSessionCategory is empty, sessions pass through (non-breaking for adapters that don't classify)gofunc extractSessionMetadata(firstUserMessage string) (category, cronJobName, sourceChannel string) { if strings.HasPrefix(firstUserMessage, "[cron:") { return adapter.SessionCategoryCron, extractCronJobName(firstUserMessage), "" } if strings.HasPrefix(firstUserMessage, "System:") { if strings.Contains(firstUserMessage, "WhatsApp gateway") { return adapter.SessionCategoryInteractive, "", "whatsapp" } return adapter.SessionCategorySystem, "", "" } return adapter.SessionCategoryInteractive, "", detectSourceChannel(firstUserMessage) }
Optional fields on adapter.Session for richer display and filtering:
CronJobName string — for cron/scheduled sessions; used as session name when setSourceChannel string — for multi-channel adapters (e.g., "telegram", "whatsapp", "direct")Optional field on adapter.Message:
SourceLabel string — per-message source attribution badge (e.g., "TG] Marcus", "WA]", "cron] job-name")Set these during parsing when the source format contains channel/origin metadata. The conversations plugin and conversation flow UI use these for display.
For adapters whose source format embeds structured prefixes in user messages (e.g., channel tags, cron headers), strip them during parsing to keep the conversation view clean.
Message.Content and text ContentBlocksMessage.SourceLabel for badge displaygo// In processMessageLine for user messages: content, _, _, contentBlocks := parseContent(raw.Message.Content) sourceLabel := extractSourceLabel(content) // "[TG] Marcus" content = stripMessagePrefix(content) // clean body only for i := range contentBlocks { if contentBlocks[i].Type == "text" { contentBlocks[i].Text = stripMessagePrefix(contentBlocks[i].Text) } } msg := adapter.Message{ Content: content, ContentBlocks: contentBlocks, SourceLabel: sourceLabel, }
This keeps Content human-readable while preserving origin metadata in SourceLabel.
Lessons learned from building global-scope adapters (Pi, Codex):
Global adapters (WatchScopeGlobal) store sessions in a single directory regardless of project. They must filter by CWD matching projectRoot in Sessions():
projectRoot once per Sessions() call (Abs + EvalSymlinks)filepath.Rel — a session matches if its CWD is equal to or a subdirectory of the project rootSessionCategory set — empty passes throughGlobal adapters need to handle project switching gracefully:
Sessions(projectRoot) result is project-filtered, even when adapter caches retain source-global metadataSee references/cursor-db-format.md for Cursor's per-session SQLite database structure (Merkle tree blobs, hex-encoded metadata, WAL considerations).
See references/warp-sqlite-schema.md for Warp's single SQLite database structure (ai_queries, agent_conversations, blocks tables, protobuf tasks).
Other measured skills in the registry, with their headline benchmark lift.