# Plugin Reference This page covers advanced plugin behavior, environment variables, and stream reliability controls. ## Observer and settings UI See the [Settings guide](user-guide.md#settings-modal) for connection modes, model choices, and save/apply behavior. ## Running OpenCode with the plugin This plugin's CLI calls require the grouped command tree. Update the CLI and plugin together, then restart OpenCode. An older CLI without these command paths cannot serve the plugin's CLI calls or fallbacks. One `@codemem/opencode-plugin` package serves OpenCode 1.18.29+ through its `server()` entrypoint and OpenCode 2 through its `setup()` entrypoint. OpenCode 2 support is validated against the exact stable `@opencode/cli@2.0.24` and `@opencode/plugin@2.0.24` releases; Codemem labels its OpenCode 2 integration beta. OpenCode 1 supports the capture and recall behavior below. On OpenCode 2 the plugin captures user and assistant messages, terminal usage, tool results, and session lifecycle events. Its automatic recall uses `session.context` only: the latest user-message ID is required, missing identity skips safely, and retries or tool continuations replay retained context byte-for-byte. Compaction, title, and generate hooks remain isolated. Both the default message surface and legacy system surface work. 1. Install the configured npm plugin on either host. OpenCode 1 contributors can instead remove that entry temporarily and start OpenCode inside this repo to load the checkout-local V1 source. 2. Every tooling session creates memory artifacts in SQLite. 3. Prompt-time memory injection appends volatile recall output to the latest user message by default, preserving the stable system/history prefix for provider prompt caches. 4. Use `codemem memory stats` and `codemem memory list` to confirm ingestion. 5. Browse the viewer at the printed URL. OpenCode loads configured npm plugins and project-local `.opencode/plugins/` files as separate sources. In this repository, the local wrapper loads the V1 source but is a no-op on OpenCode 2. For OpenCode 1 source testing, temporarily remove the configured npm entry before launching from the checkout so the local wrapper cannot lose the first-registration race. For OpenCode 2 source testing, add this checkout's `packages/opencode-plugin` directory to the host's `cli.json` `plugins` list, temporarily remove the npm entry, and restart the TUI. Restore the npm entry after testing; removing it without adding the package directory leaves Codemem inactive on OpenCode 2. ### OpenCode host support, troubleshooting, and rollback Host support at a glance: | Host | Requirement | Status | | --- | --- | --- | | OpenCode 1 | 1.18.29 or newer (`engines.opencode`) | Supported | | OpenCode 2 | validated on exact `@opencode/cli@2.0.24` and `@opencode/plugin@2.0.24` | Beta integration | Install on either host with `codemem setup --opencode-only` (or `npx -y codemem setup --opencode-only`). Setup writes the singular `plugin` key on purpose: OpenCode 1 requires it, and OpenCode 2 translates it into its native `plugins` configuration, so one entry serves both hosts. The manual `mem-status`, `mem-recent`, and `mem-stats` tools keep their hyphenated IDs on both hosts. Troubleshooting: - **No automatic recall on OpenCode 2.** Recall runs through `session.context` and requires a non-empty, non-whitespace latest user-message ID. When the ID is missing or blank, that turn skips recall rather than guessing identity; capture and the manual tools continue. Retries and tool continuations replay retained context and do not retrieve again, so a repeated turn without new context is expected. - **No notifications on OpenCode 2.** OpenCode 2 loads `@codemem/opencode-plugin/tui` automatically beside the server plugin. The companion subscribes to the server plugin's location-scoped RPC notices and replays notices emitted during startup. Restart the TUI after installing or upgrading the plugin; notification delivery is best-effort and does not affect capture or recall. - **Duplicate registration warning.** `codemem duplicate plugin registration skipped` in `~/.codemem/plugin.log` means OpenCode loaded Codemem twice for one project, usually a configured npm entry plus a checkout-local copy. Remove one of them. The first server registration owns notifications as well as capture and recall. - **Capture looks stalled on either host.** Run `codemem diagnostics capture status` and follow the [post-restart config sanity checklist](#post-restart-config-sanity-checklist); both hosts share the same raw-event pipeline and spool behavior. - **Console windows flash on Windows when OpenCode loads the plugin.** Current releases start every plugin child process with a hidden console window. That covers CLI version and `npx` bootstrap probes, plugin CLI commands, the startup `codemem --version` and `git rev-parse` checks, and viewer auto-start. Older releases opened one visible window per probe in each connected project, so upgrade the plugin if windows still appear. Other platforms are unaffected. - **Raw-event POST returns `409 viewer_identity_mismatch`.** Check that the viewer and host use the same database, home, device, actor, runtime/workspace, and embedding settings. OpenCode pauses capture HTTP attempts for the current plugin runtime and continues saving new events to its existing spool. It shows one warning and writes `raw_events.delivery.paused code=viewer_identity_mismatch` with restart guidance to `~/.codemem/plugin.log`, without copying the response body or target values. Align `CODEMEM_*` settings, then restart the viewer and OpenCode to resume saved events. Restarting only the viewer does not clear the plugin's pause. If OpenCode also reports memory-only events or a full spool, preserve the backlog and repair spool capacity before restarting OpenCode to avoid losing unsaved events. An older viewer may reject a host with no `CODEMEM_CONFIG` override when the viewer explicitly sets the same default config file. For the older-viewer case, update and restart the viewer's owning service. Before restarting OpenCode, confirm that pending events are saved and there are no unresolved memory-only or full-spool warnings. Restart OpenCode to clear the delivery pause, then check backlog status. Keep spool files until delivery is confirmed. The receiver accepts an omitted override only when the explicit path matches the core config resolver's implicit read path, including workspace/runtime fallback and JSON/JSONC selection; it does not ignore different configs or other identity fields. The core global fallback is `~/.config/codemem/config.json` (or `config.jsonc` when JSON is absent), not `XDG_CONFIG_HOME`. Rollback: - **Stop the OpenCode 2 path.** Set `CODEMEM_PLUGIN_IGNORE=1` in the environment that launches OpenCode 2, or remove the Codemem plugin entry from that host's config. OpenCode 1 keeps working from the same installed package. - **Return to OpenCode 1.** Launch OpenCode 1.18.29+ with the same config. Both hosts write one raw-event stream and one SQLite database, so switching hosts in either direction needs no storage migration. - **Pin changes.** Codemem only moves its OpenCode 2 pin in a dedicated change that reruns the [pinned contract](opencode-v2-contract.md) and packed-host smoke tests; see [versioning](versioning.md#opencode-host-compatibility). ### Repository-only lint feedback When OpenCode runs from a codemem source checkout, `.opencode/plugins/lint-feedback.js` auto-loads repository-owned OpenCode 1 and OpenCode 2 adapters backed by `packages/opencode-plugin/src/lint-feedback-core.ts`. Both run the installed Biome launcher through Node without a shell and check JavaScript or TypeScript paths included by `biome.json` when handled by `edit`, `write`, `apply_patch`, or `patch`, including move destinations; paths outside that configured Biome scope are ignored. They append at most 10 new or worsened diagnostics and leave the edit intact when Biome fails or exceeds its 10-second timeout. Existing diagnostics are a warning-level ratchet rather than a cleanup mandate. For anonymous command callbacks, the matcher adds the enclosing factory name to method-based warning identities such as `addJsonOption`. It recognizes named, non-generic `create*Command(): Command` function declarations with no parameters and an explicit `Command` return type. Babel parses TypeScript first, with a JSX retry, so regex literals, division, and template contents do not change factory boundaries. Source that cannot be parsed cleanly keeps its unqualified identity. The parser is a repository development dependency and is not included in the published plugin. OpenCode 2 support is pinned and host-tested against 2.0.24. Its tool hooks make feedback visible in the successful tool result and isolate overlapping calls by session and call ID. OpenCode 2 exposes no shell post-execution hook, so shell-driven file changes bypass immediate feedback; run `pnpm lint:delta -- --base ` at a stable checkpoint. Hook limitations never replace or disable the required CI ratchet. The repository-only scope includes `packages/ui/playwright*.config.ts`, `packages/ui/visual/**/*.ts`, and `packages/ui/scripts/visual-*.mjs`, matching Biome's UI visual tooling includes. This hook is contributor tooling only. Neither the repository wrapper nor `src/lint-feedback.ts` is included in the published `@codemem/opencode-plugin` package, so installing codemem does not activate it. Restart OpenCode after changing the checkout's plugin configuration. If the plugin fails to load because a development dependency such as `@babel/parser` is missing, its error names the package and the recovery steps. Run `pnpm install --frozen-lockfile` from the repository root, then reload OpenCode. If the running OpenCode service still reports the same missing package, run `opencode service restart`. Restarting interrupts every session that uses the shared service. The Biome pilot is the repository's bounded lint experiment. It covers package `src` trees, the canonical published OpenCode runtime under `packages/opencode-plugin/.opencode`, the two checkout plugin entrypoints, selected adapter hooks, package JSON, and root TypeScript configuration. The OpenCode runtime keeps its existing two-space formatting for package stability; Biome still applies lint rules, including the complexity-15 and 50-line production thresholds. The tracked JS/TS inventory at the 0.45.0 baseline is: | Source family | Files | Biome status | | --- | ---: | --- | | Existing package source and selected hooks/config | 770 | Covered | | Published OpenCode runtime and checkout entrypoints | 10 | Covered by this extension | | E2E harness | 36 | Excluded from this bounded pilot; exercised by E2E jobs | | Root scripts and configuration | 22 | Excluded except `scripts/ci-workflow.test.mjs` and `vitest.config.ts`; exercised by focused script tests | | Legacy CLI plugin harness | 18 | Excluded; compatibility tests run through the plugin smoke job | | Package support scripts, tests, and configuration | 12 | Excluded; package-specific checks remain authoritative | | Plugin package shims, smoke scripts, and contract fixture | 7 | Excluded; packed-artifact and host smoke tests remain authoritative | | Other adapter entrypoint | 1 | Excluded; adapter-normalizer tests remain authoritative | | Generated adapter bundles | 2 | Excluded; generated from `packages/core/src/claude-hooks.ts` and `codex-hooks.ts` | | Frozen evaluation snapshots | 2 | Excluded; immutable baseline fixtures | | Type declaration files | 4 | Excluded; checked by TypeScript/package contract tests | Generated normalizer bundles and frozen evaluation snapshots must not be lint-fixed directly. Change their source or regeneration workflow instead. Expanding coverage leaves the existing 1,592 warnings unchanged and exposes 63 warnings plus one informational diagnostic in the canonical runtime. The new diagnostics break down as follows: | Rule | Count | | --- | ---: | | `noExcessiveCognitiveComplexity` | 42 | | `noExcessiveLinesPerFunction` | 17 | | `noNestedTernary` | 2 | | `noUnusedFunctionParameters` | 1 | | `noPrototypeBuiltins` | 1 | | `noUselessEscapeInRegex` (information) | 1 | | Runtime path | Diagnostics | | --- | ---: | | `packages/opencode-plugin/.opencode/lib/runtime.js` | 50 | | `packages/opencode-plugin/.opencode/lib/opencode-v2-adapter.js` | 7 | | `packages/opencode-plugin/.opencode/lib/delegation-context.js` | 4 | | `packages/opencode-plugin/.opencode/lib/compat.js` | 2 | | `packages/opencode-plugin/.opencode/lib/raw-event-spool.js` | 1 | Run the same diagnostic comparison outside the editor with: ```text pnpm lint:delta -- --base [--head | --staged] [--json] ``` `--base` is required. Use `--base auto` to compare from the merge base of an available local remote-default ref (including renamed remotes) and fall back to `HEAD`; the pre-commit hook uses this mode so commits do not depend on `origin/main` or include upstream-only changes. Pass `--head` for a committed ref-to-ref comparison, or pass `--staged` to compare only the Git index as the pre-commit hook does; those flags cannot be combined. Omit both to freeze the current working tree, including untracked files that are not ignored. The command materializes detached temporary worktrees and never stashes, resets, or checks out over the active worktree. It runs the pinned Biome binary with the head snapshot's policy against both sides, then compares diagnostics only for added, modified, renamed, or deleted paths. Exit code `0` means no new diagnostics or policy weakening, `1` means regressions were found, and `2` means the comparison could not be trusted. JSON output includes every regression; human output shows the first ten. Appending lint overrides is accepted only when every new override uses non-negated includes and adds error-only rules. Editing or removing existing overrides, adding exclusions or suppressions, weakening rule levels, removing includes, changing Git ignore policy, disabling linting, increasing thresholds, missing refs, tool failures, and malformed or incomplete Biome reports fail closed. Include matching uses a state machine rather than wildcard-expanded regular expressions. Matching work grows with the product of pattern and path lengths, including nonmatches with repeated wildcards or brace alternatives. Slash handling, globstars, ordinary character classes, alternatives, ordered exclusions, and literal folder prefixes retain their existing behavior. There is one rare character-class compatibility exception: if the first closing `]` is escaped, the matcher accepts a literal suffix up to the next `]` (for example, `[a\]b]` or `[\]]`). It throws `SyntaxError` if that suffix contains `*`, `?`, `{`, `}`, `[`, or another backslash, or has no closing `]`. The previous regex expansion could reinterpret those suffix tokens while the class remained open; patterns such as `[\]{a,b}]` now fail closed rather than retaining that accidental syntax. Ordinary classes, including metacharacters before their first closing bracket, are unchanged. Pull request CI runs this comparison inside the required `TypeScript Lint` job using the event's immutable base and tested merge commits. The silent CLI invocation uploads one valid, complete JSON report and emits at most ten annotations total; unchanged legacy debt passes. Because enforcement extends an existing required status, it needs no separate branch-protection setting. Comparison results are not cached, so revisions and tool or policy changes cannot reuse a stale result; dependency caching remains lockfile-keyed. OpenCode prompt-time pack construction and prompt-pack ledger transitions use the long-lived local viewer first. Retryable connection, timeout, endpoint-version, server, or malformed-response failures fall back to the compatible CLI path. Validated request errors are terminal only after a compatible profile handshake; before compatibility is established, a structured request error may indicate a foreign or older process and uses the CLI fallback. Policy and authorization errors remain terminal. A `viewer_contract_unsupported` response is likewise terminal after a compatible profile handshake and may fall back before one. The HTTP timeout uses `CODEMEM_INJECT_HTTP_MAX_TIME_S` (default: 2 seconds). Pack and ledger requests include their resolved default or explicit database, identity/config, compression, and embedding targets. The viewer also rejects a cached store identity that no longer matches current database/config resolution. A mismatch uses the local CLI fallback exactly once instead of reading or retrying another local profile. A payload-free profile handshake runs before each POST and returns `protocol_version` plus `min_supported_protocol_version`; clients accept overlapping ranges and interpret an older profile without the minimum as a single-version range. Fetch redirects are disabled so prompt-derived request bodies are not replayed to another endpoint. ### OpenCode prompt-path benchmark The following results are historical source-tree measurements from before the current phase isolation. They cover the **OpenCode 1 plugin path only** and exclude Claude and Codex latency. See the [benchmark methodology](../scripts/eval/README.md#prompt-path-performance-benchmark) for the current isolated-phase process and counter rules. The privacy-safe report contains no prompt, memory content, IDs, or paths. | Mode | Median / p95 | Prompt children | | --- | --- | --- | | Direct CLI | 857.459 / 1001.124 ms | — | | Healthy Viewer | 9.478 / 10.772 ms | `pack=0`, `ledger=0`, `other=0`, `failed=0` | | Classified Viewer-unavailable fallback | 832.101 / 881.455 ms | `pack=30`, `ledger=30`, `other=0`, `failed=0` | ## Claude marketplace install Codemem's Claude integration is hook-first and distributed through a Claude plugin marketplace source in this repo (`.claude-plugin/marketplace.json`). In Claude Code, add the marketplace and install the plugin: ```text /plugin marketplace add kunickiaj/codemem /plugin install codemem ``` The plugin starts MCP with the TS CLI: - `codemem mcp` Claude's Node/ESM wrapper normalizes each native hook once, then sends the exact normalized envelope to the local server's canonical `POST /api/raw-events` endpoint. Healthy HTTP ingestion starts no `codemem` or `npx` child: both HTTP `202` replies with numeric `accepted`/`queued` counts and legacy replies with numeric `inserted`/`skipped` counts count as success. Queued acceptance confirms durable enqueue, not completed extraction; it also ends a successful enqueue-only retry after a boundary request fails. Malformed replies or HTTP failures still use the existing fallback path. On a retryable failure, the wrapper sends the same serialized envelope to: - `codemem enqueue-raw-event` - `npx -y codemem@ enqueue-raw-event` The wrapper never remaps the native payload during fallback, so event identity is identical across HTTP and direct enqueue. Named `POST /api/claude-hooks` remains a compatibility alias/caller for older packaged and plugin-free CLI paths. Transcript fallback scans backward through at most the final 16 MiB using a bounded reusable chunk buffer and stops at the latest qualifying assistant record. When that tail starts immediately after a newline, the first complete record is retained; when it starts in the middle of a record, the partial first record is discarded. JSONL records may use LF or CRLF, and UTF-8 characters remain valid across chunk boundaries. Claude preserves its existing best-effort failure posture: if Viewer HTTP and both command fallbacks fail, the wrapper logs the failure and exits non-zero. It does not maintain a file spool; Codex's separately documented normalized-envelope spool is intentionally adapter-specific. You can update an existing marketplace install with: ```text /plugin marketplace update codemem-marketplace ``` Ingest one Claude hook payload through the installed wrapper: ```bash printf '%s\n' '{"hook_event_name":"SessionStart","session_id":"sess-1"}' | node plugins/claude/scripts/ingest-hook.mjs ``` Prompt-time retrieval runs through the packaged dependency-free Node hook. It validates the Viewer protocol, database, and runtime identity before sending identity-gated `POST /api/pack`. Claude prompt retrieval and event ingestion accept only explicit loopback Viewer hosts (`localhost`, `127.0.0.0/8`, or IPv6 loopback); non-loopback hosts are never fetched. By default, `SessionEnd` requests a best-effort boundary flush after enqueue rather than waiting for sweeper timing. Set `CODEMEM_CLAUDE_HOOK_FLUSH=0` to force enqueue-only behavior, and set `CODEMEM_CLAUDE_HOOK_FLUSH_ON_STOP=1` to include `Stop` boundary flush. Direct Viewer transport keeps the boundary request, durable HTTP retry, and command fallbacks inside one Claude Code host budget (1.5 seconds by default, configurable with `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS`), preserves command-fallback time after preprocessing and across both HTTP attempts, and reserves a 50 ms exit margin. The fallback reserve is normally 10% of the host budget, clamped between 500 ms and 5 seconds, but never exceeds half of the post-margin budget. `Stop` uses one 125-second internal budget under a 130-second packaged hook timeout, leaving startup and shutdown headroom. Override the boundary budget with `CODEMEM_CLAUDE_HOOK_BOUNDARY_TIMEOUT_MS`; `SessionEnd` still clamps its request to the live remaining host budget. The legacy `claude-hook-ingest` CLI fallback persists the boundary event, then extracts at most one 100-event batch. Remaining events wait for the Viewer or another invocation. The packaged wrapper above calls `enqueue-raw-event` and owns its host deadline separately. The legacy CLI has no overall extraction deadline, and limiting events does not bound an individual observer call's duration. The packaged template currently registers these hook events in `plugins/claude/hooks/hooks.json`: - `SessionStart` - `UserPromptSubmit` - `PreToolUse` (`Read` only) - `PostToolUse` - `PostToolUseFailure` - `Stop` - `SessionEnd` `UserPromptSubmit` runs `scripts/user-prompt-hook.mjs`, which: - sends the hook payload into capture ingest (`ingest-hook.mjs`) in the background, and - performs a payload-free compatible-profile check, retrieves an identity-gated Viewer pack, returns host-compatible `hookSpecificOutput.additionalContext`, then records delivery best-effort with a 500 ms cap. Healthy prompt-time Claude injection starts no `codemem` or `npx` prompt child. Retryable transport, version/profile, and local database/runtime identity mismatches start one compatibility chain: `codemem claude-hook-inject`, then the plugin-version-pinned `npx` equivalent if needed. Valid request failures after a compatible handshake, policy, authorization, and compatible-profile contract failures do not fall back. Pre-handshake structured request failures use the compatibility chain. Non-loopback Viewer hosts and redirects are rejected. Ledger failure never retries inline or changes already-written hook output. For Claude hooks, project resolution precedence is: 1. `CODEMEM_PROJECT` (if set) 2. repo/cwd-derived project name (`resolve_project(cwd)`) 3. payload `project` fallback (only when cwd is unavailable) `PreToolUse:Read` runs the dependency-free `scripts/pre-read-hook.mjs`. It checks ignore/disabled settings, a nonempty file path, cwd containment, file existence, and the size gate before context lookup or CLI execution. Files below 1,500 bytes are skipped unless they match the existing config/infra exceptions; `CODEMEM_FILE_CONTEXT_MIN_BYTES` overrides that threshold. Ignored events and missing paths do no retrieval or ledger work. Other skipped reads may record one best-effort HTTP ledger entry within 500 ms, but never start a CLI or open a local database. Eligible reads check the Viewer profile, database, and runtime identity, then send a target-paired `POST /api/file-context`. The server validates the action/body before acquiring the store and validates the target before querying or writing the ledger. Client project resolution retains the precedence above and uses filesystem git-root markers, not the Viewer's cwd or environment. Healthy and valid-empty responses start no `codemem` or `npx` child. Query failures return continuation with the existing `query_failed` attempt code; valid empty results never fall back. This retrieval adds context only; capture/extraction still uses `PostToolUse` / `PostToolUseFailure` tool results. Fallback is allowed for unavailable/retryable transport, malformed responses, older endpoints/profiles, or database/runtime target mismatches. A configured non-loopback Viewer host is rejected as policy and never starts local fallback. Policy/authorization failures, redirects, and compatible request rejections do not fall back. Only on fallback, the hook probes `codemem claude-hook-file-context --transport-profile` and requires visibility enforcement and deferred delivery; version strings alone cannot prove a prerelease contains the fix. If needed it probes/runs `npx -y codemem@` with the same capability requirement, without embeddings. A missing/invalid manifest version disables npx, never selects `latest`. An older pinned package without the capability returns no context rather than using an unsafe retrieval path. HTTP, capability probes, fallback lookups, and delivery updates share an eight-second budget under a ten-second packaged host timeout. `CODEMEM_FILE_CONTEXT_TIMEOUT_MS` can lower that internal budget, but cannot raise it above eight seconds. Profile/lookup HTTP calls each have a 750 ms cap; HTTP delivery updates have a 250 ms cap. CLI lookups reserve up to 1,500 ms within the same remaining budget for their delivery process, including CLI startup. Child output is limited to 64 KiB combined stdout/stderr, and deadline/output-limit failures terminate the spawned child group. Local filesystem checks run synchronously; these limits do not make a stalled filesystem interruptible. Selection uses the shared core runner: 40 authorized candidates, at most 15 displayed observations, specificity based on `files_modified`, one observation per originating session, and the existing five-minute freshness tolerance. Each HTTP/installed-CLI/npx lookup has a separate UUID attempt and a transport-qualified request ID linked to one hook invocation. A timed-out HTTP attempt can remain recorded but undelivered while a separate local attempt succeeds; no retry overwrites its timestamps or exposures. The server and transport CLI defer handoff until the hook's stdout write succeeds, then accept an acknowledgment matching the attempt/request/session. Replayed/conflicting attempts cannot claim delivery of a newly rendered artifact. Ledger or acknowledgment failures never change output or start another fallback. Direct non-transport CLI invocation retains its original handoff-before-return behavior. File-context retrieval obeys the same ownership and scope visibility rules as normal memory reads, including revocation and managed-scope proof checks. These checks run before result limits, so inaccessible memories neither appear in file context nor displace visible results. ## Codex integration Codex is a supported integration. The Codex plugin uses the same shared raw-event pipeline as Claude and OpenCode. It is packaged under `plugins/codex/` with `.codex-plugin/plugin.json`, bundled `.mcp.json`, and hook scripts under `plugins/codex/scripts/`. Codex's Node/ESM wrapper adds a timestamp and nonce when the host omitted a timestamp, normalizes exactly once, and sends the exact envelope to `POST /api/raw-events`. Healthy HTTP ingestion starts no `codemem` or `npx` child. After a retryable HTTP failure, it durably spools the normalized envelope before starting this fallback chain: - `codemem enqueue-raw-event`, then the pinned `npx` equivalent. - A successful fallback removes the envelope from `~/.codemem/codex-raw-event-spool`; if both fail, it remains there for a later HTTP drain. This is separate from the legacy native-hook spool. The same serialized envelope—and therefore the same event ID—is used by every transport. Named `POST /api/codex-hooks` remains a compatibility alias/caller for older packaged and plugin-free CLI paths. ```bash printf '%s\n' '{"hook_event_name":"SessionStart","session_id":"codex-1"}' | node plugins/codex/scripts/ingest-hook.mjs ``` `UserPromptSubmit` runs `scripts/user-prompt-hook.mjs`, which: - sends the hook payload into capture ingest (`ingest-hook.mjs`) in the background, and - performs a payload-free compatible-profile check, retrieves an identity-gated Viewer pack, and returns framed `hookSpecificOutput.additionalContext`; delivery recording is best-effort and capped at 500 ms. The packaged Codex hook is a dependency-free direct Viewer client. Healthy prompt retrieval starts no `codemem` or `npx` child. Retryable Viewer transport, version/profile, and local database/runtime identity mismatches and pre-handshake structured request failures use one local compatibility chain; validated request failures after compatibility is established, policy, authorization, and compatible-profile contract failures fail closed. Prompt and event HTTP reject non-loopback Viewer hosts. The injected pack is framed as codemem reference data, not instructions. The hook has a total 4.5-second prompt-output budget within Codex's 5-second host timeout, and always emits `{"continue": true}` so a hook failure does not block a session. ```bash printf '%s\n' '{"hook_event_name":"UserPromptSubmit","session_id":"codex-1","prompt":"what did we change","cwd":"/tmp/demo"}' | codemem codex-hook-inject ``` `codemem codex-hook-inject` is retained for compatibility and plugin-free setup. It now uses the same profile-validated, identity-gated Viewer HTTP retrieval before falling back to its local database pack. Like the packaged hook, it rejects non-loopback prompt retrieval and fails closed on policy, authorization, and compatible-profile contract errors; local packing is limited to classified compatibility failures. The packaged hook remains the zero-child healthy path. For Codex hooks, project resolution precedence matches the Claude hook path: 1. `CODEMEM_PROJECT` (if set) 2. repo/cwd-derived project name 3. payload `project` fallback (only when cwd is unavailable) `Stop` events map the inline `last_assistant_message` when present, and fall back to the last assistant message in `transcript_path` so final responses are captured even when the inline field is omitted. This fallback uses the same backward, bounded 16 MiB JSONL scan and record-boundary rules as Claude. The packaged Codex template registers `SessionStart`, `UserPromptSubmit`, `PostToolUse`, and `Stop` in `plugins/codex/hooks/hooks.json`. See `docs/plans/2026-05-28-codex-first-class-integration.md` for the historical rollout plan and validation gates. ### Install, update, and uninstall Install through Codex's own plugin marketplace — there is no `codemem setup` step: ```bash codex plugin marketplace add https://github.com/kunickiaj/codemem.git codex plugin add codemem@codemem # refresh the marketplace snapshot later: codex plugin marketplace upgrade # remove: codex plugin remove codemem@codemem ``` The plugin bundles `.mcp.json`, `hooks/hooks.json`, and a dependency-free generated normalizer. Its MCP `npx` launcher requests both `codemem` and `@codemem/embeddings` in the same temporary environment so the optional runtime is resolvable. Ingest wrappers use Viewer HTTP without child processes when healthy; `codemem` and pinned `npx` are fallback-only. Generated files come from the TypeScript normalizers in `packages/core/src/` via `node scripts/build-adapter-normalizers.mjs` and are protected by a byte-drift test. Validated targets: Codex CLI 0.135+ and current Desktop builds. ### Plugin-free install (`codemem setup --codex-only`) API-key / non-subscription Codex Desktop greys out plugin installation. For that case, configure Codex directly — no marketplace, no plugin: ```bash npx -y codemem setup --codex-only # or, with a global install: codemem setup --codex-only ``` What it does (idempotent; honors `CODEX_HOME`; backs up existing files; `--force` to refresh): - **MCP:** appends `[mcp_servers.codemem]` to `/config.toml` if not already present. It uses a durable global `codemem mcp` command when available; otherwise its `npx` command requests both `codemem` and `@codemem/embeddings` before launching `codemem mcp`. Setup upgrades the exact older managed `npx -y codemem mcp` table but leaves custom launchers untouched. The file is never reparsed or reformatted: setup either appends the table or replaces only the managed `command` and `args` lines, preserving comments and unrelated servers (including secrets). - **Hooks:** merges `SessionStart`, `UserPromptSubmit` (ingest + inject), `PostToolUse`, and `Stop` into `/hooks.json`, preserving any unrelated user hooks. Hook commands resolve to a direct `codemem codex-hook-*` call when `codemem` is on `PATH`; otherwise their `npx` fallback requests both packages before invoking the hook command. Prompt injection validates the loopback Viewer profile and retrieves with `POST /api/pack` first, using the local database only for classified compatibility fallback. Hooks loaded from the user config layer require a one-time trust approval in Codex (you'll be prompted on first run; MCP recall needs no trust). Codex setup also runs automatically in a plain `codemem setup` when a Codex home (`~/.codex` or `$CODEX_HOME`) is detected. ### Troubleshooting - **No memories and no raw events captured.** Confirm the `codemem` the hooks resolve actually has the Codex commands: `codemem codex-hook-ingest ` fallback while the plugin manifest still pins a pre-0.35 version) silently fails and spools. Inspect normalized wrapper envelopes at `~/.codemem/codex-raw-event-spool/`, legacy native-hook payloads at `~/.codemem/codex-hook-spool/`, and the plugin log at `~/.codemem/plugin.log`. - **Payloads are accumulating in a hook spool.** The Viewer is unavailable, rejected the configured target, or could not durably queue the event. Current Claude, Codex, and Pi compatibility commands do not open SQLite for ordinary transport failures; they retain the native payload and drain entries oldest-first through Viewer HTTP after recovery. Exact invalid-session and verified size rejections leave active selection only after safe retention, allowing later entries to proceed. Inspect these receipts with `codemem diagnostics capture list-rejected --format native-hook-v1 --provider claude --json`, choosing the matching provider. Claude preserves direct ingestion and synchronous flush for its current boundary event. Older queued Claude boundaries can be retained and require explicit recovery, which requests their boundary flush. Pi keeps pending boundary work retryable with its existing local fallback. - **`POST /api/raw-events` returns 404.** The running viewer predates normalized edge ingress; restart or upgrade it. Older plugin packages may continue using the named compatibility route. - **Normalized spool backlog drains automatically** at one envelope per successful ingest. The wrapper never reads or removes files from the legacy native-hook spool. - **A model rejects injected context** (for example "the conversation must end with a user message"): disable prompt-time injection with `CODEMEM_INJECT_CONTEXT=0`. Capture/ingest keeps working and recall is still available through the MCP tools. ## Pi extension The extension's CLI calls require grouped commands such as `memory list` and `session search`. Upgrade the CLI and extension together, then restart Pi. Pi support is the `@codemem/pi-extension` package. Supported host: Pi 1.1.0 or newer, below 2.0; upgrade an older host with `pi update` first ([Pi host compatibility](versioning.md#pi-host-compatibility)). Install the durable CLI (on Linux, set `ONNXRUNTIME_NODE_INSTALL=skip` before the first install; see the README), then: ```text codemem setup --pi-only ``` Restart Pi. Setup honors `PI_CODING_AGENT_DIR`. A fresh setup adds `npm:@codemem/pi-extension@` to that directory's `settings.json` `packages` list; an existing configured dev path may be retained. It defaults to native tools on a fresh setup. It preserves an existing `tools_mode`. It can fill unset `observer_*` keys from Pi API-key providers (cheap-model-first) without copying secrets. Eligible wire APIs are `openai-completions`, `openai-responses`, and `anthropic-messages` (the last only when the provider id is `anthropic`); an API key does not make other wire APIs eligible. Automatic derivation reports `unconfigured (oauth-only)` when only OAuth credentials are available. That is an auto-derivation status, not the state of every observer connection. Configure observer credentials or the connection separately, with provider or model overrides as needed. See [observer auth](user-guide.md#observer-auth-configuration). `--pi-mcp` is optional and legacy. It configures the third-party `pi-mcp-adapter` surface when that adapter is detected: it keeps an existing codemem MCP entry unless `--force` is supplied, and sets `pi.tools_mode` to `mcp-adapter`. It does not configure Pi's native MCP. Without the adapter, setup writes nothing MCP-related. `--pi-extension-path ` writes a local `packages` entry instead of the npm pin (dev). Uninstall: remove the `@codemem/pi-extension` packages entry and restart Pi. The shared store is left intact. Hidden `pi-hook-*` commands are adapter plumbing, not setup steps. ### Surfaces | Surface | Behavior | |---|---| | Ingest | Ordinary events prefer `POST /api/pi-hooks` (compatibility alias into the canonical envelope, `source: "pi"`), with `codemem pi-hook-ingest` CLI fallback (spool on failure). `session_before_compact` and `session_shutdown` always attempt the CLI path so a flush can run; failure is fail-open and does not break the session | | Injection | `context` appends `## codemem memories` to the latest user message of the request copy. Older messages replay the exact in-memory block. The system prompt and saved transcript are not modified. Decisions clear on `session_start`; a restart refetches | | File context | After a successful built-in `read`, related memories may be appended to that tool result. Errors and other tools do not | | Tools | 15 native `memory_*` tools via `pi.registerTool` when `pi.tools_mode` is `native` (the default), including `memory_session_search`. No MCP required; the codemem MCP server also registers `memory_session_search` (15 tools) for MCP-connected surfaces | | Compaction | `session_before_compact` attempts a flush only and does not skip recall. `session_compact` skips one new fetch only when `willRetry` is set and `reason` is not `manual` (overflow resume). Failed compaction, `agent_settled`, manual compaction, and a later user message clear that skip. A threshold compact skips only if that same guard matches | | Project | Nearest Git root, same walk as the other adapters | Prompt recall uses the latest user text, trimmed and cut at 500 characters (`recent work` when empty). Project scope is separate; this is not the OpenCode working-set query. Fetch order: prove `GET /api/prompt-pack-profile`, `POST /api/pack`, `codemem memory pack --json`, then `pi-hook-inject`. That HTTP pack attempt times out at 2 seconds and does not write an OpenCode retrieval-ledger row. Already-shown items are omitted from a new pack when the response carries valid renderer item ids, fingerprints, and spans. Defaults are 8 items, 800 approximate pack tokens, and 16000 characters. Without `CODEMEM_INJECT_RETAINED_TOKEN_BUDGET`, 800 is the pack request budget and does not reserve the header. A positive retained ceiling is optional; a full ceiling attaches nothing new. Ingest cursors persist as `codemem.cursor` metadata via `appendEntry`. Recall decisions do not. Pi's CLI boundary fallback shares one local extraction allowance across the entire invocation, including spool recovery: at most one batch of 100 saved events. Unprocessed events remain stored, and incomplete boundary receipts remain in the spool with their original target sequence for later processing. A queued Viewer acknowledgement transfers responsibility without local extraction. New memories can therefore be delayed while the Viewer is stopped. Pi's extension timeout remains separate from this event limit. ### Session search and history import Session search covers the Pi conversation text codemem ingests (user/assistant text blocks; thinking, tool-call, and tool-result content is skipped). The CLI, viewer REST route, Pi native tool, codemem MCP tool, and shared core primitive return `{query, query_truncated, results[], returned, total_matches, truncated}`. Each result carries `source: "pi"`, session id, project, role, timestamp, a snippet plus `snippet_truncated`, and `full_length`. Matching uses only the first 8,192 input characters and 64 effective tokens; `query_truncated` marks that reduction independently of query-echo clipping, and counts reflect only the effective query. This is raw-transcript search, not memory visibility filtering: a term that appears only in stored metadata or in an extracted memory does not match. Empty results are explicit, never an error. Human output warns when only part of the query was matched, including when there are no results; shorten the query before treating an empty partial match as missing history. - `codemem session search ` searches stored Pi sessions. Flags: `--project `, `--session-id `, `--limit ` (1–20, default 10), `--snippet-chars ` (100–4000, default 1200), `--json`, `-d/--db-path`. - `codemem session import` backfills `~/.pi/agent/sessions/**/*.jsonl` (honors `PI_CODING_AGENT_DIR`) into the raw-event store. Deterministic event ids dedupe against live capture; size/mtime-unchanged files are skipped per destination database. Unsafe partial overlap is reported per file without rewriting stored history; use a separate destination database for a complete import. `--extract` (off by default, observer-model cost scales with backlog) drains pending Pi sessions through the standard sweeper flush so extracted memories carry Pi attribution. Without it, the command stores searchable events without running extraction, though a running viewer's sweeper can still pick them up like any other backlog. - The pi extension's native `memory_session_search` exists only in native tools mode (its `mcp-adapter` mode registers no native tools); it calls `GET /api/pi/sessions/search` and falls back to `codemem session search --json` when the viewer is unavailable. Both transports default to the current Pi project; a non-blank `project` argument overrides it. The manually invoked CLI and direct viewer route remain unscoped when no project filter is supplied. - The codemem MCP server registers its own `memory_session_search`, so MCP-connected surfaces — including the `mcp-adapter` path — get the same search additively. It runs `searchPiSessions` against its own store in-process (no HTTP or CLI round trip) with the same parameters, bounds, response shape, and raw-transcript-only privacy. An omitted `project` resolves lazily per call from `CODEMEM_PROJECT` or the server's working directory; an explicit `project` overrides it, and `session_id` only narrows within that effective project. Import `--json` preserves the top-level import counters and adds `extraction: {requested, flushedEvents, failedSessions, pendingSessions, error}`. `failedSessions` counts flush errors during this run; `pendingSessions` counts the remaining Pi backlog, or is `null` when extraction was not requested. `error` contains the first observer-initialization or session-flush error, or `null`. Extraction snapshots every pending Pi stream's latest event sequence before processing and drains those captured ranges in batches of at most 100 events. It stops a stream on failure or lack of cursor progress and continues to later streams. Concurrent arrivals beyond the captured sequence wait for a later run or the Viewer. Initialization failure, session failure, or remaining Pi backlog exits with code 1 in both output modes; JSON also includes `error: "pi_extraction_incomplete"` and `message`. Successfully imported events remain stored, and failed batches retain the standard sweeper retry behavior. ### Native tools | Tool | Purpose | |---|---| | `memory_search` | Search; return full body text | | `memory_search_index` | Search; compact index, no body | | `memory_explain` | Ranking diagnostics for a query or IDs | | `memory_session_search` | Search stored Pi conversation text | | `memory_recent` | Recent memories, newest first | | `memory_pack` | One formatted pack for a context string | | `memory_get` | One memory by ID | | `memory_get_observations` | Several memories by ID | | `memory_remember` | Create a memory | | `memory_forget` | Soft-delete a memory | | `memory_learn` | How to use these tools | | `memory_schema` | Kinds, fields, and filters | | `memory_timeline` | Chronological window around an anchor | | `memory_expand` | Memories by ID plus nearby timeline | | `memory_distill_candidates` | Recurring memories as reviewable candidates | Native HTTP proves `GET /api/prompt-pack-profile` matches this process's `db_path` and `identity_target`, then resends both on the query. An unproven or mismatched viewer falls back to the CLI and is not trusted on 2xx. `memory_remember` is not replayed after an ambiguous HTTP timeout, connection reset, or 5xx. An unproven viewer, a disabled viewer, connect failures, and 4xx may still fall back. Reads may fall back more broadly. Config and env, including `CODEMEM_PI_*` and shared inject knobs, are in the [package README configuration table](../packages/pi-extension/README.md#configuration). `CODEMEM_PI_HOOK_HTTP_TIMEOUT_MS` (default 5000) is the ingest and native-tool HTTP timeout, not the pack-fetch timeout. ### Troubleshooting - **Extension not loaded.** Confirm `settings.json` `packages` contains the npm pin or dev path, then restart Pi. Setup writes under `PI_CODING_AGENT_DIR` when set, otherwise `~/.pi/agent`. - **CLI fallback fails.** `codemem` must be on `PATH` for ingest, pack, and tool fallbacks. - **Observer stays unconfigured.** Automatic derivation reports `unconfigured (oauth-only)` when only OAuth credentials are available (`packages/core/src/pi-observer-config.ts`). That is an auto-derivation status, not the state of every observer connection. Configure observer credentials or the connection separately, with provider or model overrides as needed. Setup never copies Pi secrets. See [observer auth](user-guide.md#observer-auth-configuration). - **Duplicate tools.** Native registration plus a `codemem` `mcp.json` entry warns once. Pick one surface: `pi.tools_mode` / `CODEMEM_PI_TOOLS_MODE` of `native` or `mcp-adapter`. - **Viewer target mismatch.** Upgrade or restart the viewer so the profile proof matches. Until then, packs and tools use the CLI fallback. - **Turn off Pi recall without stopping capture.** `CODEMEM_PI_INJECT_PROMPTS=0` disables prompt injection. `CODEMEM_PI_FILE_CONTEXT=0` disables read-file context. They are independent. If `CODEMEM_PI_INJECT_PROMPTS` is unset, `CODEMEM_INJECT_CONTEXT=0` also disables Pi prompt injection; it does not disable file context. ## Post-restart config sanity checklist After restarting OpenCode or the viewer, run this quick check when behavior looks off: 1. Confirm plugin + viewer are talking to the same DB path. 2. Check backend stats and recent writes (`codemem memory stats`, `codemem memory list`). 3. Verify runner mode and source (`CODEMEM_RUNNER`, `CODEMEM_RUNNER_FROM`) match your install strategy. 4. Confirm injection controls are what you expect (`CODEMEM_INJECT_CONTEXT`, `CODEMEM_INJECT_LIMIT`, `CODEMEM_INJECT_TOKEN_BUDGET`). 5. If stream mode is enabled, check backlog health (`codemem diagnostics capture status`). If needed, restart viewer + plugin flow: ```bash codemem service restart ``` If you override the viewer bind, keep the plugin and viewer aligned on the same target: ```bash set -lx CODEMEM_VIEWER_HOST 127.0.0.1 set -lx CODEMEM_VIEWER_PORT 38892 ``` The plugin now passes that explicit host/port through when it auto-starts, health-checks, stops, or restarts the viewer. Every plugin instance with viewer auto-start enabled runs the liveness monitor, including instances that found a viewer already running. After two consecutive failed checks (one per minute), it runs `codemem serve start`, at most once every five minutes. `serve start` does nothing when the port is already open, so several instances recovering at once cannot stop each other's viewer. A viewer that holds the port but stops answering is not replaced; run `codemem service restart` yourself. The liveness monitor requires a successful `GET /api/health` JSON response identifying `service: "codemem-viewer"`; `ready: false` still means the viewer process is live. For compatibility, only a `404` from the health route triggers one bounded probe of the legacy raw-event status endpoint. Raw-event ingest availability keeps its separate preflight behavior, now bounded by a 5-second timeout so a hung viewer socket cannot stall event delivery. Do not run multiple viewers against the same DB/runtime folder unless they intentionally share the same bind target; otherwise `viewer.pid` ownership becomes ambiguous. If compatibility toasts appear after restart, follow the runner-specific guidance in Compatibility guidance behavior below. ## OpenCode plugin tools exposed to the model - `mem-status` - show viewer URL, log path, stats, and recent entries. - `mem-stats` - show just the stats block. - `mem-recent` - show recent items (defaults to 5). These are plugin tools callable by the agent/runtime, not user-facing slash commands. OpenCode 2 registers the same hyphenated IDs through `tool.transform` with `codemode: false`; a packed-host smoke test verifies the IDs are preserved. ### Shared MCP server on OpenCode 2 (opt-in) OpenCode 2.2.6 and later can share one MCP server process across project directories (`pool: true`). A shared `codemem mcp` process runs in one fixed directory, so it has to be told which project each call came from. Start it with `--caller-context required` and give every project the same entry. `codemem setup --opencode-only --opencode-mcp pooled` writes it to the global OpenCode config: ```json { "mcp": { "servers": { "codemem": { "type": "local", "command": ["codemem", "mcp", "--caller-context", "required"], "cwd": "/absolute/path/that/exists", "protocol": "2026-07-28", "pool": true } } } } ``` The plugin adds the calling session's directory, the host's `CODEMEM_PROJECT` value, the session ID, and a call ID to each memory tool call, and removes that argument from the schema the model sees. Searches, writes, sharing scopes, distill context, and retrieval counts then match what a per-project server would produce. Setup writes the shared entry only when asked. It replaces a codemem entry it wrote before, refuses to replace one you customized unless you pass `--force`, and refuses a config that defines other servers directly under `mcp` (the OpenCode 1 layout). `codemem setup --opencode-only --opencode-mcp stdio` restores the per-project entry. - The plugin must be loaded in every project that uses the entry. Without it, each memory tool call fails with `caller_context_required`. The server never falls back to its own directory. - Name the entry `codemem`. The plugin sends caller details only to that server's tools. - `CODEMEM_PROJECT` in the entry's `environment` has no effect on a shared server. The plugin sends the value from the OpenCode process's own environment, which is the same for every project. - OpenCode shares a process only between entries with the same command, `cwd`, `environment`, protocol, and timeouts. Projects that set a different `CODEMEM_DB` or `CODEMEM_CONFIG` in `environment` get their own process. - If the shared process exits, OpenCode marks the server failed in every project that used it and removes its tools until you reconnect it from `/mcps`. Calls made in between fail and are not replayed. - OpenCode 1 has no pooling. Keep the per-project entry there. ### Built-in memory tools (experimental, opt-in) Set `CODEMEM_OPENCODE_NATIVE_TOOLS=1` (or `true`/`yes`) to have the plugin register the 14 codemem memory tools itself, so OpenCode no longer needs a `codemem mcp` process per project. The tools have the same names, inputs, and JSON results as the MCP tools, with `codemem_memory_` IDs on both hosts (`codemem_memory_search`, `codemem_memory_remember`, and so on). On OpenCode 2 they live in the `codemem` namespace with Code Mode enabled, so Code Mode callers use `tools.codemem.memory_search(...)`. Each call runs on the shared viewer when it serves this plugin's database and supports tool calls. Otherwise it runs `codemem memory-tool ` in the session directory and the result ends with a note that the viewer was unavailable. A write (`memory_remember`, `memory_forget`) that times out or fails inside the viewer returns an error rather than retrying through the CLI, because the write may already have happened. A read retried through the CLI counts as one retrieval in `codemem memory stats`: both attempts carry the same call ID, which is OpenCode 2's tool-call ID or, on OpenCode 1 (which has none), an ID the plugin generates for that call. If a `codemem` MCP server is still configured (`mcp.codemem` on OpenCode 1, `mcp.servers.codemem` on OpenCode 2) and not disabled, the plugin keeps the MCP tools and skips its own, logging and showing one notice. Remove the MCP entry to switch. The flag is off by default in this release. ## MCP tools exposed to agents The MCP server exposes memory retrieval and write tools such as `memory_search`, `memory_pack`, `memory_recent`, `memory_remember`, and `memory_forget`. Its 15-tool roster also includes `memory_session_search` over stored Pi user/assistant text. That addition is MCP-only: the shared thin-host catalog and OpenCode's experimental native-tool roster remain at 14 tools. ### MCP result and annotation contract All 15 tools publish the standard optional `outputSchema` and `annotations` fields; `packages/mcp-server/src/tool-contracts.ts` is the authority. On success, `structuredContent` is an object that validates against the declared schema, and `content[0].text` remains compact JSON for compatible text-only clients. The two representations are identical after JSON serialization, so `undefined` properties are omitted. Check `isError` before reading `structuredContent`: tool execution errors set `isError: true` and omit `structuredContent` so SDKs do not validate an error against the success schema. Registered-tool input validation and business errors remain tool execution errors. Starting in 0.49, calling an unknown tool returns a JSON-RPC protocol error with code `-32602`, as the MCP specification requires. Earlier versions returned a tool result with `isError: true` for that case. Integrations should handle protocol errors separately from tool execution errors and refresh the tool list before retrying a name the server does not recognize. A rejected call does not close the connection. Annotations describe each tool's primary operation on user data and its access beyond the local server; they are not authorization. Retrieval, metadata/schema, pack, and proposal-only distill tools are read-only. Incidental delivery logging, usage records, and caches do not change that classification. `memory_remember` adds data, while `memory_forget` is a destructive soft delete and is idempotent only in the no-added-effects sense—repeating it returns `not_found`. `memory_pack`, `memory_distill_candidates`, and `memory_remember` may load an external model or invoke the observer, so their open-world hints remain enabled. These annotations do not change authentication or transport, and clients may still apply their own prompting policies. `memory_distill_candidates` mines recurring lessons into reviewable context candidates. It is read-only and does not modify documentation files. By default an observer-model worthiness pass drops routine-activity clusters (release/CI status, review passes with no findings, context lookups) before the candidates are returned; pass `judge: false` to skip it. When no observer model is configured the tool returns unjudged output with `judged: false` and a `judge_error` in the metadata. Example agent requests: - "Find recurring project lessons worth adding to AGENTS.md." - "Run distill for all projects and show top candidates." - "Distill without judging so I can see the raw recurrence ranking." ## Observer model defaults - OpenAI: `gpt-6-luna` (tier routing uses `gpt-6-luna` for simple batches and `gpt-5.6-terra` for rich batches) - Anthropic: `claude-4.5-haiku` (mapped to Anthropic direct API alias `claude-haiku-4-5` when using `api_http`) Provider/model selection can be overridden with `CODEMEM_OBSERVER_PROVIDER` and `CODEMEM_OBSERVER_MODEL`. Custom providers are loaded from OpenCode config. ### Observer output rollout `legacy_xml` remains the default observer output mode during rollout. Set `CODEMEM_OBSERVER_OUTPUT_MODE=auto` to request constrained output where Codemem has executable transport evidence: official OpenAI Responses and direct Anthropic API-key calls use the versioned JSON envelope, while OAuth consumers, Claude/Codex sidecars, and unknown gateways preselect XML and report the capability reason. `json_schema` is an explicit operator assertion for a compatible custom OpenAI gateway configured by `observer_base_url`, or an Anthropic gateway configured by `CODEMEM_ANTHROPIC_ENDPOINT`. Codemem does not infer custom-gateway support from a provider name or URL, and a declared constrained path fails closed on refusal, truncation, missing output, invalid JSON, or local schema failure. It does not silently retry the response as XML. Diagnostics report fixed reason codes and requested/actual mode; they do not copy provider, transcript, or memory content. The provider-neutral `record_memories` tool definition is available for future transports and uses the same envelope as tool input. Codemem requires exactly one call and rejects missing, duplicate, wrong-name, or invalid-input calls. No provider/runtime cell uses this transport yet; each cell needs executable request and response contract tests before enablement. XML is a compatibility contract, not an immediate deprecation. Codemem will retain its prompt, parser, and repair path until a bounded rollout window shows negligible fallback use and every supported access path has a tested intentional contract. Removal will happen only in a later compatibility-breaking release with release notes. ### Observer auth modes Observer connections support API keys, an OpenCode account, and local Claude or Codex sessions. - Explicit runtime values: `api_key` (API key), `opencode_v2` (OpenCode account), `claude_sidecar` (Local Claude session), and `codex_sidecar` (Local Codex session). API-key mode requires a configured API credential, including for custom endpoints, and excludes cached subscription sign-ins. OpenCode-account mode requires the running local service and never falls back to a direct API key or imports Pi provider/model defaults. Missing credentials or an unavailable service produce a visible observer error. - API-key mode with provider `opencode` accepts `OPENCODE_API_KEY` only for the built-in OpenCode Zen endpoint; custom endpoints require their own explicitly configured credential. That variable is not used for other providers. Empty or whitespace-only tier model overrides use the provider's tier defaults, or the saved base model for a custom provider. - Settings shows restart guidance beside Save changes when an edited value requires it, and reports the actual result after saving. Field disclosures retain the affected scope and existing-data impact without repeating restart warnings; observer timing comes from the save result. Inactive observer tuning still explains when a connection ignores a value. Removing an authentication environment override can change an automatic connection, but does not activate API authentication for an explicitly selected local session. Unused pack limits do not require a restart. - Automatic detection has its own connection choice, so you can explicitly select a connection even when it matches the detected one. Saving Automatic clears the pinned runtime and restores detection; its preview ignores the saved runtime pin. The provider remains editable for automatic connections because it can still affect OpenCode requests; model guidance follows that editable provider. API-key and OpenCode-account connections show model catalogs; explicitly selected local sessions do not. Checking observer status refreshes automatic tier routing when apply finishes, without overwriting a connection draft, an edited routing switch, or an explicit configuration/environment setting. An edited routing switch is saved as an explicit choice even when it matches the active automatic value. - Authentication recovery guidance uses a server preview that ignores the auth-source environment override without changing the running process. It offers removal/restart recovery only when the saved source would use an API connection; local Claude sessions that remain local keep inactive guidance. - If apply finishes while a connection edit is unsaved, Settings keeps the draft's routing. Reverting all connection edits restores the cached active routing before another connection edit can save it. Explicit routing choices and environment-controlled routing remain unchanged. - With an Auto provider, custom model prefixes match configured provider IDs case-insensitively. OpenCode account requests retain the configured provider ID and preserve the remaining model ID's case. Direct custom-provider requests strip the same prefixes before applying configured model-ID mappings. - Legacy `api_http` and omitted runtime settings retain their existing routing until you explicitly select a connection. For newly captured OpenCode 2 raw events, implicit OpenCode OAuth routing (including a saved `api_http` with no explicit credential or custom endpoint) uses the local service. Older unmarked events remain on their prior path; mixed-version streams flush at generation boundaries. Unrelated Settings edits do not migrate a connection. - The V2 service uses the chosen provider/model and whichever account is active for that provider in OpenCode; codemem does not choose subscription versus API billing. Settings' OpenCode V2 catalog suggestions are not proof of access through the selected connection. During OpenCode location startup, codemem retries only the exact pre-generation model-selection rejection for up to about eight seconds, without changing the provider or model. Other failures are not retried; a model that remains unavailable fails visibly. - OpenCode's stateless one-shot API lacks a provider-enforced output-token cap and reports no usage. The local timeout and response-size limit constrain only codemem's wait and accepted data, not provider generation. The Codex/Claude sidecars and legacy OpenCode OAuth Codex path also have no provider-enforced output cap. To require a provider-side cap, select `api_key` for OpenAI Responses or Anthropic Messages. Historical recovery does not automatically move to the OpenCode service. - `claude_sidecar` runs observer calls via local Claude runtime auth (no `ANTHROPIC_API_KEY` required). - `claude_sidecar` uses `claude_command` (or `CODEMEM_CLAUDE_COMMAND`) as argv prefix for launching Claude CLI. Default: `["claude"]`. - `codex_sidecar` runs observer calls via the local `codex` CLI (`codex exec`), so Codex / ChatGPT Pro users get memory extraction with **no API key** — auth is delegated to the Codex CLI (`~/.codex`). It uses `codex_command` (or `CODEMEM_CODEX_COMMAND`) as the argv prefix. Default: `["codex"]`. The spawned process runs with `--ephemeral --ignore-user-config -s read-only` and codemem's own hooks suppressed, so it never recurses into capture. - codemem auto-selects `codex_sidecar` only when no `observer_runtime` is set, no API key is available from any provider, the OpenCode OAuth cache has no usable credentials, the `codex` CLI is resolvable, and `~/.codex/auth.json` exists. Otherwise set `observer_runtime = "codex_sidecar"` (or `CODEMEM_OBSERVER_RUNTIME=codex_sidecar`) explicitly. - Default models: - `api_key` and legacy `api_http`: `gpt-6-luna` for OpenAI unless `observer_model` is set. - `opencode_v2`: the selected provider's default model unless `observer_model` is set; OpenAI uses `gpt-6-luna`. With OpenAI tier routing enabled, simple/rich defaults are `gpt-6-luna` / `gpt-5.6-terra`. - `claude_sidecar`: `claude-4.5-haiku` unless `observer_model` is set. - `codex_sidecar`: `gpt-6-luna` unless `observer_model` is set; with tier routing enabled, simple/rich defaults are `gpt-6-luna` / `gpt-5.6-terra`. Explicit tier models take precedence over an explicit base model, which takes precedence over these defaults. The selected model is passed to `codex exec` via `-m`. - Anthropic direct API calls accept Anthropic model IDs/aliases; use `claude-haiku-4-5-20251001` if you need a pinned snapshot instead of the moving alias. - If `observer_model` is unsupported in Claude CLI, codemem retries once without `--model`. The same fallback applies to `codex_sidecar`: an unavailable tier model is retried once without `-m`. - Supported auth sources: `auto`, `env`, `file`, `command`, `none`. - Supported: API keys and gateway tokens codemem can read directly. - Custom provider path does not implicitly fall back to OpenCode/IAP env tokens; use provider key, `CODEMEM_OBSERVER_API_KEY`, `file`, or `command`. - For codemem-native custom providers, set `observer_base_url` (or `CODEMEM_OBSERVER_BASE_URL`) to avoid relying on OpenCode provider config. For command-refreshed gateway auth, configure a command token source plus templated headers: ```json { "observer_provider": "your-gateway-provider", "observer_base_url": "https://gateway.example/v1", "observer_runtime": "api_key", "observer_auth_source": "command", "observer_auth_command": ["iap-auth", "--audience", "example"], "observer_auth_timeout_ms": 1500, "observer_auth_cache_ttl_s": 300, "observer_headers": { "Authorization": "Bearer ${auth.token}" } } ``` `observer_auth_command` is direct argv execution (no shell interpolation). - Config key type: JSON string array (`["cmd", "arg1", "arg2"]`). - Env var `CODEMEM_OBSERVER_AUTH_COMMAND` must also be a JSON string array (for example `'["iap-auth","--audience","example"]'`), not a space-separated command string. Header template variables: - `${auth.token}` - `${auth.type}` - `${auth.source}` Command/file token cache behavior: - Successful token resolutions are cached for `observer_auth_cache_ttl_s`. - Failed token resolutions are not cached. ## Stream-only mode (advanced) Raw events preserve captured activity independently of observer extraction. Stream contract: - Preflight availability: `GET /api/raw-events/status?limit=0` (memory-only on queue-capable Viewers) - Event streaming: `POST /api/raw-events` - Non-2xx and network failures are treated as stream failures. - The Viewer durably appends accepted raw events to its filesystem inbox, returns `202`, and drains that inbox into SQLite outside the request path. - OpenCode 1.18.29 session IDs are read from each event's SDK-shaped `info` or `part` payload. Assistant messages and usage are captured after either `info.finish` or `info.time.completed`; current `info.tokens` and legacy usage fields are normalized into one token shape. - Successful tools arrive through `tool.execute.after` and record `output.output`. Failed tools arrive as errored `ToolPart` updates and are normalized to `tool.execute.after` raw events with a null result and the reported error. Repeated failure updates for the same session and call are captured once, and their deduplication state is cleared when the session is deleted. - Raw-event batches accepted by the viewer are retried by the Viewer-owned inbox drainer before the sweeper processes persisted sessions. - The Viewer inbox survives restarts, accepts at most 2,000 retained entries, and reports bounded warnings for corrupt files or a sustained backlog. A full or unwritable inbox returns a safe `503` without exposing its path or event contents. For manual recovery, stop Viewer and inspect `~/.codemem/viewer-raw-event-inbox/`; archive retained `.json` entries before removing them, then restart Viewer. - After Viewer delivery fails, OpenCode writes the exact normalized envelope to `~/.codemem/opencode-raw-event-spool`. It does not start `enqueue-raw-event`; retained entries retry over HTTP at bounded startup or session boundaries with the same event ID. - Viewer degradation logs identify the failed `status`, `post`, or `backoff` stage and distinguish timeout, connection, HTTP-status, and ingest-unavailable causes. Successfully spooled events do not show a user-facing warning for temporary failures. Explicit `409 viewer_identity_mismatch` pauses live POSTs and spool drains until the plugin restarts, preserves active spool entries, and shows one warning even when spooling succeeds. Other 409 responses keep their existing retry behavior. Payloads, target values, subprocess output, paths, endpoints, and addresses remain omitted. - Corrupt spool entries are retained for recovery. The spool accepts at most `CODEMEM_RAW_EVENT_SPOOL_MAX_ENTRIES` `.json` entries and rejects a new event when full without evicting existing entries. Duplicate events keep the first durable serialization when differences are limited to top-level delivery timestamps and valid runtime-local `cwd`, `project`, and `started_at`. Context reuse requires all three keys on both copies, each a string or null, and identical remaining fields. Later automatic retries adopt the saved body and timestamps, including when another process wins publication. Context drift with incomplete or invalid values remains a conflict. Payload, identity, host-generation, provenance, and unknown-field differences also remain conflicts. Entries missing context keys can still match under the existing delivery-timestamp rule. The original saved bytes are never rewritten. If a private spool write fails or the spool is full, keep OpenCode running while you repair or restart Viewer and reach a session boundary to retry; restarting OpenCode before the memory-only event is delivered could lose it. If specific entries remain rejected, archive the retained spool for manual recovery; do not delete it until the events are delivered or intentionally discarded. - OpenCode delivery retains rejected entries only after an actual POST returns an exact known payload-validation message at HTTP 400, or HTTP 413 with `error: "payload too large"` and a positive finite `max_bytes` smaller than the full outgoing UTF-8 request. Unknown responses, malformed JSON, Content-Length errors, authentication failures, and target errors other than explicit identity mismatches remain retryable. Retention preserves the original saved bytes outside active drain selection and inside the existing capacity limit. It publishes and syncs the retained name before removing the active name. A conflicting retained copy leaves the active copy intact. Retention and inspection require real directory paths and reject entry symlinks. Normal capture writes continue to support symlinked spool locations. - A drain processes only its existing loaded batch, normally at most 20 entries. Retaining a full batch makes later healthy entries eligible on the next drain. Retention failures leave saved copies intact but may prevent queue advancement. Live terminal rejections are persisted before retention and do not start Viewer backoff. Other failures keep their existing ordering and backoff behavior. Content-free warnings distinguish successful retention, failed retention, and lock-release failure. - If persistence adopts a different canonical copy after HTTP 413, ordinary delivery or spool draining retries the saved copy before size-based retention. The drain can run at the end of the same flush. The rejected incoming copy may have had longer runtime context than the saved copy. - `codemem diagnostics capture list-rejected --json` lists the `opencode-raw-event-v1` format, opaque receipts, byte counts, statuses, reasons, and `not_checked` validation state without reading payloads. Oversized and malformed payloads remain visible in this metadata list. `codemem diagnostics capture show-rejected '' --json` validates one entry and reports metadata. Only explicit `--raw` includes its original text as an escaped JSON string. Reads are capped at 16 MiB even if a file grows during inspection. These commands leave files untouched and use neither HTTP nor SQLite. After inspection, `codemem diagnostics capture recover-rejected '' --db-path '~/.codemem/mem.sqlite' -y` retries one selected entry. The original target is unknown, so `--db-path` and `-y` confirm the current database and runtime identity. The command preflights the loopback Viewer profile, protocol, database, identity, and advertised ingest size. It posts the exact retained bytes in one wrapped request, rejects redirects, and has no SQLite fallback. Use `--json` for machine-readable output. - `CODEMEM_RAW_EVENTS=0` pauses capture and every OpenCode spool drain. Existing spool files remain untouched until raw events are enabled again. - If OpenCode reports that a raw event was not saved for retry after a Viewer timeout, keep the client running until delivery recovers. The plugin records a content-free `raw_events.spool.failure` line in the local Codemem plugin log with a failure stage and allowlisted code (`conflict`, `full`, or a filesystem errno). Conflict lines also identify the comparison branch, the reason, and changed paths from a fixed field-name allowlist. Differences outside that list produce only `other=true`. Field values, arbitrary payload keys, event IDs, filenames, and hashes are omitted. If that log cannot be written, the same safe category goes to the host log. This distinguishes an existing-entry conflict from a directory, write, or sync error without logging the event ID or transcript. The warning alone does not prove which event was lost; inspect the retained spool and Viewer status before restarting the client. ### Selected-entry recovery storage Native hook inspection is available separately through `codemem diagnostics capture list-rejected` and `codemem diagnostics capture show-rejected` with `--format native-hook-v1`. Select `--provider claude`, `--provider codex`, or `--provider pi`. OpenCode remains the default format. Native retained names end in `.retained`, which older native hook drainers ignore. Inspection preserves existing permissions, refuses unsafe paths, caps payload reads at 16 MiB, and reveals text only with `--raw`. Automatic native retention is not enabled yet. `codemem diagnostics capture recover-rejected` accepts the same native format and provider selectors, plus explicit `--db-path` and `-y` confirmation. It reuses the Viewer profile, identity, origin, redirect, and size checks, and sends the native payload to its provider route. A valid `202` with one accepted and queued request transfers responsibility to the Viewer. An ordinary `200` must report one insertion and zero skips. Native skip responses and all synchronous Pi boundary responses keep the receipt. Pi receipts containing a saved extraction cutoff are rejected before POST because the HTTP route cannot preserve that cutoff. Recovery rechecks the locked snapshot before cleanup, leaves active aliases untouched, and supports `--keep-receipt`. The internal OpenCode recovery API validates one retained entry and passes its original bytes to a delivery callback. The callback must validate acceptance before returning a supported `queued` or `ingested` acknowledgement. The storage API itself sends no HTTP requests. After acknowledgement it rechecks the opened file, current path, metadata, hash, and exact bytes before removing only the selected retained name. Active aliases remain untouched. Results distinguish accepted delivery, changed or failed cleanup, uncertain directory durability, and lock-release failure. Successful retention can likewise report a lock-release warning separately from its durable result. If retention fails, its original error takes precedence over a later release failure. Passing `--keep-receipt` to `codemem diagnostics capture recover-rejected` requests preservation after acknowledgement. The storage API's named `keepReceipt` option still requires successful validation and unchanged-file checks, then reports accepted delivery with `cleanup: "kept"`. The command exits successfully when the lock is released. It leaves the receipt's bytes and inode unchanged, and the receipt continues to count toward the existing spool capacity limit. Default cleanup is unchanged. Retention and recovery share a private lock per event digest. A live or uncertain owner reports busy. A newly starting owner can briefly leave an incomplete record, so retry a repair-required result once before attempting repair. Stopped owners, persistent incomplete records, and unverifiable locks require manual repair, without automatic age-based removal. A crash can leave a lock behind. Stop capture and all recovery processes, make a private backup of the spool, and verify that no operation owns the lock before removing only that lock. Never remove retained `.json` entries to clear a lock. If ownership remains uncertain, leave the files intact. The delivery callback runs under the spool's mutation serializer and must not await another mutation in that same spool. Coordination covers participating Codemem processes. An unrelated writer can still replace a path between the final identity check and removal. Unless `--keep-receipt` is set, the retry command removes a receipt only after a recognized `202` queued or `200` ingested acknowledgement and unchanged-file cleanup. A timeout, a non-acknowledgement, or another ambiguous result retains the receipt because the Viewer may already have accepted it. If delivery was acknowledged but cleanup needs inspection, inspect the receipt and recovery result. Do not retry blindly. Duplicate acknowledgements identify an existing event ID without comparing content, so use `--keep-receipt` if you suspect an ID conflict. ### Delegated brief capture (OpenCode 1) A verified task brief is context for later work, not evidence of human approval or a new discovery. The OpenCode 1 adapter observes running `task` parts with `callID`, `state.input.{subagent_type,description,prompt}` and `state.metadata.{parentSessionId,sessionId}`. On the pinned OpenCode 1.18.30 host, `chat.message` receives the complete resolved message and parts before the host persists those parts individually. The production adapter requires that hook snapshot together with a matching live task binding. The snapshot must contain exactly one ordinary, non-ignored text part, with the exact task brief and requested child agent. It retains the original message and parts so later in-place hook changes are checked too. At the prompt-capture boundary, SDK reads cross-check the hook snapshot against the stored child session and message: parent/child IDs, message and part IDs, creation time, current agent and exact text must match. The child message must postdate the task start. A seemingly complete SDK read alone cannot qualify because it may show only partially persisted parts; missing snapshots or task metadata delivered after the hook leave provenance unknown. The parent assistant's agent is not used as the child's agent. The plugin freezes optional `capture_context` outside the event payload and ID seed. Spool replay preserves the same envelope. Ingress stores validated provenance in nullable `raw_events.capture_context_json`; the first accepted event wins on retries, including when it had no provenance. Invalid optional provenance stays unknown and does not reject valid raw data; existing identity validation remains strict. Old rows stay unknown, and access identity, project, visibility and memory kinds do not change. Classification revalidates the complete host report against the prompt's exact text and shape, including after adapter normalization. Removing private content can change the prompt hash: that mismatch safely yields unknown provenance, not proof of forgery. A host provenance report never grants access or proves human approval. A batch containing only proven briefs and harmless lifecycle bookkeeping completes without an observer request or durable memory. Raw events remain under the existing retention policy. Later tool or assistant findings use earlier briefs from the exact same source and stream as labeled observer context; they are not replayed as new events. A partial index supports bounded retrieval without scanning unrelated events. Recovered briefs follow all new evidence in the observer prompt. Their full text is sanitized before truncation, and the appended context block has a small aggregate cap including its label. Observer clipping can omit old context, but cannot displace the evidence prefix that would have been sent without it. The recovered `delegatedBriefs` list is transient observer context, not a duplicate stored in `sessions.metadata_json.session_context`. Other session-context fields remain intact, including a provenance-labeled `firstPrompt` when applicable. The context cap preserves complete XML entities and Unicode code points. Session-context backfill and extraction replay read the same validated raw-event sidecar as normal flushes. Replay refuses proven brief-only input before calling the observer (`ContextOnlyReplayError`, code `delegated_brief_context_only`), including batches without a local session mapping; mixed batches keep their labels and may recover earlier same-stream instructions. This refusal does not fabricate a successful extraction evaluation or alter the raw history. `diagnostics extraction replay` presents that context-only result as a non-error outcome with `status: "context_only"`, `code: "delegated_brief_context_only"`, `evaluated: false` and exit status zero. `diagnostics extraction benchmark` records it in `summary.contextOnlySkips`, increments `summary.contextOnlySkipped`, and continues the remaining batches and repetitions. The existing `runs`, output failures and all evaluation, stability, cost, latency and output-rate denominators exclude these skips; `summary.scheduledTotal` counts the full scheduled workload. The generated schema includes the nullable sidecar and its partial index. Existing database upgrades remain behind the normal compatibility gates; plain `connect()` does not add this column to an existing database. Legacy backfill/replay readers treat an absent column as unknown provenance without running a migration. | Bound | Limit | |---|---| | Observed task bindings, including replay guards | 128 per plugin instance | | Binding lifetime | 10 minutes | | Exact brief text | 64,000 characters | | Host metadata lookup at capture | 200 ms total; sibling failure and disposal abort outstanding reads | | Concurrent metadata lookups | At most the current binding-cache size; duplicate requests share a lookup | | Earlier instructions recovered for an observer batch | Latest 4 provenance-bearing events; at most 800 appended characters in aggregate, including label | Missing, late, expired, conflicting, synthetic or multipart provenance remains unknown; capture does not wait for a later metadata event. Replayed updates cannot bind a consumed task to a different message. Distinct later task calls can bind new messages in a reused child session; ambiguous simultaneous matches do not qualify. Restart and disposal discard live bindings but preserve already captured envelopes. Tasks that started before the plugin instance do not qualify. Disposal waits for capture preparation before checking durable delivery, and cancels active host lookups immediately rather than waiting for their timeout. Mixed batches continue normal extraction with proven instructions labeled as context. This is a host-specific provenance check, not a complete language classifier. OpenCode 2, Claude Code, Codex and Pi are unchanged; reviewer recall opt-out is a separate follow-up and is not enabled by this metadata. Restart OpenCode to load an updated plugin. ### Stream diagnostics and settings `GET /api/raw-events/status` also includes `transcript_diagnostics`, a per-Viewer-process, per-router-instance counter block scoped explicitly to `legacy_compatibility_routes`. It counts Claude and Codex compatibility-route transcript reads by the fixed outcomes `ok`, `not_provided`, `path_rejected`, `unreadable`, `no_complete_record`, and `no_assistant_record`. These counters are not persisted, do not include paths or transcript content, and do not describe the normal generated-adapter path through `POST /api/raw-events`. A skipped legacy `Stop` response keeps `skip_reason: "transcript_unavailable"` and may include one of the non-`ok` outcomes as `skip_detail`; other mapping skips remain `skip_reason: "unsupported_hook"`. Suggested settings: ```bash export CODEMEM_RAW_EVENTS_SWEEPER=1 export CODEMEM_RAW_EVENTS_SWEEPER_LIMIT=25 export CODEMEM_RAW_EVENTS_STUCK_BATCH_MS=300000 # optional quiet-period flush before the next periodic sweep # export CODEMEM_RAW_EVENTS_AUTO_FLUSH=1 # export CODEMEM_RAW_EVENTS_DEBOUNCE_MS=10000 # optional retention # export CODEMEM_RAW_EVENTS_RETENTION_MS=$((7*24*60*60*1000)) ``` To monitor backlog: ```bash codemem diagnostics capture status ``` If `raw-events-status` shows `batches=error:N` (legacy label) or `queue=... failed:N` for a stream, retry: ```bash codemem diagnostics capture retry ``` ## Hook lifecycle and flush boundaries The OpenCode 1 plugin uses event hooks and flushes on explicit lifecycle boundaries: - `tool.execute.after`: queue tool event; contributes to force-flush thresholds. - `session.idle`: immediate flush attempt. - `session.created`: flush previous session buffer before switching context. - `/new` prompt boundary: flush before session reset. - `session.error`: immediate flush attempt. Force-flush thresholds (immediate flush): - `>=50` tool events, or - `>=15` prompts, or - `>=10` minutes session duration. Failure semantics: - Stream POST failures are backoff-gated in plugin runtime (`CODEMEM_RAW_EVENTS_BACKOFF_MS`). - Availability checks are rate-limited (`CODEMEM_RAW_EVENTS_STATUS_CHECK_MS`) and use the queue-capable Viewer's memory-only readiness response. - Each periodic viewer sweep drains a bounded batch from accepted sessions, including sessions that remain active; failed batches are retried by viewer/store queue workers (`codemem diagnostics capture retry`). ## Project label normalization When ingesting plugin payloads, codemem stores a normalized project label instead of a full path. - Path-like labels are reduced to the basename (for example, `/home/user/projects/example` -> `example`). - Windows-style paths are normalized with Windows path rules on every OS runtime. - `C:\Users\user\projects\example` -> `example` - `D:/dev/client-demo` -> `client-demo` - `\\server\share\team\project-x` -> `project-x` - `CODEMEM_PROJECT` still has highest precedence and is normalized the same way. ### Multi-adapter project unification If you run multiple adapters for the same project (for example OpenCode + Claude), set a shared `CODEMEM_PROJECT` value in both runtimes to guarantee unified project grouping in memory retrieval. ## Environment hints | Env var | Description | | --- | --- | | `CODEMEM_RUNNER` | Override auto-detected runner: `codemem` (global), `npx`, `node` (repo/dev), or custom binary name. | | `CODEMEM_RUNNER_FROM` | Runner source override: npm package spec for `npx` (for example `codemem@0.20.0-alpha.7`), or repo/CLI entry path for `node`. | | `CODEMEM_VIEWER` | Set to `0`, `false`, or `off` to disable the viewer entirely. | | `CODEMEM_VIEWER_HOST`, `CODEMEM_VIEWER_PORT` | Explicit host/port the plugin-managed viewer should start, probe, stop, and restart. Prompt retrieval accepts loopback hosts only. | | `CODEMEM_VIEWER_AUTO` | Set to `0`/`false`/`off` to disable auto-start (default on). | | `CODEMEM_VIEWER_AUTO_STOP` | Set to `1`/`true`/`yes` to stop a viewer this plugin instance started when its session is deleted, including one it started to replace a viewer that stopped responding (default off, because one viewer serves every OpenCode project). | | `CODEMEM_PLUGIN_LOG` | Path for the plugin log file (set `1`/`true`/`yes` for `~/.codemem/plugin.log`; Claude hook failures are logged to this path by default). | | `CODEMEM_PLUGIN_LOG_PATH` | Explicit log file path for Claude hook script logging (overrides `CODEMEM_PLUGIN_LOG` for that script). | | `CODEMEM_CLAUDE_HOOK_HTTP_CONNECT_TIMEOUT_S` | Claude hook HTTP enqueue connect timeout in seconds (default `1`). | | `CODEMEM_CLAUDE_HOOK_HTTP_MAX_TIME_S` | Claude hook HTTP enqueue total timeout in seconds (default `2`). | | `CODEMEM_CODEX_HOOK_HTTP_TIMEOUT_MS` | Codex hook HTTP enqueue timeout in milliseconds (default `1000`). | | `CODEMEM_CODEX_HOOK_LOCK_DIR` | Codex hook fallback lock path (default `~/.codemem/codex-hook-ingest.lock`). | | `CODEMEM_CODEX_HOOK_LOCK_TTL_S` | Seconds before a Codex hook fallback lock is treated as stale (default `120`). | | `CODEMEM_CODEX_HOOK_SPOOL_DIR` | Legacy native Codex hook fallback spool directory (default `~/.codemem/codex-hook-spool`); the normalized wrapper does not read or drain it. | | `CODEMEM_CODEX_RAW_EVENT_SPOOL_DIR` | Normalized Codex raw-event envelope spool directory (default `~/.codemem/codex-raw-event-spool`). | | `CODEMEM_CODEX_LOCAL_PACK_ONLY` | Internal coordination flag set by the packaged Codex wrapper when it invokes the CLI compatibility fallback; skips duplicate Viewer retrieval. Not intended for manual use. | | `CODEMEM_INJECT_HTTP_MAX_TIME_S` | Viewer request timeout for OpenCode and Claude prompt retrieval, the per-request cap for packaged Codex, and the total profile-plus-pack HTTP budget for plugin-free Codex (default and maximum `2` seconds for plugin-free Codex). Claude and Codex ledger completion has a separate fixed 500 ms cap; packaged Codex also enforces a total 4.5-second output budget. | | `CODEMEM_INJECT_MAX_CHARS` | Max chars returned as Claude/Codex `additionalContext` (default `16000`). | | `CODEMEM_PLUGIN_CMD_TIMEOUT` | Milliseconds before a plugin CLI call is aborted (default `20000`). | | `CODEMEM_MIN_VERSION` | Minimum required CLI version for plugin compatibility warnings (default `0.9.20`). | | `CODEMEM_BACKEND_UPDATE_POLICY` | Compatibility and release-notification policy: `notify` (default), `auto`, or `off`. | | `CODEMEM_INSTALL_KIND` | Internal/advanced release-guidance detection override (`npm-global`, `pnpm-global`, `mise`, `npx`, `docker`, `repo-dev`, `pinned`, or `unknown`). Markers do not prove ownership or enable installation. | | `CODEMEM_CODEX_ENDPOINT` | Override Codex OAuth endpoint. | | `CODEMEM_PLUGIN_DEBUG` | Set to `1`, `true`, or `yes` to log plugin lifecycle events. | | `CODEMEM_PLUGIN_IGNORE` | Skip all plugin behavior for this process on either OpenCode host. | | `CODEMEM_INJECT_CONTEXT` | Set to `0` to disable memory pack injection (default on). | | `CODEMEM_INJECT_SURFACE` | OpenCode injection surface: `message` by default; set `system` for the legacy system-prompt transform. | | `CODEMEM_INJECT_LIMIT` | Max memory items in injected pack (default `8`). | | `CODEMEM_INJECT_RETAINED_TOKEN_BUDGET` | Opt-in approximate cap for retained OpenCode automatic message blocks, off by default. Only an explicit positive safe integer (for example `8000`) enables it; unset, invalid, or nonpositive values disable it. Count full wrapped blocks currently retained, including replay/reconstruction. Compaction notifications do not reset allowance. Does not apply to legacy system injection or explicit MCP recall. | | `CODEMEM_INJECT_TOKEN_BUDGET` | Positive approximate token cap for OpenCode's complete wrapped injection (default `800`). OpenCode reserves its context prefix before sending the remaining budget through Viewer or CLI; unset, zero, negative, and invalid values use `800`. An override too small to leave a positive pack budget injects nothing because `0` means unlimited to generic pack calls. Pack accounting uses `ceil(characters / 4)`, not the provider tokenizer. | | `CODEMEM_USE_OPENCODE_RUN` | Use `opencode run` for observer generation (default off). | | `CODEMEM_OPENCODE_MODEL` | Model for `opencode run` (default `gpt-6-luna`). | | `CODEMEM_OPENCODE_AGENT` | Agent for `opencode run` (optional). | | `CODEMEM_OBSERVER_PROVIDER` | Force `openai`, `anthropic`, or a custom provider key (optional). | | `CODEMEM_OBSERVER_MODEL` | Override observer model (default `gpt-6-luna` or `claude-4.5-haiku`). | | `CODEMEM_OBSERVER_API_KEY` | API key for observer model (optional). | | `CODEMEM_CLAUDE_COMMAND` | JSON argv array for Claude CLI invocation used by `claude_sidecar` (default `["claude"]`). | | `CODEMEM_OBSERVER_RUNTIME` | Observer connection: `api_key`, `opencode_v2`, `claude_sidecar`, or `codex_sidecar`. Omitted or legacy `api_http` values retain automatic routing. | | `CODEMEM_OBSERVER_OUTPUT_MODE` | Observer output contract: `legacy_xml` (default); `auto` enables JSON Schema only on proven direct API cells and preselects XML elsewhere; `json_schema` explicitly asserts compatible custom OpenAI (`observer_base_url`) or Anthropic (`CODEMEM_ANTHROPIC_ENDPOINT`) gateway support. Malformed constrained output fails closed without XML reparsing. | | `CODEMEM_ANTHROPIC_ENDPOINT` | Anthropic Messages API endpoint override. With provider `anthropic`, API-key auth, and output mode `json_schema`, this explicitly opts a compatible endpoint into constrained output. | | `CODEMEM_OBSERVER_AUTH_SOURCE` | Observer auth source (`auto`, `env`, `file`, `command`, `none`). | | `CODEMEM_OBSERVER_AUTH_FILE` | Path to token file used when auth source is `file`. | | `CODEMEM_OBSERVER_AUTH_COMMAND` | Command argv as a JSON string array used when auth source is `command`. | | `CODEMEM_OBSERVER_AUTH_TIMEOUT_MS` | Command auth timeout in milliseconds (default `1500`). | | `CODEMEM_OBSERVER_AUTH_CACHE_TTL_S` | Cache TTL for command/file auth resolution in seconds (default `300`). | | `CODEMEM_OBSERVER_HEADERS` | JSON object of templated observer headers, e.g. `{"Authorization":"Bearer ${auth.token}"}`. | | `CODEMEM_OBSERVER_MAX_CHARS` | Max observer prompt characters (default `12000`). | | `CODEMEM_RAW_EVENTS_BACKOFF_MS` | Backoff window after stream failure before retrying stream POSTs (default `10000`). | | `CODEMEM_RAW_EVENTS_STATUS_CHECK_MS` | Minimum interval between stream availability preflight checks (default `30000`). | | `CODEMEM_RAW_EVENTS_HARD_MAX` | Hard upper bound for queued or in-flight raw-event deliveries under sustained failure pressure (default `2000`). Events rejected at delivery capacity remain in the bounded in-memory queue for flush or disposal retry instead of adding promise or detached-batch work. | | `CODEMEM_RAW_EVENT_SPOOL_DRAIN_LIMIT` | Max valid saved envelopes attempted per spool drain; corrupt entries do not consume this limit (default `20`). | | `CODEMEM_RAW_EVENT_SPOOL_MAX_ENTRIES` | Max `.json` entries in the OpenCode raw-event spool (default `2000`). A full spool rejects new event IDs without evicting existing entries; the failed write remains only in the bounded in-memory queue. | | `CODEMEM_RAW_EVENTS_AUTO_FLUSH` | Set to `1` to enable viewer-side debounced flush of streamed raw events (default off). | | `CODEMEM_RAW_EVENTS_DEBOUNCE_MS` | Debounce delay before auto-flush per session (default `60000`); the periodic sweeper may drain the session sooner. | | `CODEMEM_RAW_EVENTS_SWEEPER` | Set to `1` to enable periodic sweeper flush for sessions with unflushed events (default on). | | `CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_MS` | Sweeper tick interval (default `30000`). | | `CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_S` | Config/env interval in seconds used by Settings UI (default `30`; overridden by `CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_MS` when set). | | `CODEMEM_RAW_EVENTS_SWEEPER_LIMIT` | Max sessions with unflushed events to process per sweeper tick (default `25`). | | `CODEMEM_RAW_EVENTS_STUCK_BATCH_MS` | Mark flush batches older than this many ms as error (default `300000`). | | `CODEMEM_RAW_EVENTS_RETENTION_MS` | If >0, delete raw events older than this many ms (default `0`, keep forever). | | `CODEMEM_CLAUDE_HOOK_FLUSH` | Set to `0` to disable immediate `SessionEnd` boundary flush (default on for `SessionEnd`; `Stop` still requires `CODEMEM_CLAUDE_HOOK_FLUSH_ON_STOP=1`). | | `CODEMEM_CLAUDE_HOOK_FLUSH_ON_STOP` | Set to `1` to flush on Claude `Stop` hooks in addition to `SessionEnd` (default off). | | `CODEMEM_CLAUDE_HOOK_BOUNDARY_TIMEOUT_MS` | Override the direct Viewer request wait for `SessionEnd`, clamped inside `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS`. For opt-in `Stop` flushing, this sets the whole boundary budget; the first request reserves fallback time within it (default total: `125000` ms). | ## Compatibility guidance behavior When the plugin detects CLI/runtime version mismatch, it shows guidance based on runner mode: - `CODEMEM_RUNNER=codemem`: run `npm install -g codemem` (the CLI installs its optional semantic runtime), then restart OpenCode. On Linux, prefix with `ONNXRUNTIME_NODE_INSTALL=skip` to avoid downloading the unused GPU provider (see the semantic-runtime install notes). - `CODEMEM_RUNNER=npx`: the compatibility warning recommends moving to a global `codemem` install, which includes its optional semantic runtime. Clear explicit `CODEMEM_RUNNER` and `CODEMEM_RUNNER_FROM` overrides so the plugin detects that install, then restart OpenCode. To keep using npx instead, update `CODEMEM_RUNNER_FROM` to the desired `codemem@` spec; the plugin pairs the matching `@codemem/embeddings` version automatically. On Linux, see the CPU-only semantic-runtime install notes in the README. - `CODEMEM_RUNNER=node`: pull latest repo changes and run `pnpm build`, then restart OpenCode - custom/unknown runner: update the underlying `codemem` binary or package source, then restart OpenCode Update policy: - `CODEMEM_BACKEND_UPDATE_POLICY=notify` (default): show warning toast with suggested action - `CODEMEM_BACKEND_UPDATE_POLICY=auto`: try a best-effort auto-update for eligible compatibility-floor mismatches and fresh same-channel releases observed for at least 24 hours, then warn if still outdated - skipped for `node` dev-mode runners - skipped when `CODEMEM_RUNNER_FROM` is pinned to a fixed package/version - skipped for pnpm-global, mise, Docker, unknown, stale, unsupported-channel, cross-channel, or downgrade states - `CODEMEM_BACKEND_UPDATE_POLICY=off`: no compatibility toast (logging still records mismatch) After its startup delay, the plugin also runs `codemem update check --json` through the same argv-based CLI runner. The CLI derives `alpha`, `beta`, `rc`, or `latest` from the installed version. `notify` and `auto` show a best-effort toast at most once per newly discovered release on that channel in the current OpenCode process; `off` skips this release check. Under explicit `auto`, an eligible result executes a paired, version-pinned public-registry install for `codemem` and `@codemem/embeddings`, then verifies the active CLI version before a plugin-owned Viewer is restarted. On Linux, both plugin-owned auto-update paths preserve the existing child environment and set `ONNXRUNTIME_NODE_INSTALL=skip` for the install; other platforms keep the existing environment behavior. Current, unavailable, malformed, ineligible, and timed-out results are ignored or shown as guidance without delaying plugin startup. The plugin-owned installer is best effort: it does not use the CLI install lock or Windows npm-shim handling, and plugin-owned auto-update is disabled on Windows. Avoid starting simultaneous automatic updates from multiple OpenCode sessions; use `codemem update install` when serialized installation is required. Mise-managed CLIs are detected from a semver-qualified mise install path or normalized `MISE_DATA_DIR` path and receive global `mise use -g npm:codemem@` guidance. Only the user's explicit `codemem update install` command may execute that argv-only update. It first compares bounded machine-readable active and global mise source records, requires a user-owned global source, and canonicalizes current install-path ownership. It then pins public npm registries for the spawned command and writes the exact release into mise's primary global config. Verification allows the source to move from user `conf.d` or the recognized user-level `~/.config/mise.toml` file to `config.toml` but requires the post-update global `version` or `requested_version` before running `mise exec -- codemem --version` outside the invoking project; plugin background auto-update never treats mise as eligible. pnpm-global CLIs are recognized from canonical virtual-store path evidence, which can provide release notifications and the exact paired package command but cannot prove ownership. Only an explicit `codemem update install` may mutate that installation: from a neutral directory it uses bounded, no-shell `pnpm root -g`, `pnpm bin -g`, and `pnpm list -g --depth 0 --json` checks to prove the root is exactly the list root (pnpm 12) or its `node_modules` directory (pnpm 9–11), and that the list root owns the active Codemem package. It installs exact matching `codemem` and `@codemem/embeddings` packages from the public npm registry and verifies both registered package state and that launcher. The updater never runs a build-approval command; pnpm 9 still runs install scripts by default, while newer releases apply their configured build-script policy. Plugin background auto-install never treats pnpm-global as eligible. Docker images set `CODEMEM_INSTALL_KIND=docker` so release guidance cannot mistake the bundled global npm package for a host npm installation. Docker deployments never self-update; rebuild and restart the image with the desired `CODEMEM_VERSION` instead. Compatibility checks do not block plugin startup.