0062. Claude calls go through a Claude Agent SDK sidecar
Source:
docs/decisions/0062-claude-agent-sdk-sidecar.md. Generated at build time; edit the source file.
Date: 2026-11-21. Status: accepted (owner direction). Amends ADR 0057.
Context
Section titled “Context”The owner asked that the AI layer use the same integration as their other project: the Claude Agent SDK (@anthropic-ai/claude-agent-sdk), which runs Claude Code under the hood. R3 had planned a hand-written reqwest client for the Messages API (Tasks 9–12). Task 9 (wire types, errors, redaction, config-driven cost, output parsing) is merged; Task 10 (SSE) was paused at tests only (WIP b36215f on r3/c).
Facts checked against the official docs on 2026-11-21 (code.claude.com/docs/en/agent-sdk/*):
- Auth:
ANTHROPIC_API_KEY, Bedrock, Vertex, Foundry, or a subscriptionCLAUDE_CODE_OAUTH_TOKEN. Verbatim: “Unless previously approved, Anthropic does not allow third party developers to offer claude.ai login or rate limits for their products, including agents built on the Claude Agent SDK. Use the API key authentication methods described in the Quickstart instead.” - Structured output:
options.outputFormat = { type: "json_schema", schema }(draft-07); result instructured_output; failure subtypeerror_max_structured_output_retries. - Prompt caching is automatic; TTL via
ENABLE_PROMPT_CACHING_1H=1. - No Message Batches support.
- One
query()= oneclaudesubprocess; docs suggest sizing about 1 GiB RAM per concurrent session. total_cost_usdis a client-side estimate, not billing;modelUsagegives per-model token counts.
Decision
Section titled “Decision”- A small Node service,
services/ai-sidecar, owns every interactive Claude call (report sections, weekly reviews, weakness-change notes, the coach chat). It wrapsquery()with:maxTurnssmall, no built-in tools (chat tools are exposed as in-process MCP tools that call back into Rust),permissionMode: "dontAsk",settingSources: [],CLAUDE_CODE_DISABLE_AUTO_MEMORY=1, an isolatedcwdandCLAUDE_CONFIG_DIR, a customsystemPrompt,outputFormatfor JSON sections, and pinned full model ids. - Rust stays in charge. Rust builds the prompts, owns budgets, the circuit breaker, metering and the fact-checker (validator), and talks to the sidecar over a local HTTP/JSON + server-sent-events contract. The sidecar holds no business rules. Amended (Amendment 1, Task 10 fix round 1): its only database access is the chat session store, which uses one table (
ai_sdk_session_entries) through a restricted role (ai_sidecar, with SELECT/INSERT/DELETE on that table only). The sidecar reads no other data. - Batches stay on the Messages API. The monthly and weekly regenerations (Tasks 16, 20) keep the 50% batch discount through a minimal Rust batch client built on the merged Task 9 wire types. The planned streaming SSE client (Task 10) is dropped; streaming comes from the SDK.
- Cost is ours, not the SDK’s estimate. Metering computes cost from
modelUsagetoken counts with the validatedPricingTable(Task 9) and stores the SDK estimate only for comparison. - Auth. Production uses
ANTHROPIC_API_KEY(or a cloud provider). The sidecar refuses to start in production with only a subscription token. Local development may use the owner’sCLAUDE_CODE_OAUTH_TOKEN; the docs don’t explicitly cover a developer testing their own product with a personal subscription, so this stays an open owner item. - Supply chain. The SDK is pinned exactly and passes the 7-day npm age check; its native
claudebinary comes from optional dependencies, so installs must not omit them.
Consequences
Section titled “Consequences”- R3 lane C is re-planned: Task 10 becomes the sidecar and its contract; Task 11 becomes the Rust sidecar client plus the minimal batch client; Task 12 (breaker, fake client) is unchanged in purpose. Tasks 13, 18, 20, 23, 26 and 27 get hand-offs.
- Each concurrent call costs a subprocess, so the sidecar has a concurrency cap and a queue; capacity planning uses measured RSS.
- If the subprocess model proves too heavy at scale, the Rust contract lets us swap the sidecar for a direct Messages client without touching callers.
Contract and isolation (Task 10)
Section titled “Contract and isolation (Task 10)”This section was recorded with the implementation in services/ai-sidecar (SDK 0.3.325). Task 11 codes against this contract, so change the two together.
Endpoints. All bodies are JSON with camelCase keys. Every route except /health needs authorization: Bearer ${AI_SIDECAR_TOKEN} and answers 401 without it.
-
POST /v1/querymakes one stateless structured call. The request carriesmodel, effort, maxTokens, timeoutMs, maxTurns, systemPrompt, prompt[] (text blocks), outputFormat?. The reply is 200 for any SDK result message:{subtype, stopReason, structuredOutput?, text, numTurns, durationMs, modelUsage{model: {inputTokens, outputTokens, cacheReadInputTokens, cacheCreationInputTokens}}, sdkCostUsd}.subtypepasses through:success,error_max_turns,error_max_structured_output_retriesorerror_during_execution. When the result carriesapi_error_status, the reply instead has that HTTP status and an Anthropic error body. -
POST /v1/chatruns one chat turn over SSE. The request is the query body withoutoutputFormat, plus:tools[] {name, description, inputSchema};toolCallback {url, token}, required whentoolsis not empty (Task 11: a turn without tools, such as the “answer now” follow-up, omits it and mounts no coach server);conversationId(a uuid);resume(a boolean);rebuildContext, required whenresumeis true (otherwise 400).
The stream sends these events:
delta {text, messageId?}, for top-leveltext_deltaonly;retract {messageIds, reason}, naming streamed messages that a refusal or a superseding message withdrew (done.textis authoritative);tool_use {id, name, input, messageId?}(a later retract namingmessageIdwithdraws the call), wherenameis the SDK’s MCP namemcp__coach__<name>(Rust strips the prefix);- exactly one terminal event, either
done(the query result plussession: "new" | "resumed" | "rebuilt"andsessionModelUsage) orerror(the error body plusstatus); - a
: pingcomment every 15 s.
A client disconnect aborts the query.
-
GET /healthneeds no token, makes no model call and returns no secret. Its body is{ok, auth, inFlight, queued, maxConcurrency, sdkVersion, mirrorErrors}. -
The tool callback is
POST {toolCallback.url}withBearer {toolCallback.token}and the body{name, input}. Rust answers{content, isError}. A non-2xx reply, a malformed body, a network error or a timeout becomes the tool result{"available":false,"reason":"tool unavailable"}withisError: true. The model never sees a status or a URL.
Error bodies. Every error uses the Anthropic shape {"type":"error","error":{"type","message"}}, so Rust’s classify_status (T9) maps it unchanged. Statuses map to types like this:
- 400 →
invalid_request_error; - 401 →
authentication_error; - 403 →
permission_error; - 429 →
rate_limit_error, withretry-afterfrom the SDK’s lastapi_retrydelay; - 529 →
overloaded_error; - any other status ≥ 500 →
api_error.
A timeout is 504 api_error, and a call aborted by shutdown (SIGTERM) is 503 api_error. A second concurrent turn of one conversation is 409 with the non-Anthropic type turn_in_progress; Rust should treat it as “busy, retry after the running turn”. Messages are fixed strings and never echo SDK text, because that text may contain a key.
Isolation. buildOptions is the single place where the options are set:
modelcomes from an allowlist (claude-sonnet-5-5,claude-haiku-5-5) and is never an alias.maxTurnsis capped at 10.systemPromptis the custom string from the request.tools: [],strictMcpConfig: true,permissionMode: "dontAsk"andsettingSources: [].verbatimPrompts: true, so user text is never expanded as@pathor dispatched as a slash command.cwdis an empty work dir.agents,hooks,fallbackModel,thinkingandmaxThinkingTokensare never set./v1/querysetspersistSession: falseandoutputFormat, and uses no session./v1/chatsetsmcpServers: {coach},allowedTools(exactly themcp__coach__<name>names) andincludePartialMessages: true. It also setssessionIdon the first turn orresumeon later turns, together withsessionStore.- Chat never sets
persistSession: falseorenableFileCheckpointing, because the SDK rejects both when a store is present.
Env allowlist. The child’s env replaces the parent environment. It holds only these variables:
PATH;HOMEandCLAUDE_CONFIG_DIR, both set to the config dir;CLAUDE_CODE_DISABLE_AUTO_MEMORY=1andCLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1;CLAUDE_CODE_MAX_OUTPUT_TOKENS;CLAUDE_AGENT_SDK_CLIENT_APP=chess-improver-sidecar/0.1;CLAUDE_CODE_PROJECT_DIR_NAME=chess-improver-coach, which keeps the session store’sprojectKeystable across replicas and paths;- the one credential that
authchose: the API key, the OAuth token (development only), or, forcloud, theCLAUDE_CODE_USE_*flag and the provider variables.
AI_SIDECAR_TOKEN, AI_SESSION_DATABASE_URL, DATABASE_URL and every other variable are left out.
Chat sessions (owner direction, controller ruling). Chat uses the SDK’s native sessions, and the session id is the Postgres conversation id.
- Turns. The first turn runs with
sessionId. Later turns run withresumeand send only the new user message. - Storage. A Postgres
SessionStore(PgSessionStore) mirrors the transcripts into one table,ai_sdk_session_entries. Its columns areproject_key text,session_id uuid,subpath text NOT NULL DEFAULT '',seq bigint,entry jsonbandcreated_at timestamptz. The primary key is(project_key, session_id, subpath, seq). - Access. The sidecar connects as the dedicated role
ai_sidecar, which has only SELECT, INSERT and DELETE on that table. Task 17 owns the migration, the role and the GRANT; the sidecar’s tests use a fixture copy. - Entries. They are opaque JSON. SQL reads only the documented top-level
uuid, as the idempotency key for retried batches. Appends are serialized per transcript with an advisory lock. - Conformance. The adapter passes a port of the SDK’s conformance suite, which the npm package does not ship.
- Fallback. Sometimes the transcript is unknown: neither a store row nor a local file exists. Sometimes the resume fails before any output: an
error_during_executionresult, or a throw with no result. In either case the sidecar clears that session’s rows and retries once as a new session. The retry’s prompt is Rust’srebuildContextfollowed by the new message. - Mirror errors. Each
system/mirror_errorincrements themirrorErrorswarning metric and logs a warning without detail. - Local disk. The CLI’s own disk (
/var/lib/ai-sidecar) is a tmpfs scratch area, with no named volume. - Deletion. Rust deletes the
ai_sdk_session_entriesrows for the conversation id in the same transaction as the conversation (Tasks 17 and 25). The sidecar has no delete endpoint. - JSON calls. One-shot JSON calls stay stateless.
JSON Schema to zod. Rust owns the tool schemas as JSON Schema, but tool() needs a zod raw shape. The converter accepts only the T22 subset:
- a top-level
objectwithproperties,required,additionalProperties: falseand an optionaldescription; - the property types
string(optionally withenum),integer(optionally withminimum/maximum),number,boolean, andarrayofstring.
Properties that are not required become .optional(). Anything else throws SchemaUnsupported(path), which /v1/chat returns as a 400 before anything is queued or spawned.
Tool schemas have no nullable form (Task 22). The converter has no anyOf and no null, so the chat tools (chat::tools) do not use the required-and-nullable form of the output schemas. An optional property is left out of required and becomes .optional(). The Rust executor (chat::execute) validates every field again and treats a missing optional field and null the same way. An unexpected key is rejected with the fixed message invalid input: unexpected field, which never names the key.
Timeout ordering. The timeouts nest from shortest to longest:
- T23’s engine wait is 45 s.
- The callback fetch times out at 55 s.
- The MCP per-server tool-call limit (
createSdkMcpServer({ timeout })) is 60 s.
Separately, each request’s timeoutMs aborts the whole query.
Limiter. At most maxConcurrency 4 calls run at once, each in its own subprocess of about 1 GiB. Further requests wait in a FIFO queue of up to 32 for at most 30 s. When the queue is full or the wait runs out, the reply is 529 overloaded_error with retry-after: 5. A client that disconnects while queued leaves the queue. Compose caps the container with mem_limit: 5g, and capacity planning uses measured RSS.
Production guard. AI_SIDECAR_ENV=production or NODE_ENV=production turns the guard on. With auth of oauth or none, the sidecar exits with code 78 and the message “refusing to start: production needs ANTHROPIC_API_KEY or a cloud provider; a subscription token is not allowed (ADR 0062)”. Production also requires AI_SESSION_DATABASE_URL. In development oauth is allowed, and none starts, reports auth:"none" and answers every call with 401 authentication_error.
Licence. @anthropic-ai/claude-agent-sdk is “SEE LICENSE IN README.md”: Anthropic’s commercial terms, not open source. Its peers are permissive: @modelcontextprotocol/sdk 1.32.2 (MIT), @anthropic-ai/sdk 1.8.0 (Apache-2.0) and zod 4.6.7 (MIT). So is pg 8.23.1 (MIT). All are pinned exactly and pass the 7-day age check. The platform claude binaries come from the SDK’s optionalDependencies, so installs must keep optional dependencies.
Amendment 1 (2026-11-21): chat uses SDK sessions stored in Postgres
Section titled “Amendment 1 (2026-11-21): chat uses SDK sessions stored in Postgres”Owner direction: the coach chat uses the SDK’s native sessions, as in the owner’s reference project. The plain Messages API is stateless, so the history has to be stored either way.
- Sessions. A new conversation runs
sessionId = conversation uuid, and each later turn runsresume = conversation uuidwith only the new user message. Claude sees its own earlier replies verbatim, and caching across turns is automatic (5-minute TTL;ENABLE_PROMPT_CACHING_1H=1for longer). - Storage. We use the documented pluggable
options.sessionStore(agent-sdk/session-storage). The sidecar’s Postgres adapter writes opaque entries to one table,ai_sdk_session_entries, through a dedicated role granted access to that table only. The CLI’s local transcript disk is scratch (tmpfs). This supersedes “the sidecar has no database access” for this single table. - System of record. Postgres conversations and messages (Tasks 17 and 25) remain the record for display, titles, rollover summaries and deletion. If a resume fails, the sidecar retries once as a new session seeded with Rust’s rebuilt context (summary plus recent turns).
- Deletion and retention. The SDK never deletes from a store. Rust deletes a conversation’s
ai_sdk_session_entriesrows in the same transaction as the conversation itself, so “delete conversation” and “delete all” leave nothing behind. - One-shot calls. Report sections and other JSON one-shot calls stay stateless.
- Unverified items, tested in Task 10: the version that added
SessionStore, the result shape for a missing session on resume, and thedeleteSessionsignature.
Notes from the Task 10 review (fix round 1)
Section titled “Notes from the Task 10 review (fix round 1)”-
Verbatim prompts.
buildOptionssetsverbatimPrompts: true, which requires Claude Code 2.1.248 or later; the bundled CLI is 2.1.325. Without it, the CLI expands user text such as@/proc/self/environas a file mention and dispatches/compact-style text as a slash command. With it, prompts are delivered as written, and the CLI’s turn-start attachment pass (nested CLAUDE.md files, skill listings) is skipped too. That suits a sidecar with an empty cwd and no settings. -
Cumulative versus per-turn usage, and metering (controller ruling, fix round 2). The SDK’s result
modelUsageis cumulative for the session: on a resumed turn it includes every earlier turn, because the transcript carries the saved totals. The sidecar reports two fields.sessionModelUsageis the SDK’s running total.modelUsageis the turn’s own usage per model. On a resumed turn it is summed from the stream’smessage_startandmessage_deltausage. On a new or rebuilt turn it is the SDK’s figure, which is per-turn there and also counts internal calls. When a failed resume attempt preceded a rebuild, that attempt’s streamed usage is added.
Rust meters as follows. For
/v1/query, and for new or rebuilt chat turns, it metersmodelUsage. For a resumed turn, it meterssessionModelUsage(now) − sessionModelUsage(previous turn)per model; Rust keeps each turn’ssessionModelUsagefor this. If any difference is negative (for example, after a rebuild reset the totals), it falls back tomodelUsage. The difference also captures internal calls that the stream does not show./v1/queryis stateless, so itsmodelUsageis per call. Model keys pass through unchanged, including a refusal-fallback model outside the allowlist, and Rust prices unknown keys conservatively. -
Local transcripts are scratch. Before every new or rebuilt attempt, the sidecar removes
configDir/projects/<projectKey>/<id>.jsonland<id>/, because the CLI rejects asessionIdwhose file exists. With a store configured, it also removes them after each turn. The compose service has a read-only root and sized tmpfs mounts for/var/lib/ai-sidecar(512 MiB) and/tmp(256 MiB). -
Retractions (SDK-faithful, fix round 2). Deltas carry the
messageIdof their API message. Aretract {messageIds, reason}event names only messages the sidecar actually streamed and has not already retracted. It is triggered in three ways:- When a streamed message ends with
stop_reason: "refusal", its retract (reason: "refusal") is sent at once, before the fallback model’s replacement text. - An assistant message’s
supersedestriggers a retract (reason: "superseded"). - A
model_refusal_fallback’sretracted_message_uuidstriggers a retract (reason: "model_refusal_fallback").
The uuids in the last two are mapped to message ids, and unknown or already-retracted uuids are a no-op.
done.textis authoritative for the turn’s final text. - When a streamed message ends with
-
One turn per conversation. Two overlapping turns of one conversation would delete each other’s transcripts and branch the stored session. The sidecar holds an in-process lock per conversation id. When a store is configured, it also holds a Postgres session-level advisory lock,
pg_try_advisory_lock(2026112110, hashtext(conversation_id)), on a dedicated pool connection for the whole turn, so replicas exclude each other. The two-int key keeps it apart from the store’s single-bigint append locks. The lock is taken once a limiter slot is free, so a queued request holds no connection. A second turn gets 409 with error typeturn_in_progress, before any header. On anewturn whose id already has store rows (a retried first turn), those rows are deleted first. -
Store writes.
appendisINSERT … ON CONFLICT DO NOTHINGagainst Task 17’s partial unique index(project_key, session_id, subpath, (entry->>'uuid')) WHERE entry ? 'uuid', so retried batches and in-batch repeats are no-ops. Theai_sidecarrole is created NOLOGIN by the migration. Operations grantLOGIN PASSWORDout of band; in dev compose that isdocker/postgres/ai-sidecar-role.sh(profileai).
Notes from Task 11
Section titled “Notes from Task 11”- Optional callback.
toolCallbackis optional whentoolsis empty, and such a turn mounts nocoachMCP server. A callback that is sent is still validated. - Turn-lock hygiene (final Task 10 review).
lockLostcounts only while the lock is held. A no-operrorlistener stays on the lock connection after release (once per pooled client, so listeners do not pile up). On the not-acquired path a failingRESETdestroys the connection and still reports “held elsewhere” (409), instead of throwing, which would have let the turn run with no lock. - Test schema. The sidecar’s store tests read the
ai_sdk_session_entriestable, indexes and role block from Task 17’s real migration (db/migrations/20261121030000_ai_coaching.sql) at test time; the copied fixture is gone.
Interactive engine checks (Task 24)
Section titled “Interactive engine checks (Task 24)”The chat’s analyse_position tool reaches Stockfish only through ai::chat::interactive::DbInteractiveEngine, one per turn (account, assistant message, turn start).
- Protocol.
sf19-n1m-mpv3-interactive-v1: Stockfish 19, 1,000,000 nodes, MultiPV 3, a 30 s timeout. It is deliberately not R1’ssf19-n300k-v1. The searches are deeper, run on positions the player made up, and are requested on demand, so they are not comparable with the pinned per-game analysis. - The separate store. Results live only in
interactive_evals(source = 'interactive'), aslines = [{multipv, score (White's point of view), pv (UCI), san, depth, nodes}].InteractiveAnalyseHandlernever writesposition_evals, and KPI, stats, profile and report code never readinteractive_evals. A “what if” line from a hypothetical position must not move a player’s accuracy, weakness rates or cached evals, and a protocol mix inposition_evalswould break the R1 cache key. A test asserts that theposition_evalscount is unchanged. - Queue. Each check is an
interactive-analysejob on R1’s Postgres queue: priority 1,user_key= account, dedupeieval:<id>, one attempt. It runs on the shared engine pool, and leases and clock-step rules of ADR 0032 apply unchanged. Runners claim one kind each, so priority 1 orders jobs only withininteractive-analyse, which is plain FIFO. It does not put these jobs ahead ofanalyse-game; they meet only at theEnginePool, which has no priority.user_keyis stored but no strategy reads it yet.interactive-analyseis not aServedKind, so its runner (Task 26) must usePriorityFifo:FairRoundRobinwould refuse every claim. Fairness between accounts for interactive checks is a follow-up. Until then, only the per-turn cap of 2 and the quotas bound one account’s share. The request polls its row every 100 ms for up to the caller’s wait. When the wait passes first it returnsPending, and Task 23 then callswaitorabandon. - Quotas. Free plans get 3 checks a week and Pro plans 20 a day (
entitlements::engine_quotas, UTC windows). A charged row is one use. The reservation is atomic:db::interactive::reserve_evaltakespg_advisory_xact_lock(30002, hashtext(account)), counts charged rows per window in new statements under READ COMMITTED, and inserts the pending row only if every quota has room, all in one transaction. A test fires N+1 requests in parallel against N remaining checks and accepts exactly N, and it fails when the lock is removed. A request over the quota writes nothing and returnsLimit { window, resets_at }. Task 22’s cap of 2 checks per turn is applied before any of this, so a third call getsper_turnwithout touching the quota. - Reuse. A charged
donerow of the same account, FEN (normalised after the moves) and protocol within 24 h is copied into a newdonerow withcharged = false, linked to the new message. No engine call is made, and this works even when the quota is used up. Only charged originals are reused, so the 24 h window runs from the result that was paid for. A free copy never extends it (review m2). - Refunds (
charged = false).- An engine failure other than a closed pool marks the row
failed. - A dead-lettered job (
on_dead) marks the rowfailed. abandonrefunds the check (account-scoped). It also cancels it, as described under “Cancellation”.- A lost job is failed by
ai-reconcilestep 6. - A closed pool (shutdown) releases the job after 5 s without failing the row.
- An engine failure other than a closed pool marks the row
- Cancellation (T23 m6). A drop guard closes this gap. If a
requestorwaitfuture is dropped while it polls (the turn was cancelled), the guard spawns anabandon. A check whose result nobody saw is never charged. - A refund is also a cancellation (review I1, controller ruling).
db::interactive::abandon_evalsets apendingrow tofailedwith errorabandonedandcharged = false, in one update guarded bystatus = 'pending'. The handler skips non-pending rows at load.complete_evalalso needspending, so a running analysis’s late lines are dropped. Whichever update wins the race decides the outcome. If the completion wins, the row isdoneand stays charged, because the result exists. If the refund wins, the row isfailedand uncharged, and never reusable. A refunded check can therefore never become a free result, so a player cannot cancel a turn and then ask again to get unlimited checks. A poll-time DB error arms the same guard, and this rule covers it too. The alternative, re-charging on reuse, was rejected: it needs a second quota reservation inside the reuse path. Tests:a_cancelled_check_is_not_reused_freeanda_refund_racing_completion_never_yields_a_free_result. - Scoping. Eval ids are 32 lowercase hex (
Uuid::simple).waitandabandononly see the engine’s own account, so a foreign id isUnavailableor a no-op.
Worker wiring (Task 26)
Section titled “Worker wiring (Task 26)”WorkerEnvreadsAI_SIDECAR_URL/AI_SIDECAR_TOKEN(a URL without a token is a startup error),AI_TOOL_BIND(default0.0.0.0:7311),AI_TOOL_PUBLIC_URL,ANTHROPIC_API_KEY(batches only), the three budget variables andAI_PRICING_FILE. ItsDebugredacts the key and the token.- Enabled check. AI is enabled only when the sidecar is configured and its
/healthreports a credential (auth != "none"). The probe is tried 3 times, 2 s apart; if all fail, AI is disabled until the next start (ai: disabled (sidecar health check failed)). Compose starts the worker only after the sidecar is healthy, so a sidecar that refuses to start (for exampleAI_SIDECAR_ENV=productionwithout a key) also keeps the analysis worker down: production deployments must run a healthy sidecar, and a deployment without AI removes the dependency. The client iswith_breaker(AiRuntime { sidecar, batches }, Breaker(5, 60 s)); the tool endpoint starts only when AI is enabled andAI_TOOL_PUBLIC_URLis set. - The log line is exactly
ai: enabled (sidecar, batches on|off)orai: disabled (AI_SIDECAR_URL not set | sidecar has no credential | sidecar health check failed). A test captures every log line of the worker’s start and checks that neither the key nor the token appears. - Runners. One per AI kind, AI or not, all
PriorityFifo:generate-report(2, 20 min),weekly-reviewandexplain-weakness-change(2 each, 10 min),coach-chat(4),interactive-analyse(1, 2 min, on the sharedEnginePool), and the batch schedules, the batch poll (45 min) andai-reconcile(5 min), one each. Deviation: the brief’s 3 min hard timeout forcoach-chatpredates the 10 min turn budget of Task 25 (CHAT_TURN_TIMEOUT), so the runner’s deadline is that plus 60 s; a shorter one would cut turns the job still allows and lose their metering. The AI runners addAI_POOL_HEADROOM(30) connections to the pool.ensure_ai_recurringis scheduled with the reconciler. The analysis CLI starts no AI runner. - Inputs and plans.
DefaultEntitlements(M7 replaces it); R2’sbuild_coaching_inputas the provider (an account with no analysed game in the time class has no input yet). R2’s builder future is notSend, so the provider drives it on a blocking thread (hand-off to R2: make itSend). There is no weekly-input builder yet (NullWeeklyProvider). - Compose.
rust-workergetsAI_SIDECAR_URL: http://ai-sidecar:7310, the shared token default,AI_TOOL_BIND: 0.0.0.0:7311,AI_TOOL_PUBLIC_URL: http://rust-worker:7311,ANTHROPIC_API_KEYand the budgets, no ports, anddepends_on: ai-sidecar (service_healthy). Theai_sidecarrole gets LOGIN and its password fromai-sidecar-role(dev) or secret management (production), as before.
Amendment 2 (2026-11-22): local mode, the host’s own Claude Code login (dev only)
Section titled “Amendment 2 (2026-11-22): local mode, the host’s own Claude Code login (dev only)”Owner direction: in development the coach uses the Claude Code already signed in on the owner’s machine, with no API key and no OAuth token anywhere, like the owner’s reference project. That project runs its Node server on the host, and the Agent SDK spawns the local claude with the login in ~/.claude.
- Enabling it.
AI_SIDECAR_LOCAL_CLAUDE=1with no other credential.ANTHROPIC_API_KEY,CLAUDE_CODE_OAUTH_TOKENor a cloud flag beside it is a startup error, because it would be unclear which one runs./healthreportsauth: "local". - Never in production. The sidecar refuses to start in local mode when it is in production mode,
NODE_ENV=productionincluded (LOCAL_GUARD_MESSAGE, exit 78). - Policy. A personal Claude login is for its owner’s own use. Anthropic’s terms do not allow serving other people from it, so local mode is the owner’s development loop only. Friends in the private beta are served with
ANTHROPIC_API_KEY(or a cloud provider) and the Docker sidecar. - The child.
- The child’s
HOME,USERPROFILE,APPDATAandCLAUDE_CONFIG_DIRare not overridden, so the CLI reads the login where it lives (~/.claude/.credentials.jsonon Windows and Linux, the Keychain on macOS). - The env allowlist gains only what is needed to locate that login and run:
HOME,USER,LOGNAME,USERPROFILE,APPDATA,LOCALAPPDATA,HOMEDRIVE,HOMEPATH,USERNAME,SystemRoot,TEMP,TMPandTMPDIR, plusCLAUDE_CONFIG_DIRif the host sets it. No key or token is passed. - Every other isolation option is unchanged:
settingSources: [], so none of the user’s settings, CLAUDE.md files or skills load;CLAUDE_CODE_DISABLE_AUTO_MEMORY=1;tools: [];strictMcpConfig;permissionMode: "dontAsk";verbatimPrompts; and an empty cwd of its own (<tmp>/chess-improver-ai-sidecar/work).
- The child’s
- Host run.
pnpm --filter @ci/ai-sidecar start:local(tsx --env-file-if-exists=../../.env src/local.ts) does the following:- It checks that the SDK’s native
claudefor the platform is installed. On Windows that is@anthropic-ai/claude-agent-sdk-win32-x64, an optional dependency, so the install must keep optional dependencies. - It turns local mode on and listens on
127.0.0.1:7310. - It defaults the token to the compose dev default.
- It maps the compose session-store URL (
@postgres:5432) to the host-publishedlocalhost:55432.AI_SIDECAR_LOCAL_DATABASE_URLoverrides that mapping. Without either URL it runs with no store.
- It checks that the SDK’s native
- Compose.
docker-compose.local-claude.ymlis opt-in throughCOMPOSE_FILE.- The Docker
ai-sidecaris moved to a profile that no command enables. rust-workerusesAI_SIDECAR_URL=http://host.docker.internal:7310(withextra_hosts: host-gateway). Itsdepends_onis reset to Postgres only.- The worker publishes its tool endpoint on
127.0.0.1:7311withAI_TOOL_PUBLIC_URL=http://127.0.0.1:7311, so the host sidecar can call it back. - The host sidecar must be up before the worker starts: the worker’s health check is tried 3 times, and after that AI stays off until a restart.
- The Docker
- Rust.
AuthKind::Localcounts as a credential, so AI is on. WithoutANTHROPIC_API_KEY, scheduled regenerations run as sync sidecar jobs (M5b Task B). The start logsai: sidecar auth local (the host's Claude Code login, dev only). The line names the credential path, never a secret. - What lands in
~/.claude.- Verified in the host smoke (one haiku
/v1/query). Nothing is written underprojects/, because one-shot calls usepersistSession: false.~/.claude.jsonis not touched. The CLI does update its own housekeeping: it registers and removes asessions/<pid>.jsonentry, writes a builtin plugin state file underplugins/store/, and refreshes.credentials.jsonwhen the login’s token renews. - Chat turns. These cannot run without local persistence: the SDK requires local writes for its
sessionStoremirror, andpersistSession: falsethrows there. The transcript is written to~/.claude/projects/chess-improver-coach/<conversation id>.jsonl(the fixedCLAUDE_CODE_PROJECT_DIR_NAME). That project directory matches no real cwd, so the transcripts never appear in the owner’sclaude --resumelists. - With a session store (the host Postgres), the sidecar deletes that file and its
<id>/directory after every turn, as before. - Without a store, the transcripts stay there, because resume reads them. Delete that directory at any time; a lost transcript makes the next turn rebuild from Rust’s context.
- Verified in the host smoke (one haiku
Amendment 3 (2026-11-23): local mode records usage but does not enforce the budget
Section titled “Amendment 3 (2026-11-23): local mode records usage but does not enforce the budget”Holistic review F4: in local mode the report said “Your coach has reached this month’s spending limit”. The month’s notional spend (list prices, $2.24) had passed the beta pro budget ($2), all from the owner’s own testing, although a call on the host’s own Claude Code login has no real cost.
- Decision. When the sidecar reports
auth: "local", the worker makes its budgets notional (BudgetConfig::notional,enforce: false).budget_guardthen passes every call. Every call is still metered intoai_usageat list prices, so the numbers stay comparable with a keyed deployment. The start logsai: monthly budget not enforced (local login, no real cost; usage still recorded). - Why it can’t leak. Production refuses local mode (Amendment 2), so a production worker never sees
auth: "local", and its budget stays enforced. Every other credential (api_key,cloud,oauth) keeps the enforced budget. - The UI. With no budget refusal in local mode, no new report, note or chat answer fails with
budget, so the pages never show “spending limit” in that mode. A report that already failed for budget before the change keeps its banner until it is rebuilt.