Introducing a new way to review your PRs.

Read the announcement

thedotmack / claude-mem

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

View on GitHub

47 documents · Updated Nov 20, 2026

docs / local-runtime-api

Local runtime and API service

The local runtime is the service that makes memory available to local tools, browser clients, and capture clients. It accepts work, protects the local data boundary, coordinates provider work, and serves views that help people inspect and manage memory.

Runtime boundary

Service role

The local runtime is the main boundary between clients and the memory system. It joins storage, request handling, local capture, search, background work, provider generation, live updates, and service status so clients do not need a direct connection to each subsystem. The Postgres server service and the local worker provide complementary surfaces over this shared product boundary. The server service is created by src/…/create-server-service.ts and exposed by src/…/ServerService.ts.

The Postgres server path treats Postgres as its durable source of truth. Queue and generation support are separate boundaries, so the HTTP service can accept durable work even when no local generator is active. Meaning search is also optional; memory writes remain useful when vector support is unavailable.

The local worker keeps its SQLite data path private and starts its search, media, backup, and optional cloud services from one database manager. This keeps local capture useful when cloud sync, media upload, or vector search is disabled.

The worker binds to a non-loopback host only when the local API token protects the full surface. A leftover Observation TV token no longer creates a read-only network mode; without the local token, the worker falls back to loopback or warns that the full API is exposed.

References: src/…/create-server-service.ts• L193-264 src/…/types.ts• L41-63 src/…/DatabaseManager.ts• L46-144 src/…/worker-bind-host.ts• L44-88

Runtime lifecycle

The runtime normally stays in the foreground for a process manager. It can also run as a background daemon. Start, stop, restart, and status operations use saved process identity so an operator does not control an unrelated process.

Shutdown closes the listener and then releases queue, provider, embedding, database, sync, and local-worker resources. The worker can also use an opt-in idle window. It exits only when sessions, buffered work, open requests, viewer clients, and recent AI activity are all quiet. The idle path uses the same graceful shutdown sequence as an explicit stop.

Database startup retries transient SQLITE_BUSY errors after it closes partial state. The bounded retry window fits inside the hook readiness wait, so a busy database reports ready or failed instead of leaving the caller in an ambiguous timeout.

The command layer keeps server lifecycle, key, and job operations tied to the Postgres runtime, while older worker-service key operations remain a separate local SQLite path.

References: src/…/ServerService.ts• L234-285 src/…/ServerService.ts• L293-478 src/…/ServerService.ts• L814-852 src/…/DatabaseManager.ts• L146-176 src/…/db-init-retry.ts• L20-93 src/…/idle-exit-monitor.ts• L39-69 src/…/idle-exit-monitor.ts• L121-183

Request and memory flow

Authenticated request path

The server handles a protected request through one shared boundary. It assigns a request identity, checks the presented key and its scope, checks the team and project boundary, performs the memory action, and records the audit result. Bearer tokens are the normal form. X-Api-Key remains available for compatible clients.

The key defines the team, optional project, and allowed actions for the request. Route handlers use that identity for reads, writes, search, context, and job control. A project-scoped key cannot cross into another project.

For route contracts and authentication rules, see HTTP API and authentication.

References: src/…/postgres-auth.ts• L51-140 src/…/postgres-auth.ts• L150-257 src/…/ServerV1PostgresRoutes.ts• L162-196

Memory capabilities

The API presents one memory surface for sessions, events, observations, summaries, search, context, timelines, usage, and generation jobs. A client can either write a finished memory directly or submit activity that the generation system turns into memory later.

The local worker adds the local capture and inspection surface. It serves feeds, sessions, tool records, media metadata and variants, imports, explicit memory saves, settings, work state, deduplication review, corpora, backups, logs, and the interactive work view. It also exposes cloud-sync status and recovery controls, team knowledge reads, and progressive search for clients that need staged recall. These routes are local-service capabilities rather than a second memory model.

Explicit browser writes are tied to the worker's own origin. Origin-less hooks, command-line tools, and agent clients keep the loopback access model, while another localhost page cannot trigger memory saves, settings changes, or other guarded writes.

The memory ingest route can import native Claude Code memory files directly as observations. It uses the same store seam as an explicit memory save, rejects sources outside the supported projects area, skips exact replays, preserves file times, and nudges cloud sync after a successful write. This path does not call a model because the source is already distilled.

Meaning search improves recall when its optional service is ready. Semantic candidates are bounded and hydrated from the local store before project, source, and date rules are applied. If vector search is missing, slow, unavailable, or returns too few eligible rows, the runtime uses keyword search to keep the requested memory surface usable. Search keeps project history readable after project merges by using all stored read keys. It joins semantic results with local search results when a semantic result set does not fill the requested category or date order. Progressive recall first returns bounded index entries, then fetches selected details within their project scope.

Corpus work turns a selected set of observations into a question-ready knowledge base. Build and rebuild use the saved filter as the corpus definition. Prime starts a knowledge session, and a later query can renew that session if it has expired. The selected corpus agent can use the Claude Agent SDK or the configured API provider. The API path sends a bounded, question-focused excerpt and reports when the answer saw only part of the corpus. It uses the selected API account and does not silently move a refused question to Claude.

See Smart file-read gate for the boundary that decides when file content may enter this memory path.

References: src/…/ServerV1PostgresRoutes.ts• L886-1021 src/…/ServerV1PostgresRoutes.ts• L1023-1147 src/…/DataRoutes.ts• L230-256 src/…/MemoryRoutes.ts• L31-58 src/…/MemoryIngestRoutes.ts• L17-23 src/…/MemoryIngestRoutes.ts• L34-143 src/…/MediaRoutes.ts• L123-223 src/…/CorpusRoutes.ts• L288-437 src/…/SearchManager.ts• L469-729 src/…/ChromaSearchStrategy.ts• L45-171 src/…/errors.ts• L5-47 src/…/HybridSearchStrategy.ts• L22-99 src/…/ProgressiveMemorySearch.ts• L26-127 src/…/CorpusAgent.ts• L26-127 src/…/ApiCorpusAgent.ts• L239-395

Event-to-observation flow

The runtime records captured activity before it asks a provider to derive memory. A bounded session buffer holds live work for the life of the worker. The source transcript remains the recovery source after a worker restart, so the runtime does not promise to resurrect an in-memory backlog.

The shared ingest path applies project, privacy, tool, agent, deletion, duplicate, and capture gates before it hands work to the session manager. Durable callers mark an event handed off only after it is queued or stored. This lets a spool retry declined work without repeating accepted work.

The provider returns observations or a summary. The response processor parses that result, adds evidence from successful file operations, stores the durable result, confirms the claimed work, and only then starts broadcasts and optional integrations. Failed or denied tool calls do not become file evidence. A summary is stored when it contains progress or notes rather than only a title or future plan. Media results and source receipts follow the same commit boundary.

This order separates durable memory from downstream effects. A provider failure preserves the queued batch when retry is safe. A provider response that was billed but has unusable output is not sent again. A completed but empty result settles the batch without inventing an observation. The runtime sends one unanswered observer prompt at a time so a large backlog cannot outrun the generation budget. A provider may combine compatible pending observations into one bounded turn without changing the durable claim and confirmation flow. Quota, authentication, and capture-disable stops discard unsubmitted live work; transport, rate-limit, overflow, provider-switch, and output-retry stops preserve the bounded buffer for a later run.

The flow below shows the relationship between capture, provider work, storage, and clients.

flowchart LR
    I[Capture client] --> E[Session or event ingest]
    E --> B[Bounded in-process session buffer]
    B --> G[Provider generator]
    G --> P[Parse and validate result]
    P --> S[(Memory store)]
    S --> C[Feeds, search, viewer, and integrations]
    P -->|safe retry| B
    T[Transcript replay] -. recovery .-> E

For job ownership, retries, and provider details, see Server jobs and process supervision and Observation generation and provider runtime.

References: src/…/SessionManager.ts• L496-623 src/…/SessionManager.ts• L917-989 src/…/SessionMessageBuffer.ts• L47-65 src/…/SessionMessageBuffer.ts• L268-361 src/…/ResponseProcessor.ts• L647-727 src/…/ResponseProcessor.ts• L979-1144 src/…/ResponseProcessor.ts• L1493-1679 src/…/GeneratorExitHandler.ts• L21-123 src/…/abort-reason.ts• L45-87 src/…/shared.ts• L119-135 src/…/shared.ts• L192-479

Client surfaces

HTTP interface

The HTTP service exposes health and readiness checks beside memory and job routes. It also serves the local compatibility API for observations, summaries, prompts, sessions, imports, processing status, settings, search-related data, and work management.

Common response handling gives clients one JSON error shape. Long corpus work can use server-sent events with heartbeats and one terminal result or error. Provider-backed prime, query, and reprime work is aborted when the client disconnects; corpus builds and rebuilds remain tracked background work when their client leaves. Corpus operations for the same name are serialized so an older query cannot overwrite a newer rebuild or a deletion.

For the detailed route map and request rules, see HTTP API and authentication.

References: src/…/Server.ts• L119-240 src/…/ErrorHandler.ts• L5-70 src/…/CorpusRoutes.ts• L102-113 src/…/CorpusRoutes.ts• L175-285 src/…/SessionRoutes.ts• L621-661

Local worker interface

The local worker is the companion HTTP surface for the local SQLite memory store. It receives capture from hooks and local clients, gives clients paged and targeted reads, coordinates process-local provider sessions, and keeps local clients informed when committed data changes.

Its route groups cover these product capabilities:

  • Memory feeds, session and tool-use records, imports, deletion, statistics, and processing status.
  • Session initialization, event capture, summarization, and session end.
  • Advisor-call records and deliverables captured from transcript and hook data.
  • Corpus build, rebuild, query, and provider-backed corpus sessions.
  • Near-duplicate candidate review and full-corpus deduplication scans.
  • Settings, dependency health, MCP state, work-state records, backups, and logs.
  • Work-view snapshots, evidence, reviews, rules, focus areas, setup, and shared focus pages.
  • Cloud-sync status, recovery previews and jobs, conflict choices, and team status and search.
  • Private media readiness, metadata, source details, and viewer or model variants.

In the default local mode, the worker trusts loopback access for ordinary local clients. When local API token mode is enabled, loopback is not an automatic pass: API requests need the token, while only data-free UI files and explicitly open routes remain unauthenticated. Read requests may carry the token in the query for browser streams; writes must use the header. Browser writes that can change data or settings also require the worker's own origin. Recovery, work-view controls, backup runs, and file reads require a stricter local boundary. A separately exposed worker has a narrow read-only surface, and untrusted host names are rejected to reduce DNS-rebinding risk. Live data events are invalidation hints, so a client reconnects and reads current state instead of treating the event stream as a durable queue.

Work-state writes can have an additional local guard for selected project and list scopes. The guard sends the proposed change to a configured local command and accepts only a bounded allow or refuse answer; a missing, invalid, timed-out, or malformed guard refuses the write.

Private media reads use a stricter boundary than ordinary local API reads. They require the local socket and the worker's own page origin, and they expose only safe media metadata or approved variants. Readiness distinguishes available, still pending, deleted, and rejected media.

The event stream also has a bounded per-client queue. A client that stops reading is disconnected once its pending data reaches the limit, which lets the browser reconnect instead of making the worker retain an unbounded history.

References: src/…/middleware.ts• L140-175 src/…/middleware.ts• L232-328 src/…/DataRoutes.ts• L230-256 src/…/MemoryRoutes.ts• L31-58 src/…/MediaRoutes.ts• L13-55 src/…/MediaRoutes.ts• L123-223 src/…/MemoryIngestRoutes.ts• L102-143 src/…/SessionRoutes.ts• L621-661 src/…/SettingsRoutes.ts• L244-406 src/…/WorkStateRoutes.ts• L62-169 src/…/work-state-write-guard.ts• L40-91 src/…/SSEBroadcaster.ts• L6-16 src/…/SSEBroadcaster.ts• L25-143 src/…/MemoryFeedInvalidation.ts• L43-47

Session context delivery

Session context gives a new session a compact view of relevant memory and current work state. The runtime can serve a precomputed block for known project, platform, and display variants. It uses the live path when health data or session-specific reply data makes a block unsafe to reuse.

The cache is local-first and follows database invalidation. Deletions, merges, imports, sync changes, and relevant work-state changes remove affected files before a later render replaces them. Changes to work-state lists shown in SessionStart are removed at once, and a render that started before the change cannot put old content back. If cloud sync is not caught up, the runtime removes cached blocks and returns to live reads until the local view is safe again.

References: src/…/ContextCacheService.ts• L1-30 src/…/ContextCacheService.ts• L131-165 src/…/ContextCacheService.ts• L290-319 src/…/ContextCacheService.ts• L344-397 src/…/SearchRoutes.ts• L147-195

Cloud synchronization and team services

Cloud synchronization extends local memory to other devices without making the cloud a requirement for local capture. The runtime keeps a local device identity, pushes eligible content when configured, exposes a status probe, and offers local-only recovery flows for stale work and conflicts. Media transfer follows its own optional path so native text memory remains available when media sync is off.

Team services provide optional shared context rather than a second local memory store. The worker signs requests with the configured cloud credential and returns team status, boards, briefs, and search results only when the install is connected to a team.

The database manager treats native text sync and media transfer as separate paths. Media cleanup remains durable across failures and retries on a later interval, while media uploads honor the current setting without requiring a worker restart.

References: src/…/DatabaseManager.ts• L46-144 src/…/DatabaseManager.ts• L146-176 src/…/CloudSyncRoutes.ts• L9-36 src/…/SyncRecoveryRoutes.ts• L38-69 src/…/TeamBrainRoutes.ts• L23-63

Interactive viewer

The viewer is a browser client served by the same runtime as the local API. It reads memory, work state, and media readiness through the mounted routes, receives live updates, and sends guarded review and settings changes back to the worker.

The viewer also carries local setup and work continuation flows. Setup can scan, pause for consent, resume installation, import history, and report background work. My Work can refresh summaries, continue or open supported conversations, and stop those actions. These actions remain local-only and use the viewer origin because some of them can start work or open the user's own agent session.

The worker loads viewer pages only when a client requests them. If an update replaces the UI files while the worker is still running, the page reports the install problem and offers a restart path instead of making the API unavailable. The restart page waits for a different process that is also ready, not only for a port that accepts connections.

The work view turns captured work into a human review surface. It can show recorded evidence and deliverables, accept review decisions, manage rules and focus areas, and coordinate setup or shared focus pages. Review writes use the viewer origin and a content fingerprint so a stale screen cannot overwrite newer work. Work-view file and deliverable reads are restricted to the local viewer and are served in a sandboxed form.

For browser-side flows and user actions, see Interactive viewer client.

References: src/…/ViewerRoutes.ts• L12-84 src/…/ViewerRoutes.ts• L215-363 src/…/WorkViewRoutes.ts• L118-147 src/…/WorkViewRoutes.ts• L804-926 src/…/WorkViewRoutes.ts• L927-972 src/…/MediaRoutes.ts• L155-223 src/…/ServerViewerRoutes.ts• L3-11 src/…/ServerViewerRoutes.ts• L46-63

MCP client access

The runtime also provides read-oriented MCP access for compatible agent clients. MCP uses the same scoped memory and audit boundary as the API instead of creating a separate store.

Recall is staged: a client searches a compact index, inspects nearby timeline context, and fetches selected observation details. The worker applies the same project read-key rules to the index, timeline, and detail stages. Tool names, arguments, result limits, and project scope are checked before a request reaches storage.

References: src/…/recall-mcp-server.ts• L26-121 src/…/recall-mcp-server.ts• L142-238 src/…/ProgressiveMemorySearch.ts• L26-127 src/…/WorkStateRoutes.ts• L62-151

Runtime modes

Local and managed operation

The default local service binds to loopback. Managed and container deployments can provide an explicit host and port, but they must use real authentication and shared queue infrastructure. Loopback trust and an in-process queue are local-runtime choices, not safe network-service boundaries.

The worker can select Claude, Gemini, Codex, OpenRouter, or a generic OpenAI-compatible provider. A source-specific provider mapping can override the global choice. A local OpenAI-compatible endpoint can work without a key when that endpoint allows it. OpenAI-shaped providers use streaming when supported and fall back to a plain response when an endpoint rejects streaming fields. Provider adapters share one session lifecycle and return a common result and error meaning.

Provider selection can move work to a configured fallback during a quota or availability hold and can probe the primary again after recovery. The same dispatch decision is used for generator admission and status, so a displayed provider does not differ from the provider that receives new work. The corpus API agent follows the selected API provider and does not silently move corpus questions to Claude.

Codex runs through a bounded app-server client. Each turn uses a private workspace and a scoped credential home. The runtime disables tools, inherited instructions, MCP servers, and other unrelated capabilities, then checks the app-server's isolation report before sending memory text. A missing or invalid ChatGPT login, forbidden capability, empty billed turn, or malformed structured answer stops the run rather than repeating paid work. A changed login causes a child process to refresh before a recovery probe. Private app-server roots are removed after the child exits, and stale roots from a dead worker are swept so a crashed worker does not leave old credentials and workspaces behind.

Claude classifies setup, authentication, quota, model, context, and transient failures before the session runner decides whether to pause, retry, switch provider, or require operator action. If a gateway rejects the thinking setting, the next generation omits that setting rather than repeating the same rejected request.

For provider runtime behavior, see Observation generation and provider runtime.

References: src/…/streamed-chat-completion.ts• L1-23 src/…/streamed-chat-completion.ts• L294-355 src/…/provider-dispatch.ts• L104-167 src/…/provider-dispatch.ts• L197-250 src/…/provider-dispatch.ts• L491-609 src/…/ClaudeProvider.ts• L75-89 src/…/ClaudeProvider.ts• L150-287 src/…/CodexAppServerClient.ts• L301-389 src/…/CodexAppServerClient.ts• L578-705 src/…/CodexAppServerClient.ts• L808-889 src/…/GeneratorRunner.ts• L222-379

Health signals

The service reports separate signals for liveness, initialization, dependency health, queue work, provider state, and search support. Processing status also reports sessions parked for a provider slot, the last successful store, and sessions abandoned after repeated response stalls. A client can therefore distinguish a running service from a service that is ready to generate memory.

Provider quota snapshots are kept by account profile and window. The worker pauses subscription-backed generation near configured limits so background capture does not consume the allowance needed for interactive use. API-key runs do not use that subscription guard. Missing provider tools, unusable logins, unsafe isolation, and missing vector-search support are recorded as setup or degraded health rather than retried as ordinary provider work.

Dependency checks use the worker's effective environment when they test optional vector-search tools. A missing uvx command keeps vector search unavailable but does not stop local memory reads and writes. A failed or corrupt vector write is also non-fatal; the local store remains authoritative and later search can use keyword results.

The worker can provision the tree-sitter CLI when the installed package is present but its binary is not usable. This keeps smart file search, outline, unfold, and the file-read gate available for marketplace installs whose package lifecycle scripts did not run. A source checkout without the package has nothing to provision.

Queue and generation boundaries may be disabled without making HTTP memory reads and writes unavailable. The same graceful degradation applies to vector search: keyword search and local writes remain available while the optional dependency is repaired.

For queue roles and process recovery, see Server jobs and process supervision.

References: src/…/RateLimitStore.ts• L302-325 src/…/RateLimitStore.ts• L503-537 src/…/dependency-preflight.ts• L165-209 src/…/tree-sitter-cli-provisioning.ts• L13-42 src/…/DataRoutes.ts• L790-806 src/…/Server.ts• L216-240 src/…/errors.ts• L24-47 src/…/idle-exit-monitor.ts• L136-182

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep route adapters and the shared ingest path aligned when session, event, native prompt, platform-source, receipt, or direct-file-ingest contracts change.
  • Keep local API token checks, exact open UI file paths, trusted-host checks, browser-origin checks, private media checks, and remote read-only allowlists aligned across every new route.
  • Keep API-key scopes and team/project checks aligned with every new server memory or job route.
  • Keep the worker bind-host decision aligned with the meaning of legacy TV settings and the local API token. A non-loopback bind must not accidentally expose provider settings.
  • Keep the bounded in-memory buffer, paid-send claims, parked batches, transcript replay rules, committed receipt checks, and provider claims aligned so restart recovery does not create duplicate paid work.
  • Keep capture-disable and provider-exit categories aligned with whether buffered work is discarded, preserved, retried, or reported.
  • Keep durable storage confirmation before SSE broadcasts, sync nudges, alerts, and optional integrations.
  • Keep provider result fields aligned with response parsing, storage, token accounting, media evidence, and live broadcasts. Keep summary progress rules aligned with the fields the parser can store.
  • Keep provider error classes aligned with paid-send accounting. A billed but unreadable response must not become a safe duplicate retry.
  • Keep streaming fallback, endpoint capability memory, usage accounting, and output-start classification aligned for every OpenAI-shaped endpoint.
  • Keep provider selection, source mappings, quota holds, fallback credentials, corpus-agent choice, and single-probe claims aligned between status and generator admission.
  • Keep search fallback, bounded candidate windows, progressive index identifiers, project read keys, date windows, and corpus selection aligned. A corpus rebuild must use the saved filter and must not silently replace a corpus with a destructive shrink.
  • Keep SessionStart cache variants, project read-key expansion, invalidation timing, work-state list scope, and sync catch-up state aligned so cached context cannot outlive local or remote changes.
  • Keep work-view snapshots, fingerprints, review state, local file guards, and live events aligned so a stale review cannot change current work.
  • Keep the work-state write guard schema, project matching, command timeout, and refusal handling aligned with the route's conflict response.
  • Keep media readiness states, owner-only details, same-origin pixel access, replica resolution, and deletion rechecks aligned.
  • Keep the provider dependency preflight's effective PATH lookup aligned with the dependency health state and the vector-search fallback.
  • Keep the tree-sitter package check, binary verification, checksum set, and smart file-read gate state aligned when provisioning rules change.
  • Keep Codex isolation attestations, private credential roots, child recycling, stale-root cleanup, and paid-output error classes aligned when the app-server contract changes.
  • Keep provider fallback admission, gateway probe claims, provider status, and session resume behavior aligned when provider selection changes.

Important failure modes

TriggerConsequenceGuard
A protected request has no valid key or scopeThe memory or job operation is rejected before route work.Shared authentication and team/project checks run before the handler.
Local API token mode is enabled and a request omits the tokenThe request receives 401; loopback alone does not grant access.The token guard requires the header, or a query token for reads, except for exact data-free UI routes.
A request uses an untrusted host name or forwarded client headersThe worker rejects the request before it reaches a route.Trusted host and local-client checks reject DNS-rebinding and proxy ambiguity.
The worker binds to a non-loopback host without a local API tokenThe full worker API, including provider settings, can be reached from the network.The runtime warns; a leftover TV token causes a loopback fallback instead of a read-only network mode.
A local browser from another origin sends a destructive worker requestThe settings, capture, import, corpus, backup, work-state, or work-view change is refused.Browser writes require the service's own loopback origin; origin-less hooks and CLI clients remain supported.
A configured work-state guard is invalid, times out, or returns malformed outputThe guarded write is refused.The guard validates its config and answer, limits output, and kills a command after two seconds.
A private media request comes from another page, port, or forwarded clientMetadata or image bytes are refused.The media guard checks the socket peer, host, forwarding headers, and own-page origin.
A media replica is not ready or was deleted during a readThe client sees a pending, rejected, or not-found result rather than stale bytes.Replica resolution and a post-read metadata check fence the response.
A direct memory ingest source is outside the supported projects directoryNo file is stored.The ingest route validates the source before walking it.
A client stops reading the live event streamIts queued frames are dropped when the bounded limit is reached, and it must reconnect.SSE treats events as invalidation hints and disconnects stalled consumers.
No provider can serve a queued sessionCaptured work stays buffered instead of producing an observation.Provider dispatch uses a configured fallback when available and preserves work for a later probe or operator retry.
A provider response is billed but empty or malformedThe batch is not safely resent and may settle without a new observation.Provider errors carry paid-send meaning and response processing handles empty output as a terminal turn result.
A streamed provider reply stops after output startsThe response is treated as an output failure and is not resent.Stream state records whether output started before classifying the failure.
A provider hits context or output limitsThe current generation cannot continue safely.The runtime recycles the conversation or uses one bounded reasoning-off retry.
Claude quota reaches a guard or provider rejectionBackground generation pauses and queued work remains available.Per-window rate-limit state, account profiles, reset grace, fallback selection, and bounded probes control admission.
Claude or Codex rejects setup, login, model, isolation, or request configurationGeneration pauses instead of repeating the same doomed start or paid turn.Provider classification records setup or paid-output meaning; the runner waits for repair or routes work to an available fallback.
A Codex app-server child keeps old credentials after login changesA recovery probe can fail against the old login held in the child process.Idle clients are recycled before the probe so new children read the current login.
A Codex worker dies before normal cleanupPrivate roots can remain in the temporary directory.Each root records its owner process and the next client sweep removes roots whose owner is dead.
A provider dependency is missing or cannot spawnNew generator starts stop until setup changes.Preflight and start gates record dependency health and avoid repeating the same doomed start.
The tree-sitter package is present but its binary is missing or unusableSmart file reads and syntax-aware file tools stay unavailable.Worker startup provisions a pinned, verified binary when the package exists.
Vector search is unavailable, times out, or cannot write a valid collectionMemory writes continue and search falls back to keyword behavior.Search uses bounded semantic work and local hydration; Chroma failures are reported as degraded support rather than storage failures.
A worker restarts while its in-process buffer holds workBuffered work disappears from that process, but replay can recover source events.The buffer is deliberately process-local and transcript checkpoints advance only after work is stored.
A response stalls after the provider receives a batchThe claimed batch can be retried, parked, or discarded after bounded attempts.The response pacer fences late frames and the runner limits unattended resumes.
A live buffer reaches its size or age limitNew or expired capture is skipped rather than creating an unbounded backlog.Per-session and total limits, duplicate tool-use checks, and expiry pruning bound live work.
Capture is disabled while a generator is between messagesUnsubmitted buffered work is discarded, while the in-flight request can still finish and record its evidence.The session checks capture settings at safe message boundaries and preserves delivery identities.
A cached context variant is rendered before a removal or relevant work-state change completesA new session could receive deleted memory or stale open work.The runtime removes matched files synchronously and discards an in-flight render that crossed the invalidation.
Cloud sync is behind or loses its live update linkCached context is not safe to serve until the local view catches up.The cache removes files while sync is not servable and re-renders known variants after catch-up.
A cloud-sync recovery request uses a stale preview or epochThe repair is refused instead of acting on changed data.Recovery requires local access, preview tokens, and expected epochs.
A corpus client disconnects during provider-backed prime or queryThe request-scoped provider work is aborted; a build or rebuild may remain as tracked background work.The corpus route watches both response and socket close events and separates client work from persistent builds.
A second corpus operation uses the same name while one is activeThe second operation is rejected instead of racing the first file update.Per-corpus admission serializes build, rebuild, prime, query, and reprime work.
A corpus rebuild would remove most stored observationsA valid stored corpus could be replaced by a bad or stale filter result.The rebuild returns a conflict until the caller explicitly accepts the shrink.
An API corpus query uses a corpus that was not primed for the selected provider and versionThe query returns CORPUS_NOT_PRIMED instead of using a corpus session the reader did not prepare.The API agent binds its synthetic session identity to the provider and corpus version.
A work-view review uses an old snapshotThe user's decision could apply to changed work.Review writes check the expected content fingerprint and current lifecycle.
Viewer assets are absentThe interactive page is unavailable while API routes remain usable.Viewer mounting is separate from the API route set and reports a restartable install error.
Database initialization hits a transient SQLite busy stateWorker readiness can fail even though the database is healthy.Initialization closes partial state and retries bounded busy errors inside the readiness window.

Key files

FileWhy to read it
src/…/create-server-service.tsShows how the server store, auth, queues, providers, and search support are assembled.
src/…/ServerService.tsShows service lifecycle, route assembly, health, and shutdown.
src/…/ServerV1PostgresRoutes.tsShows the authenticated server memory and job surface.
src/…/postgres-auth.tsShows how a server key becomes scoped request identity.
src/…/Server.tsShows the common HTTP boundary and readiness behavior.
src/…/DatabaseManager.tsShows local storage, search, media, backup, cloud sync, and recovery setup.
src/…/db-init-retry.tsShows how transient database startup contention is recovered without hiding real failures.
src/…/worker-bind-host.tsShows how legacy TV settings and the local API token control network exposure.
src/…/middleware.tsShows local token mode, trusted-host checks, browser-origin rules, and remote read-only access.
src/…/shared.tsShows the shared capture path and its privacy, project, deduplication, and handoff gates.
src/…/work-state-write-guard.tsShows the optional external approval boundary for selected work-state writes.
src/…/MemoryIngestRoutes.tsShows direct import of native memory files into the local observation surface.
src/…/MemoryRoutes.tsShows explicit memory saves and browser-origin protection.
src/…/DataRoutes.tsShows the local memory, import, deletion, and processing-status surface.
src/…/MediaRoutes.tsShows private media access, readiness states, and replica resolution.
src/…/SessionRoutes.tsShows session capture, generator admission, provider switching, and operator retries.
src/…/SearchManager.tsShows semantic search with bounded candidate work, local fallback, project scope, date ordering, and category completion.
src/…/ChromaSearchStrategy.tsShows bounded semantic candidate retrieval and SQLite hydration.
src/…/errors.tsShows how vector service failures become degraded search support instead of local storage failure.
src/…/HybridSearchStrategy.tsShows file matching with semantic ranking and metadata fallback.
src/…/ProgressiveMemorySearch.tsShows staged index, timeline, and detail recall for agent clients.
src/…/CorpusRoutes.tsShows long-running corpus work, client disconnects, and per-corpus admission.
src/…/CorpusAgent.tsShows the provider-neutral corpus contract and runtime choice between agent implementations.
src/…/ApiCorpusAgent.tsShows provider-bound corpus questions, bounded excerpts, and versioned synthetic sessions.
src/…/CorpusRenderer.tsShows the shared shape used to present corpus observations to question-answering agents.
src/…/KnowledgeAgent.tsShows Claude Agent SDK corpus priming, querying, and expired-session recovery.
src/…/summary-content.tsShows which parsed summary fields count as durable progress.
src/…/SessionManager.tsShows session buffering, claims, confirmation, provider pauses, and delayed resume.
src/…/SessionMessageBuffer.tsShows the process-local work boundary and transcript-replay recovery model.
src/…/ResponseProcessor.tsShows how provider output becomes durable observations, evidence, and downstream events.
src/…/GeneratorExitHandler.tsShows which generator exits preserve live work and which discard it.
src/…/abort-reason.tsShows the shared meaning of generator stop categories.
src/…/provider-dispatch.tsShows provider selection by source, quota fallback, and recovery probes.
src/…/GeneratorRunner.tsShows provider failure booking, fallback resumes, and bounded retry or discard decisions.
src/…/streamed-chat-completion.tsShows streaming liveness, usage assembly, endpoint fallback, and paid-send classification.
src/…/ClaudeProvider.tsShows Claude provider setup, response handling, and refusal classification.
src/…/GeminiProvider.tsShows Gemini endpoint and quota or error classification.
src/…/CodexAppServerClient.tsShows the bounded, isolated Codex runtime and its credential-refresh, output validation, and stale-root cleanup behavior.
src/…/ContextCacheService.tsShows how SessionStart context variants are learned, invalidated, and kept safe during sync.
src/…/SSEBroadcaster.tsShows the bounded live-event delivery contract for viewer clients.
src/…/SettingsRoutes.tsShows settings redaction, write boundaries, provider choices, and dependency health.
src/…/WorkStateRoutes.tsShows the agent work-state read and write boundary.
src/…/WorkViewRoutes.tsShows the local review, setup, conversation, rules, focus, evidence, and live-view boundary.
src/…/ViewerRoutes.tsShows shared UI pages, health, restart behavior, and the live event stream.
src/…/ServerViewerRoutes.tsShows how the viewer shares the runtime with the API.
src/…/dependency-preflight.tsShows startup checks for provider and vector-search dependencies.
src/…/tree-sitter-cli-provisioning.tsShows how the worker makes the syntax tool available for smart file reads.