Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). Authentication
Overview
jcode lets users authenticate with a wide range of LLM providers so they can use existing subscriptions (Claude Max, ChatGPT Pro, Gemini) or API keys. The auth layer supports OAuthOpen Authorization flows, API keys, Azure Entra ID, and reuse of external credentials (e.g. Codex or Claude CLI auth files), with a browser-based login flow driven from the CLI (jcode login). This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | Low-friction login with their existing subscriptions, multi-account support, and clear auth status |
| Maintainer | Accurate provider catalog, diagnosable auth failures, testable login flows |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall support logging in to multiple built-in providers, including Anthropic Claude, OpenAI/Codex, Gemini, Azure OpenAI, and OpenAI-compatible API-key providers. | Must | The system shall support logging in to multiple built-in providers, including Anthropic Claude, OpenAI/Codex, Gemini, Azure OpenAI, and OpenAI-compatible API-key providers. |
| FR-2MustThe system shall support browser-based OAuthOpen Authorization login for providers that require it, including printing an auth URL and running a local callback server. | Must | The system shall support browser-based OAuthOpen Authorization login for providers that require it, including printing an auth URL and running a local callback server. |
| FR-3MustThe system shall support API-key login for providers that accept keys, via interactive prompt, `--api-key`, or environment variable. | Must | The system shall support API-key login for providers that accept keys, via interactive prompt, --api-key, or environment variable. |
| FR-4MustThe system shall detect and reuse external credentials from other CLIs (e.g. Codex auth.json, Claude .credentials.json) with ask-before-read and symlink rejection. | Must | The system shall detect and reuse external credentials from other CLIs (e.g. Codex auth.json, Claude .credentials.json) with ask-before-read and symlink rejection. |
| FR-5MustThe system shall store credentials securely (e.g. `~/.jcode/auth.json`, macOS Keychain) and support multiple accounts per provider. | Must | The system shall store credentials securely (e.g. ~/.jcode/auth.json, macOS Keychain) and support multiple accounts per provider. |
| FR-6MustThe system shall refresh expired tokens, coordinating refreshes so concurrent requests do not double-refresh. | Must | The system shall refresh expired tokens, coordinating refreshes so concurrent requests do not double-refresh. |
| FR-7ShouldThe system shall provide auth status and diagnostics (`jcode auth status`, `jcode auth doctor`) and end-to-end auth validation (`jcode auth-test`). | Should | The system shall provide auth status and diagnostics (jcode auth status, jcode auth doctor) and end-to-end auth validation (jcode auth-test). |
| FR-8ShouldThe system shall support experimental CLI providers (Cursor, GitHub Copilot, Antigravity) and named OpenAI-compatible provider profiles. | Should | The system shall support experimental CLI providers (Cursor, GitHub Copilot, Antigravity) and named OpenAI-compatible provider profiles. |
| FR-9MayThe system shall allow scriptable login via printed auth URL and callback (`--print-auth-url`, `--callback-url`, `--auth-code`). | May | The system shall allow scriptable login via printed auth URL and callback (--print-auth-url, --callback-url, --auth-code). |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustThe system shall never read credential files through symlinks. | Must | Security | The system shall never read credential files through symlinks. |
| NFR-2MustThe system shall keep tokens out of logs and error output. | Must | Security | The system shall keep tokens out of logs and error output. |
| NFR-3ShouldA failed or missing login for one provider shall not prevent using other providers. | Should | Availability | A failed or missing login for one provider shall not prevent using other providers. |
| NFR-4ShouldThe default provider shall be auto-detected from available credentials. | Should | Usability | The default provider shall be auto-detected from available credentials. |
Constraints
- Must support both subscription-based (OAuthOpen Authorization) and API-key-based providers in one auth model.
- Must run without a hosted auth service; callbacks are handled locally.
Acceptance Criteria
Every FR and NFR shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
Acceptance criteria verify how a requirement is proven done, they do not restate it. Write concrete, scenario-based criteria (happy path, edge cases and error states where applicable).
- FR-1MustThe system shall support logging in to multiple built-in providers, including Anthropic Claude, OpenAI/Codex, Gemini, Azure OpenAI, and OpenAI-compatible API-key providers.
- Given a clean
~/.jcodewith no auth - When the user runs
jcode loginfor a supported provider and completes the flow - Then the provider appears as authenticated and usable for sessions
- Given a clean
- FR-2MustThe system shall support browser-based OAuthOpen Authorization login for providers that require it, including printing an auth URL and running a local callback server.
- Given an OAuthOpen Authorization provider selected for login
- When the browser flow completes against the local callback server
- Then the returned token is stored and a session can start with that provider
- FR-3MustThe system shall support API-key login for providers that accept keys, via interactive prompt, `--api-key`, or environment variable.
- Given an API-key provider
- When a key is provided interactively or via
--api-key/environment variable - Then the key is validated and stored
- FR-4MustThe system shall detect and reuse external credentials from other CLIs (e.g. Codex auth.json, Claude .credentials.json) with ask-before-read and symlink rejection.
- Given an external credential file (e.g.
~/.codex/auth.json) - When the user consents to reading it
- Then the credential is used without copying it into jcode's own store
- Given an external credential file (e.g.
- FR-5MustThe system shall store credentials securely (e.g. `~/.jcode/auth.json`, macOS Keychain) and support multiple accounts per provider.
- Given stored credentials
- When the user lists accounts or starts a session
- Then multiple accounts are selectable and the chosen one is used
- FR-6MustThe system shall refresh expired tokens, coordinating refreshes so concurrent requests do not double-refresh.
- Given an expired token
- When a request needs the token
- Then it is refreshed once and concurrent requests share the refreshed token
- FR-7ShouldThe system shall provide auth status and diagnostics (`jcode auth status`, `jcode auth doctor`) and end-to-end auth validation (`jcode auth-test`).
- Given an installed jcode with configured providers
- When the user runs
jcode auth doctororjcode auth-test - Then it reports each provider's auth state and pinpoints failures
- FR-8ShouldThe system shall support experimental CLI providers (Cursor, GitHub Copilot, Antigravity) and named OpenAI-compatible provider profiles.
- Given a configured named provider profile or experimental provider
- When the user logs in with that profile
- Then the profile is usable for sessions
- FR-9MayThe system shall allow scriptable login via printed auth URL and callback (`--print-auth-url`, `--callback-url`, `--auth-code`).
- Given a headless environment
- When the user runs login with
--print-auth-urland later supplies the auth code - Then the login completes without opening a browser
- NFR-1MustThe system shall never read credential files through symlinks.
- Given a symlink placed where a credential file is expected
- When credential detection runs
- Then the symlink is rejected and not followed
- NFR-2MustThe system shall keep tokens out of logs and error output.
- Given a login or token-refresh failure
- When error output is produced
- Then no token or secret material appears in logs or stderr
- NFR-3ShouldA failed or missing login for one provider shall not prevent using other providers.
- Given one misconfigured provider
- When a session targets a different provider
- Then the session succeeds regardless of the misconfigured provider
- NFR-4ShouldThe default provider shall be auto-detected from available credentials.
- Given exactly one set of credentials available
- When jcode starts without a provider flag
- Then the matching provider is auto-selected
Conflicts
None identified yet.
Open Questions
- Which provider/account selection UX should win when multiple credentials are available for the same provider? The current behavior is inferred from code, not verified end to end.
Specification: ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). Authentication
Overview
Auth is implemented in the jcode-base layer (crate jcode-base/src/auth/) and driven by CLI commands in src/cli/login/, src/cli/account.rs, src/cli/auth.rs, and src/cli/auth_test/. The login CLI orchestrates provider-specific flows: OAuthOpen Authorization browser flows with a local callback server, API-key prompts, and external credential detection. Stored credentials live under ~/.jcode/ with platform-appropriate hardening (macOS Keychain where applicable), and a refresh coordinator deduplicates token refreshes. This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
src/cli/login.rs ─┐
src/cli/login/ ─┼─► jcode-base/src/auth/ (per-provider modules)
src/cli/auth.rs ─┤ ├─ claude.rs / codex.rs / gemini.rs / google.rs
src/cli/auth_test ┘ ├─ azure.rs / copilot.rs / cursor.rs / antigravity.rs
├─ external.rs (external credential sources)
├─ oauth.rs + refresh_coordinator.rs
└─ doctor.rs (auth diagnostics)
│
▼
~/.jcode/auth.json, openai-auth.json,
gemini_oauth.json, external CLIs' stores,
macOS Keychain
Data Models
Auth State
| Field | Type | Constraints | Description |
|---|---|---|---|
| provider_key | string | PK | Identifier of the provider (e.g. anthropic, openai). |
| account | string | not null | Account label for multi-account support. |
| credential | object | not null | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific token/key material and metadata. |
| source | enum | not null | e.g. oauth, api-key, external. |
API Contracts
CLI: jcode login [provider]
Flags: --account, --no-browser, --print-auth-url, --callback-url, --auth-code, --complete, --json, --no-validate, --api-base, --api-key, --api-key-env, --google-access-tier.
Behavior | Description
|---|---|
| No browser flag | Opens the OAuthOpen Authorization URL in the default browser and starts a local callback server. |
| --print-auth-url | Prints the URL and waits for --auth-code to complete the flow. |
| --api-key / --api-key-env | Validates and stores an API key directly. |
CLI: jcode auth status / jcode auth doctor
Reports per-provider auth state and common failure causes.
CLI: jcode auth-test
End-to-end auth validation with options --login, --all-configured, --coverage, --context-audit.
Sequences
Browser OAuthOpen Authorization login
User → jcode login → open browser / print URL
User authorizes in browser
ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). → local callback server → auth code
jcode → token exchange → refresh_coordinator → store credential
jcode → validates token (unless --no-validate) → success
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
Auth lives in jcode-base |
Downward-closed foundational layer | All upper layers and the CLI can rely on auth without layering issues. |
| Per-provider modules | One module per provider | Isolates provider-specific OAuthOpen Authorization quirks; experimental providers are clearly separated. |
| External credential reuse | Read other CLIs' auth files with consent | Lets users reuse subscriptions without maintaining duplicate tokens. |
| Refresh coordinator | Single coordinated refresh | Avoids concurrent double-refresh storms on shared tokens. |
| Multiple storage backends | Files + macOS Keychain | Balances portability with platform security. |
Risks and Unknowns
- External credential formats change without notice when upstream CLIs change.
- OAuthOpen Authorization callback flows are hard to test end to end in CIContinuous Integration; most coverage relies on local HTTP test servers and API-key providers.
Out of Scope
- A hosted identity service for jcode accounts (the
jcode accountcommand is unrelated account/billing surface). - New experimental provider integrations beyond what the codebase already ships.
Test Plan: ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). Authentication
Scope
Covers provider login flows (OAuthOpen Authorization and API key), auth status/diagnostics, external credential detection, and token refresh coordination. Out of scope: live tests against paid providers (guarded behind live_tests).
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Login flow against a local HTTP test server for OpenAI-compatible providers | tests/auth_login_flow.rs with a local OpenRouter/OpenAI-compat server |
ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). authenticated, session usable |
| TC-2 | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). catalog invariants | crates/jcode-base/src/provider_catalog_tests.rs |
Catalog entries valid and consistent |
| TC-3 | Registry behavior | crates/jcode-base/src/registry_tests.rs |
ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). registration works |
| TC-4 | External credential review candidates | crates/jcode-base/src/auth/*_tests.rs |
Detection and ask-before-read behave correctly |
| TC-5 | Refresh coordination | crates/jcode-base/src/auth/refresh_coordinator.rs tests |
Concurrent refreshes deduplicate |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-6 | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). matrix auth/endpoint sweep | tests/provider_matrix.rs |
All configured providers behave per endpoint state |
| TC-7 | End-to-end auth validation suite | scripts/test_auth_e2e.sh |
Each provider's login/refresh path passes |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-8 | Credential file is a symlink | Detection rejects it (never follows symlinks) |
| TC-9 | Expired token with concurrent requests | Token refreshed exactly once; requests share the result |
| TC-10 | One provider misconfigured | Other providers still work |
Test Infrastructure
- Local HTTP test server for OpenAI-compatible login flows (used by
auth_login_flow.rs). - Script-based e2e suite (
scripts/test_auth_e2e.sh). - Live provider tests guarded behind
live_testsand not run in CIContinuous Integration by default.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall support logging in to multiple built-in providers, including Anthropic Claude, OpenAI/Codex, Gemini, Azure OpenAI, and OpenAI-compatible API-key providers. | TC-1, TC-2 |
| FR-4MustThe system shall detect and reuse external credentials from other CLIs (e.g. Codex auth.json, Claude .credentials.json) with ask-before-read and symlink rejection. | TC-4, TC-8 |
| FR-6MustThe system shall refresh expired tokens, coordinating refreshes so concurrent requests do not double-refresh. | TC-5, TC-9 |
| FR-7ShouldThe system shall provide auth status and diagnostics (`jcode auth status`, `jcode auth doctor`) and end-to-end auth validation (`jcode auth-test`). | TC-6, TC-7 |
| NFR-1MustThe system shall never read credential files through symlinks. | TC-8 |
requirements
- Which provider/account selection UX should win when multiple credentials are available for the same provider? The current behavior is inferred from code, not verified end to end.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Context CompactionReducing accumulated context (and the KV cache) when a session grows too large.
Overview
Context compaction keeps long sessions usable by compressing the accumulated context (and provider KV cacheProvider-side key-value cache for repeated prompt prefixes.) when it grows too large. jcode supports reactive, proactive, and semantic compaction strategies, all configurable under the [compaction] config section. This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | Long-running sessions that stay fast and stay within provider context limits |
| Maintainer | Predictable compaction behavior that preserves important context |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall compact a session's context when it approaches the provider context window limit. | Must | The system shall compact a session's context when it approaches the provider context window limit. |
| FR-2MustThe system shall support multiple compaction strategies: reactive (on threshold), proactive (before it is needed), and semantic. | Must | The system shall support multiple compaction strategies: reactive (on threshold), proactive (before it is needed), and semantic. |
| FR-3MustThe system shall preserve a summary of the compacted context so later turns retain continuity. | Must | The system shall preserve a summary of the compacted context so later turns retain continuity. |
| FR-4MustThe system shall record compaction state on the session so resume reflects the compacted context. | Must | The system shall record compaction state on the session so resume reflects the compacted context. |
| FR-5ShouldThe system shall keep a cache-relevant hash of messages so KV-cache prefix changes are detected after compaction. | Should | The system shall keep a cache-relevant hash of messages so KV-cache prefix changes are detected after compaction. |
| FR-6ShouldThe system shall allow strategy configuration per the `[compaction]` section (reactive/proactive/semantic). | Should | The system shall allow strategy configuration per the [compaction] section (reactive/proactive/semantic). |
| FR-7MayThe system shall support context-window resolution invariants across providers (respecting per-provider limits). | May | The system shall support context-window resolution invariants across providers (respecting per-provider limits). |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustCompactionReducing accumulated context (and the KV cache) when a session grows too large. must never lose the ability to resume the session. | Must | Reliability | CompactionReducing accumulated context (and the KV cache) when a session grows too large. must never lose the ability to resume the session. |
| NFR-2ShouldCompactionReducing accumulated context (and the KV cache) when a session grows too large. must be cheap enough to run mid-turn without disrupting the user. | Should | Performance | CompactionReducing accumulated context (and the KV cache) when a session grows too large. must be cheap enough to run mid-turn without disrupting the user. |
| NFR-3ShouldSessions at the context limit must be able to continue rather than fail. | Should | Availability | Sessions at the context limit must be able to continue rather than fail. |
Constraints
- CompactionReducing accumulated context (and the KV cache) when a session grows too large. interacts with the KV cacheProvider-side key-value cache for repeated prompt prefixes.; hashes must stay stable for unchanged prefixes.
- Context window limits differ per provider.
Acceptance Criteria
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FR-1MustThe system shall compact a session's context when it approaches the provider context window limit.
- Given a session near its context limit
- When a new turn starts
- Then the context is compacted and the turn continues
- FR-2MustThe system shall support multiple compaction strategies: reactive (on threshold), proactive (before it is needed), and semantic.
- Given each configured strategy
- When the strategy condition is met
- Then compaction runs accordingly
- FR-3MustThe system shall preserve a summary of the compacted context so later turns retain continuity.
- Given a compacted session
- When a later turn runs
- Then it receives a summary of the compacted context
- FR-4MustThe system shall record compaction state on the session so resume reflects the compacted context.
- Given a compacted session
- When the session is resumed
- Then the compacted state is reflected
- FR-5ShouldThe system shall keep a cache-relevant hash of messages so KV-cache prefix changes are detected after compaction.
- Given compaction of a session
- When cache-relevant hashes are computed
- Then the prefix change is detected for KV-cache correctness
- FR-6ShouldThe system shall allow strategy configuration per the `[compaction]` section (reactive/proactive/semantic).
- Given a
[compaction]config with a strategy - When jcode runs
- Then the configured strategy is used
- Given a
- FR-7MayThe system shall support context-window resolution invariants across providers (respecting per-provider limits).
- Given a provider with a known context window
- When the context window is resolved
- Then the resolved limit respects provider invariants
- NFR-1MustCompactionReducing accumulated context (and the KV cache) when a session grows too large. must never lose the ability to resume the session.
- Given a compacted session
- When the session is reopened
- Then it resumes without data loss
- NFR-2ShouldCompactionReducing accumulated context (and the KV cache) when a session grows too large. must be cheap enough to run mid-turn without disrupting the user.
- Given compaction running
- When the user continues interacting
- Then the disruption is minimal
- NFR-3ShouldSessions at the context limit must be able to continue rather than fail.
- Given a session at the limit
- When the user continues
- Then the session continues rather than failing on context overflow
Conflicts
None identified yet.
Open Questions
- What is the exact compaction trigger threshold and how much context is retained? The logic is inferred from
compaction.rsand the compaction core crate.
Specification: Context CompactionReducing accumulated context (and the KV cache) when a session grows too large.
Overview
CompactionReducing accumulated context (and the KV cache) when a session grows too large. is implemented in crates/jcode-base/src/compaction.rs (policy and state), crates/jcode-compaction-core (compaction engine), and crates/jcode-app-core/src/agent/compaction.rs (turn-loop integration). The message model supports OpenAICompaction content blocks and cache-relevant message hashes (stable_message_hash, cache_relevant_message_hashes) so KV-cache prefix changes are detected after compaction. This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
agent turn loop (app-core/agent/compaction.rs)
│ checks budget + strategy
▼
jcode-base/src/compaction.rs (reactive/proactive/semantic policy, session compaction state)
│
▼
jcode-compaction-core (engine)
│
├── summary preserved in message stream
├── session compaction state recorded (StoredCompactionState)
└── cache-relevant hashes updated for KV-cache correctness
Data Models
CompactionReducing accumulated context (and the KV cache) when a session grows too large. config ([compaction])
| Key | Description |
|---|---|
| reactive | Compact when approaching the limit. |
| proactive | Compact before it is needed. |
| semantic | CompactionReducing accumulated context (and the KV cache) when a session grows too large. informed by semantic importance. |
CompactionReducing accumulated context (and the KV cache) when a session grows too large.-related message model
| Field | Type | Description |
|---|---|---|
| OpenAICompaction | ContentBlock | Compacted-context marker in the message stream. |
| stable_message_hash | string | Stable hash for unchanged prefixes. |
| cache_relevant_message_hashes | list | Hashes that affect KV-cache prefix validity. |
Sequences
Reactive compaction on a turn
TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). start → context usage checked → limit approached
→ run compaction strategy → compress context → append summary
→ record compaction state on session → update cache-relevant hashes
→ turn continues with compacted context
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Multiple strategies | reactive/proactive/semantic | Users tune cost vs. context quality. |
| Hash-based KV-cache detection | stable_message_hash / cache_relevant_message_hashes |
Prevents stale KV-cache prefixes after compaction. |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. core crate | jcode-compaction-core |
Isolates engine from policy and turn-loop. |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. state persisted | StoredCompactionState |
Resume reflects compacted context. |
Risks and Unknowns
- CompactionReducing accumulated context (and the KV cache) when a session grows too large. thresholds and retention are not formally documented; inferred from code.
- Semantic compaction quality depends on model behavior and embedding importance scoring.
Out of Scope
- Lossless long-term context storage beyond the preserved summary.
- ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific compaction APIs that are not already integrated.
Test Plan: Context CompactionReducing accumulated context (and the KV cache) when a session grows too large.
Scope
Covers compaction policy, state, KV-cache hash correctness, and context-window resolution invariants. Out of scope: live provider behavior (covered by the context-window matrix suite where applicable).
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | CompactionReducing accumulated context (and the KV cache) when a session grows too large. policy and state | crates/jcode-base/src/compaction_tests.rs |
CompactionReducing accumulated context (and the KV cache) when a session grows too large. triggers and records state correctly |
| TC-2 | MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. cache-relevant hashing | crates/jcode-message-types unit tests |
Hashes stable for unchanged prefixes, change on compaction |
| TC-3 | Context-window resolution invariants | tests/context_window_matrix.rs |
Limits resolved per provider invariants |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-4 | Agent-loop compaction | crates/jcode-app-core/src/agent_tests.rs |
TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). loop compacts and continues correctly |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-5 | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. at context limit | Continues via compaction rather than failing |
| TC-6 | CompactionReducing accumulated context (and the KV cache) when a session grows too large. then resume | Compacted state reflected on resume |
| TC-7 | Cache-relevant prefix change | Detected; KV-cache correctness preserved |
Test Infrastructure
- Context-window matrix suite (
tests/context_window_matrix.rs). - MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks.-model unit fixtures.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall compact a session's context when it approaches the provider context window limit. | TC-1, TC-4 |
| FR-4MustThe system shall record compaction state on the session so resume reflects the compacted context. | TC-1, TC-6 |
| FR-5ShouldThe system shall keep a cache-relevant hash of messages so KV-cache prefix changes are detected after compaction. | TC-2, TC-7 |
| FR-7MayThe system shall support context-window resolution invariants across providers (respecting per-provider limits). | TC-3 |
| NFR-1MustCompactionReducing accumulated context (and the KV cache) when a session grows too large. must never lose the ability to resume the session. | TC-6 |
| NFR-3ShouldSessions at the context limit must be able to continue rather than fail. | TC-5 |
requirements
- What is the exact compaction trigger threshold and how much context is retained? The logic is inferred from
compaction.rsand the compaction core crate.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Agent Tool Suite
Overview
The agent tool suite is the runtime the model invokes to act on the world.
It provides a Tool trait, a registry that owns the live tool set, and the tool implementations themselves (file access, shell, web, MCP, coordination, memory, desktop surfaces).
This feature was reverse-engineered from the existing codebase during an SDLC sync and documents already-implemented functionality.
The command-safety gate, the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox, and agent applets are documented as separate features and are only referenced here as boundaries.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Model clients | A stable, discoverable tool surface with predictable schemas and predictable failures |
| End users | Tools that finish the job without silently eating the context window or leaking credentials |
| Maintainers | One place to reason about dispatch, policy, telemetry, and the tool inventory |
| Integrators | MCP servers, SDKSoftware Development Kit clients, and desktop surfaces that plug into the same registry |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall expose a registry that registers, unregisters, lists, and executes tools by name, and that publishes provider-facing tool definitions. | Must | The system shall expose a registry that registers, unregisters, lists, and executes tools by name, and that publishes provider-facing tool definitions. |
| FR-2MustThe system shall inject a shared `intent` property into every object-shaped tool schema and mark it required, so every call carries a human-readable reason. | Must | The system shall inject a shared intent property into every object-shaped tool schema and mark it required, so every call carries a human-readable reason. |
| FR-3MustThe system shall advertise an optional `accept_large_output` property on every object-shaped tool schema and honor it when the caller sets it. | Must | The system shall advertise an optional accept_large_output property on every object-shaped tool schema and honor it when the caller sets it. |
| FR-4MustThe system shall resolve provider and namespace tool-name aliases (including `functions.` prefixes, Claude Code names, and PascalCase OAuthOpen Authorization names) to canonical registry names before dispatch. | Must | The system shall resolve provider and namespace tool-name aliases (including functions. prefixes, Claude Code names, and PascalCase OAuthOpen Authorization names) to canonical registry names before dispatch. |
| FR-5MustThe system shall enforce the per-session tool allow list and deny list at execution time, including for MCP tools addressed through aliases retired after a reconnect. | Must | The system shall enforce the per-session tool allow list and deny list at execution time, including for MCP tools addressed through aliases retired after a reconnect. |
| FR-6MustThe system shall reject a call to an unknown tool with an error that lists the available tools and suggests near-miss names. | Must | The system shall reject a call to an unknown tool with an error that lists the available tools and suggests near-miss names. |
| FR-7MustThe system shall withhold a tool result that would exceed the context budget, and shall only return a truncated result when the caller explicitly opted in. | Must | The system shall withhold a tool result that would exceed the context budget, and shall only return a truncated result when the caller explicitly opted in. |
| FR-8MustThe system shall read files as text, image, or PDF, and shall report binary files without attempting to decode them. | Must | The system shall read files as text, image, or PDF, and shall report binary files without attempting to decode them. |
| FR-9MustThe system shall write files, creating parent directories as needed, and shall report a diff summary plus a unified diff. | Must | The system shall write files, creating parent directories as needed, and shall report a diff summary plus a unified diff. |
| FR-10MustThe system shall apply exact-match edits so that all edits in a call apply or none do. | Must | The system shall apply exact-match edits so that all edits in a call apply or none do. |
| FR-11MustThe system shall apply multi-file patches in both the Codex envelope format and the unified-diff format, including file creation, deletion, and moves. | Must | The system shall apply multi-file patches in both the Codex envelope format and the unified-diff format, including file creation, deletion, and moves. |
| FR-12MustThe system shall perform literal or regular-expression replacement across files, applying every replacement or none. | Must | The system shall perform literal or regular-expression replacement across files, applying every replacement or none. |
| FR-13MustThe system shall list directory contents on request. | Must | The system shall list directory contents on request. |
| FR-14MustThe system shall search code and file names, supporting grep, find, outline, and trace modes. | Must | The system shall search code and file names, supporting grep, find, outline, and trace modes. |
| FR-15MustThe system shall run shell commands, capturing standard output and standard error separately and reporting exit status. | Must | The system shall run shell commands, capturing standard output and standard error separately and reporting exit status. |
| FR-16MustThe system shall forward standard input to a running command when the command reads from it. | Must | The system shall forward standard input to a running command when the command reads from it. |
| FR-17MustThe system shall promote a command that exceeds the foreground timeout into a background task instead of discarding it. | Must | The system shall promote a command that exceeds the foreground timeout into a background task instead of discarding it. |
| FR-18MustThe system shall parse progress markers and progress heuristics from command output and surface them as task progress. | Must | The system shall parse progress markers and progress heuristics from command output and surface them as task progress. |
| FR-19MustThe system shall terminate the whole process group of a timed-out command so that no descendant survives. | Must | The system shall terminate the whole process group of a timed-out command so that no descendant survives. |
| FR-20MustThe system shall search the web through DuckDuckGo, Bing, SearXNG, or a custom engine, and shall try the configured fallback engines in order. | Must | The system shall search the web through DuckDuckGo, Bing, SearXNG, or a custom engine, and shall try the configured fallback engines in order. |
| FR-21MustThe system shall call a custom HTTP JSON search endpoint configured under `[websearch.custom]`, mapping the JSON response into title, URL, and snippet results. | Must | The system shall call a custom HTTP JSON search endpoint configured under [websearch.custom], mapping the JSON response into title, URL, and snippet results. |
| FR-22MustThe system shall keep custom-search credentials out of diagnostics and shall not forward credentials across redirects. | Must | The system shall keep custom-search credentials out of diagnostics and shall not forward credentials across redirects. |
| FR-23MustThe system shall fetch a URL and return it as text, Markdown, or HTML, subject to a response size cap and an output size cap. | Must | The system shall fetch a URL and return it as text, Markdown, or HTML, subject to a response size cap and an output size cap. |
| FR-24MustThe system shall manage MCP servers through the `mcp` tool, supporting listing, connecting, disconnecting, reloading, status, and logout. | Must | The system shall manage MCP servers through the mcp tool, supporting listing, connecting, disconnecting, reloading, status, and logout. |
| FR-25MustThe system shall expose the MCP tool catalog through a deferred search tool and a deferred call tool, so that a model can find and invoke a server tool by name. | Must | The system shall expose the MCP tool catalog through a deferred search tool and a deferred call tool, so that a model can find and invoke a server tool by name. |
| FR-26MustThe system shall register connected MCP server tools as callable tools under a namespaced alias, resolving alias collisions deterministically. | Must | The system shall register connected MCP server tools as callable tools under a namespaced alias, resolving alias collisions deterministically. |
| FR-27MustThe system shall cache MCP tool schemas on disk so that a new session can advertise the MCP surface before the connections settle. | Must | The system shall cache MCP tool schemas on disk so that a new session can advertise the MCP surface before the connections settle. |
| FR-28MustThe system shall run independent tool calls in parallel through the `batch` tool, and shall accept the common malformed shapes models produce. | Must | The system shall run independent tool calls in parallel through the batch tool, and shall accept the common malformed shapes models produce. |
| FR-29MustThe system shall coordinate multiple agents through the `swarm` tool, covering spawn, assignment, run plans, awaiting, status, and messaging. | Must | The system shall coordinate multiple agents through the swarm tool, covering spawn, assignment, run plans, awaiting, status, and messaging. |
| FR-30MustThe system shall track structured work items through the `todo` tool, including status, grouping, confidence, and goal-level assessment fields. | Must | The system shall track structured work items through the todo tool, including status, grouping, confidence, and goal-level assessment fields. |
| FR-31MustThe system shall manage background tasks through the `bg` tool, including listing, status, output, tail, cancel, cleanup, and waiting. | Must | The system shall manage background tasks through the bg tool, including listing, status, output, tail, cancel, cleanup, and waiting. |
| FR-32MustThe system shall persist and query long-lived memory through the `memory` tool, supporting remember, recall, search, list, forget, tag, link, and related actions. | Must | The system shall persist and query long-lived memory through the memory tool, supporting remember, recall, search, list, forget, tag, link, and related actions. |
| FR-33MustThe system shall search past chat sessions through the `session_search` tool and in-conversation history through the `conversation_search` tool, with filters and grouping. | Must | The system shall search past chat sessions through the session_search tool and in-conversation history through the conversation_search tool, with filters and grouping. |
| FR-34MustThe system shall load, list, read, and reload skills through the `skill_manage` tool. | Must | The system shall load, list, read, and reload skills through the skill_manage tool. |
| FR-35MustThe system shall search the bundled Jcode documentation through the `jcode_docs` tool. | Must | The system shall search the bundled Jcode documentation through the jcode_docs tool. |
| FR-36MustThe system shall record a structured lifecycle event for every tool call, covering the requested name, the resolved name, the status, the latency, the output size, and the touched paths. | Must | The system shall record a structured lifecycle event for every tool call, covering the requested name, the resolved name, the status, the latency, the output size, and the touched paths. |
| FR-37MustThe system shall let a user-configured pre-tool hook block a call, and shall let post-tool observers and post-tool feedback hooks observe the outcome and append feedback to the result. | Must | The system shall let a user-configured pre-tool hook block a call, and shall let post-tool observers and post-tool feedback hooks observe the outcome and append feedback to the result. |
| FR-38ShouldThe system shall open desktop panels from Markdown or Markdown/PDF files and manage their lifecycle through the `panel` tool, and shall keep the legacy `side_panel` tool working. | Should | The system shall open desktop panels from Markdown or Markdown/PDF files and manage their lifecycle through the panel tool, and shall keep the legacy side_panel tool working. |
| FR-39ShouldThe system shall render an interactive native card through the `applet` tool and an inline Markdown answer through the `user_responseThe tool that returns a Markdown response to a Desktop-capable client.` tool, and shall expose both only when the desktop UI capability is enabled. | Should | The system shall render an interactive native card through the applet tool and an inline Markdown answer through the user_responseThe tool that returns a Markdown response to a Desktop-capable client. tool, and shall expose both only when the desktop UI capability is enabled. |
| FR-40ShouldThe system shall drive a real browser through the `browser` tool, covering navigation, content extraction, scripted evaluation, and interaction. | Should | The system shall drive a real browser through the browser tool, covering navigation, content extraction, scripted evaluation, and interaction. |
| FR-41ShouldThe system shall compile source in a remote sandbox through the `compile_remote` tool, reserving and settling metered usage against the subscription. | Should | The system shall compile source in a remote sandbox through the compile_remote tool, reserving and settling metered usage against the subscription. |
| FR-42ShouldThe system shall run a JavaScript program that calls other tools through the `codemode` tool, and shall register that tool only when it is enabled in the configuration. | Should | The system shall run a JavaScript program that calls other tools through the codemode tool, and shall register that tool only when it is enabled in the configuration. |
| FR-43ShouldThe system shall discover external integrations through the `integration_tools` tool, and shall register that tool only when integration discovery is enabled. | Should | The system shall discover external integrations through the integration_tools tool, and shall register that tool only when integration discovery is enabled. |
| FR-44ShouldThe system shall read and send mail through the `gmail` tool and manage calendars through the `calendar` tool. | Should | The system shall read and send mail through the gmail tool and manage calendars through the calendar tool. |
| FR-45ShouldThe system shall open or reveal a file, a folder, or a URL for the user through the `open` tool. | Should | The system shall open or reveal a file, a folder, or a URL for the user through the open tool. |
| FR-46ShouldThe system shall build, reload, test, and inspect the project under development through the `selfdev`, `desktop_selfdev`, and `debug_socket` tools. | Should | The system shall build, reload, test, and inspect the project under development through the selfdev, desktop_selfdev, and debug_socket tools. |
| FR-47ShouldThe system shall register the ambient-mode tools (`end_ambient_cycle`, `schedule_ambient`, `request_permission`, `send_message`, and `schedule`) only for ambient sessions. | Should | The system shall register the ambient-mode tools (end_ambient_cycle, schedule_ambient, request_permission, send_message, and schedule) only for ambient sessions. |
| FR-48ShouldThe system shall control the macOS desktop through the `macos_computer_use` tool on macOS hosts only. | Should | The system shall control the macOS desktop through the macos_computer_use tool on macOS hosts only. |
| FR-49MayThe system shall let a client register session-scoped custom tool callbacks that the registry dispatches to instead of a built-in tool. | May | The system shall let a client register session-scoped custom tool callbacks that the registry dispatches to instead of a built-in tool. |
| FR-50MayThe system shall provide the `maintainer_feedback` and `invalid` tools for product feedback and for reporting malformed tool usage. | May | The system shall provide the maintainer_feedback and invalid tools for product feedback and for reporting malformed tool usage. |
| FR-51MayThe system shall keep the `initiative` and `patch` tool implementations available but unregistered, so they can be restored without a migration. | May | The system shall keep the initiative and patch tool implementations available but unregistered, so they can be restored without a migration. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustThe system shall build the stateless base tool set once per process and reuse it across sessions, so session startup does not pay per-tool construction cost. | Must | Performance | The system shall build the stateless base tool set once per process and reuse it across sessions, so session startup does not pay per-tool construction cost. |
| NFR-2MustA single tool result shall not exceed the smaller of 30% of the context budget and 50,000 tokens, so no one result can dominate a context window. | Must | Performance | A single tool result shall not exceed the smaller of 30% of the context budget and 50,000 tokens, so no one result can dominate a context window. |
| NFR-3MustThe system shall resolve relative tool paths against the session working directory, and shall not let one tool write outside the paths its input names. | Must | Security | The system shall resolve relative tool paths against the session working directory, and shall not let one tool write outside the paths its input names. |
| NFR-4MustThe system shall never write a configured credential, endpoint URL, or request body into a log line, an error message, or a hook payload. | Must | Security | The system shall never write a configured credential, endpoint URL, or request body into a log line, an error message, or a hook payload. |
| NFR-5MustThe system shall serialize concurrent writes to the same file so that two tools cannot interleave a partial write. | Must | Safety | The system shall serialize concurrent writes to the same file so that two tools cannot interleave a partial write. |
| NFR-6ShouldThe system shall skip the MCP alias rebuild when a reconnected server's tool catalog is unchanged, so a reload storm does not scale with the number of servers. | Should | Performance | The system shall skip the MCP alias rebuild when a reconnected server's tool catalog is unchanged, so a reload storm does not scale with the number of servers. |
| NFR-7ShouldThe system shall publish tool definitions in a stable sorted order, so provider prompt caches are not invalidated by registry ordering. | Should | Performance | The system shall publish tool definitions in a stable sorted order, so provider prompt caches are not invalidated by registry ordering. |
| NFR-8ShouldThe system shall keep every tool description and every tool parameter description under a documented token cap, because the text rides on every request. | Should | Maintainability | The system shall keep every tool description and every tool parameter description under a documented token cap, because the text rides on every request. |
| NFR-9ShouldThe system shall not emit tool schemas that strict-mode providers reject, such as an array of a union type or a `required` entry with no matching property. | Should | Compatibility | The system shall not emit tool schemas that strict-mode providers reject, such as an array of a union type or a required entry with no matching property. |
| NFR-10ShouldThe system shall emit one structured lifecycle event per tool call, so an operator can reconstruct which tool ran, with which arguments, and with what outcome. | Should | Observability | The system shall emit one structured lifecycle event per tool call, so an operator can reconstruct which tool ran, with which arguments, and with what outcome. |
| NFR-11ShouldA failing tool shall return a diagnostic error to the caller rather than terminating the turn. | Should | Reliability | A failing tool shall return a diagnostic error to the caller rather than terminating the turn. |
| NFR-12MayThe system shall keep platform-specific tools behind a target guard, so the same registry builds on Linux, macOS, and Windows. | May | Portability | The system shall keep platform-specific tools behind a target guard, so the same registry builds on Linux, macOS, and Windows. |
Constraints
- The tool trait and the shared output types live in the
jcode-tool-coreandjcode-tool-typescrates, and the tool implementations live incrates/jcode-app-core/src/tool/. - The registry key is the provider-facing tool name, and it overrides the name the tool reports for itself.
- A tool stored inside the registry holds only a weak reference to the registry, so the registry does not own itself.
jcode-tool-types::resolve_tool_nameowns the alias table, so that lower-level crates can normalize names without depending on the tool subsystem.- The command-safety gate, the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox, and the agent applet runtime are separate features.
Acceptance Criteria
Every FR and NFR shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
Acceptance criteria verify how a requirement is proven done, they do not restate it.
Write concrete, scenario-based criteria (happy path, edge cases and error states where applicable).
Write each criterion as a fenced gherkin block with a tag matching its requirement ID, so the criteria are parseable and later executable via BDD tooling (pytest-bdd, cucumber).
Multiple scenarios per requirement are allowed; tag each with the requirement ID.
-
FR-1MustThe system shall expose a registry that registers, unregisters, lists, and executes tools by name, and that publishes provider-facing tool definitions.
gherkin @FR-1MustThe system shall expose a registry that registers, unregisters, lists, and executes tools by name, and that publishes provider-facing tool definitions. Scenario: Register and execute a tool by name Given a registry with the read tool registered When the registry executes "read" with a path to an existing text file Then the tool output contains the file contents And the registry lists "read" among its tool names -
FR-2MustThe system shall inject a shared `intent` property into every object-shaped tool schema and mark it required, so every call carries a human-readable reason.
gherkin @FR-2MustThe system shall inject a shared `intent` property into every object-shaped tool schema and mark it required, so every call carries a human-readable reason. Scenario: Every tool schema requires an intent Given the provider-facing definitions of the first-party tools When each definition is inspected Then every object schema has an "intent" property And "intent" appears in the required list of every object schema -
FR-3MustThe system shall advertise an optional `accept_large_output` property on every object-shaped tool schema and honor it when the caller sets it.
gherkin @FR-3MustThe system shall advertise an optional `accept_large_output` property on every object-shaped tool schema and honor it when the caller sets it. Scenario: The oversized-output opt-in is advertised and honored Given a tool whose result is larger than the context guard allows When the call is made without "accept_large_output" Then the result is withheld and a refusal message is returned When the same call is made with "accept_large_output" set to true Then the result is returned truncated with a truncation notice -
FR-4MustThe system shall resolve provider and namespace tool-name aliases (including `functions.` prefixes, Claude Code names, and PascalCase OAuthOpen Authorization names) to canonical registry names before dispatch.
gherkin @FR-4MustThe system shall resolve provider and namespace tool-name aliases (including `functions.` prefixes, Claude Code names, and PascalCase OAuthOpen Authorization names) to canonical registry names before dispatch. Scenario: ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). aliases resolve to the canonical tool Given a registry containing the bash tool When a call names the tool "shell_exec" or "functions.Bash" Then the bash tool runs And the lifecycle event records both the requested name and the resolved name -
FR-5MustThe system shall enforce the per-session tool allow list and deny list at execution time, including for MCP tools addressed through aliases retired after a reconnect.
gherkin @FR-5MustThe system shall enforce the per-session tool allow list and deny list at execution time, including for MCP tools addressed through aliases retired after a reconnect. Scenario: A denied tool is refused Given a session policy that denies the bash tool When the model calls the bash tool Then the call fails with a "disabled" error And the shell command is never started -
FR-6MustThe system shall reject a call to an unknown tool with an error that lists the available tools and suggests near-miss names.
gherkin @FR-6MustThe system shall reject a call to an unknown tool with an error that lists the available tools and suggests near-miss names. Scenario: An unknown tool name yields a recoverable error Given a registry with the read tool registered When a call names the tool "reed" Then the error names the unknown tool And the error lists the available tools And the error suggests the read tool -
FR-7MustThe system shall withhold a tool result that would exceed the context budget, and shall only return a truncated result when the caller explicitly opted in.
gherkin @FR-7MustThe system shall withhold a tool result that would exceed the context budget, and shall only return a truncated result when the caller explicitly opted in. Scenario: An unaffordable result is withheld rather than truncated Given a context budget that is nearly exhausted When a tool returns a result larger than the remaining budget Then the result is withheld and the caller is told to compact And the withheld bytes are not added to the context -
FR-8MustThe system shall read files as text, image, or PDF, and shall report binary files without attempting to decode them.
gherkin @FR-8MustThe system shall read files as text, image, or PDF, and shall report binary files without attempting to decode them. Scenario: Read a file, an image, and a binary file Given a text file, a PNG image, and a binary file in the working directory When the read tool is called for each of them Then the text file is returned as text And the image is returned as an image block And the binary file is reported as binary without a decode attempt -
FR-9MustThe system shall write files, creating parent directories as needed, and shall report a diff summary plus a unified diff.
gherkin @FR-9MustThe system shall write files, creating parent directories as needed, and shall report a diff summary plus a unified diff. Scenario: Write a new file Given a working directory with no target file When the write tool is called with a file path and content Then the file exists with exactly that content And the output reports the file as created with a diff summary -
FR-10MustThe system shall apply exact-match edits so that all edits in a call apply or none do.
gherkin @FR-10MustThe system shall apply exact-match edits so that all edits in a call apply or none do. Scenario: A failed edit leaves the file untouched Given a file whose second edit target does not exist When the edit tool is called with both edits Then the call fails And the file content is unchanged -
FR-11MustThe system shall apply multi-file patches in both the Codex envelope format and the unified-diff format, including file creation, deletion, and moves.
gherkin @FR-11MustThe system shall apply multi-file patches in both the Codex envelope format and the unified-diff format, including file creation, deletion, and moves. Scenario: Apply a multi-file patch Given a Codex-style patch that adds one file and updates another When the apply_patch tool is called Then both files are changed on disk And the output reports the files that changed -
FR-12MustThe system shall perform literal or regular-expression replacement across files, applying every replacement or none.
gherkin @FR-12MustThe system shall perform literal or regular-expression replacement across files, applying every replacement or none. Scenario: A cross-file replacement either lands everywhere or nowhere Given two files that both contain the search string When the replace tool is called with a regular expression Then both files are updated And a replacement that cannot be applied to one file leaves both files unchanged -
FR-13MustThe system shall list directory contents on request.
gherkin @FR-13MustThe system shall list directory contents on request. Scenario: List a directory Given a working directory holding two files and one subdirectory When the ls tool is called Then the output names both files and the subdirectory -
FR-14MustThe system shall search code and file names, supporting grep, find, outline, and trace modes.
gherkin @FR-14MustThe system shall search code and file names, supporting grep, find, outline, and trace modes. Scenario: Search for a symbol Given a source tree containing a matching function When the agentgrep tool is called in grep mode Then the output names the matching file and line When the mode is omitted Then the search runs in grep mode -
FR-15MustThe system shall run shell commands, capturing standard output and standard error separately and reporting exit status.
gherkin @FR-15MustThe system shall run shell commands, capturing standard output and standard error separately and reporting exit status. Scenario: Run a command and capture both streams Given a command that writes to standard output and standard error When the bash tool runs it Then the output contains the standard output text And the output reports the non-zero exit status and the standard error text -
FR-16MustThe system shall forward standard input to a running command when the command reads from it.
gherkin @FR-16MustThe system shall forward standard input to a running command when the command reads from it. Scenario: Forward input to a command that reads it Given a command that reads one line from standard input When the bash tool runs it and the session supplies that line Then the command output contains the supplied line -
FR-17MustThe system shall promote a command that exceeds the foreground timeout into a background task instead of discarding it.
gherkin @FR-17MustThe system shall promote a command that exceeds the foreground timeout into a background task instead of discarding it. Scenario: A command that outlasts the foreground timeout is promoted Given a command that runs longer than the foreground timeout When the bash tool runs it Then the call returns with a background task identifier And the command is still running as a background task -
FR-18MustThe system shall parse progress markers and progress heuristics from command output and surface them as task progress.
gherkin @FR-18MustThe system shall parse progress markers and progress heuristics from command output and surface them as task progress. Scenario: Progress output becomes task progress Given a background command that prints a progress marker When the progress marker is parsed Then the task status reports the reported percentage And the marker line is not repeated in the captured output -
FR-19MustThe system shall terminate the whole process group of a timed-out command so that no descendant survives.
gherkin @FR-19MustThe system shall terminate the whole process group of a timed-out command so that no descendant survives. Scenario: A timeout kills the whole process group Given a command that spawns a long-lived child process When the command times out Then neither the parent nor the child process survives -
FR-20MustThe system shall search the web through DuckDuckGo, Bing, SearXNG, or a custom engine, and shall try the configured fallback engines in order.
gherkin @FR-20MustThe system shall search the web through DuckDuckGo, Bing, SearXNG, or a custom engine, and shall try the configured fallback engines in order. Scenario: Fall back when the preferred engine yields nothing Given a preferred engine that returns no results And a configured fallback engine that returns one result When the websearch tool runs Then the fallback engine's result is returned -
FR-21MustThe system shall call a custom HTTP JSON search endpoint configured under `[websearch.custom]`, mapping the JSON response into title, URL, and snippet results.
gherkin @FR-21MustThe system shall call a custom HTTP JSON search endpoint configured under `[websearch.custom]`, mapping the JSON response into title, URL, and snippet results. Scenario: Map a custom search response Given a custom search endpoint that returns a JSON array at the configured results pointer When the websearch tool runs with engine "custom" Then each result's title, URL, and snippet are read through the configured pointers And a result with a missing URL is skipped -
FR-22MustThe system shall keep custom-search credentials out of diagnostics and shall not forward credentials across redirects.
gherkin @FR-22MustThe system shall keep custom-search credentials out of diagnostics and shall not forward credentials across redirects. Scenario: Credentials never leak and redirects are not followed Given a custom search endpoint that answers with a redirect to another host When the websearch tool runs Then the redirect is not followed And no error message or log line contains the configured credential -
FR-23MustThe system shall fetch a URL and return it as text, Markdown, or HTML, subject to a response size cap and an output size cap.
gherkin @FR-23MustThe system shall fetch a URL and return it as text, Markdown, or HTML, subject to a response size cap and an output size cap. Scenario: Fetch a page as Markdown Given a reachable web page When the webfetch tool is called with format "markdown" Then the output is the extracted Markdown text And a non-HTTP scheme is rejected before any request is made -
FR-24MustThe system shall manage MCP servers through the `mcp` tool, supporting listing, connecting, disconnecting, reloading, status, and logout.
gherkin @FR-24MustThe system shall manage MCP servers through the `mcp` tool, supporting listing, connecting, disconnecting, reloading, status, and logout. Scenario: Manage MCP servers Given a configured MCP server that is disabled When the mcp tool lists the servers Then the disabled server is listed and is not spawned When the mcp tool connects to it by name Then the connection is reported as established -
FR-25MustThe system shall expose the MCP tool catalog through a deferred search tool and a deferred call tool, so that a model can find and invoke a server tool by name.
gherkin @FR-25MustThe system shall expose the MCP tool catalog through a deferred search tool and a deferred call tool, so that a model can find and invoke a server tool by name. Scenario: Find and call a server tool Given a connected MCP server exposing a "read_file" tool When the mcp_search tool searches for "read" Then the result names the callable tool and its input schema When the mcp_call tool calls that tool Then the server's result is returned to the caller -
FR-26MustThe system shall register connected MCP server tools as callable tools under a namespaced alias, resolving alias collisions deterministically.
gherkin @FR-26MustThe system shall register connected MCP server tools as callable tools under a namespaced alias, resolving alias collisions deterministically. Scenario: Two servers exposing the same tool name get distinct aliases Given two connected MCP servers that each expose a "search" tool When the MCP surface is reconciled Then both tools are callable under distinct names And the registry maps each alias back to its own server -
FR-27MustThe system shall cache MCP tool schemas on disk so that a new session can advertise the MCP surface before the connections settle.
gherkin @FR-27MustThe system shall cache MCP tool schemas on disk so that a new session can advertise the MCP surface before the connections settle. Scenario: The MCP surface is advertised before connections settle Given a cached schema for a configured MCP server When a new session starts Then the cached MCP tools are present in the first tool snapshot -
FR-28MustThe system shall run independent tool calls in parallel through the `batch` tool, and shall accept the common malformed shapes models produce.
gherkin @FR-28MustThe system shall run independent tool calls in parallel through the `batch` tool, and shall accept the common malformed shapes models produce. Scenario: Batch runs calls in parallel and tolerates malformed shapes Given a batch of two independent read calls When the batch tool runs with the tool name given as "name" and the arguments given flat Then both reads run and both results are returned And a batch of more than ten calls is rejected -
FR-29MustThe system shall coordinate multiple agents through the `swarm` tool, covering spawn, assignment, run plans, awaiting, status, and messaging.
gherkin @FR-29MustThe system shall coordinate multiple agents through the `swarm` tool, covering spawn, assignment, run plans, awaiting, status, and messaging. Scenario: Run a swarm plan Given a plan with two independent nodes When the swarm tool runs the plan Then each node is dispatched to a worker And the terminal summary reports the succeeded and failed nodes -
FR-30MustThe system shall track structured work items through the `todo` tool, including status, grouping, confidence, and goal-level assessment fields.
gherkin @FR-30MustThe system shall track structured work items through the `todo` tool, including status, grouping, confidence, and goal-level assessment fields. Scenario: Track a multi-step task Given a task with three steps When the todo tool creates the items and marks the first one in progress Then the list reports one item in progress and two pending And each item carries its status and group -
FR-31MustThe system shall manage background tasks through the `bg` tool, including listing, status, output, tail, cancel, cleanup, and waiting.
gherkin @FR-31MustThe system shall manage background tasks through the `bg` tool, including listing, status, output, tail, cancel, cleanup, and waiting. Scenario: Wait for a background task Given a running background task When the bg tool waits for it Then the call returns when the task finishes And the output carries the task output and its status -
FR-32MustThe system shall persist and query long-lived memory through the `memory` tool, supporting remember, recall, search, list, forget, tag, link, and related actions.
gherkin @FR-32MustThe system shall persist and query long-lived memory through the `memory` tool, supporting remember, recall, search, list, forget, tag, link, and related actions. Scenario: Remember and recall a fact Given a memory store with no entry for a given query When the memory tool remembers a fact and then recalls it Then the recalled entry carries the fact and its category -
FR-33MustThe system shall search past chat sessions through the `session_search` tool and in-conversation history through the `conversation_search` tool, with filters and grouping.
gherkin @FR-33MustThe system shall search past chat sessions through the `session_search` tool and in-conversation history through the `conversation_search` tool, with filters and grouping. Scenario: Search a past session Given a saved session that contains a matching phrase When the session_search tool runs Then the result names the session and points at the matching message And the current session is excluded by default -
FR-34MustThe system shall load, list, read, and reload skills through the `skill_manage` tool.
gherkin @FR-34MustThe system shall load, list, read, and reload skills through the `skill_manage` tool. Scenario: List and load a skill Given a skill registry holding one skill When the skill_manage tool lists the skills Then the skill is listed When the skill_manage tool loads that skill Then the skill content is returned -
FR-35MustThe system shall search the bundled Jcode documentation through the `jcode_docs` tool.
gherkin @FR-35MustThe system shall search the bundled Jcode documentation through the `jcode_docs` tool. Scenario: Search the bundled documentation Given the bundled Jcode documentation When the jcode_docs tool searches for a configuration key Then the output cites the matching documentation section -
FR-36MustThe system shall record a structured lifecycle event for every tool call, covering the requested name, the resolved name, the status, the latency, the output size, and the touched paths.
gherkin @FR-36MustThe system shall record a structured lifecycle event for every tool call, covering the requested name, the resolved name, the status, the latency, the output size, and the touched paths. Scenario: Every call produces lifecycle events Given a tool that fails When the tool runs Then a start event and an error event are emitted And the events carry the resolved tool name, the status, the latency, and the touched paths -
FR-37MustThe system shall let a user-configured pre-tool hook block a call, and shall let post-tool observers and post-tool feedback hooks observe the outcome and append feedback to the result.
gherkin @FR-37MustThe system shall let a user-configured pre-tool hook block a call, and shall let post-tool observers and post-tool feedback hooks observe the outcome and append feedback to the result. Scenario: A pre-tool hook blocks the call Given a configured pre_tool hook that exits with a block decision When a tool call is made Then the call fails with the hook's reason And the tool never runs -
FR-38ShouldThe system shall open desktop panels from Markdown or Markdown/PDF files and manage their lifecycle through the `panel` tool, and shall keep the legacy `side_panel` tool working.
gherkin @FR-38ShouldThe system shall open desktop panels from Markdown or Markdown/PDF files and manage their lifecycle through the `panel` tool, and shall keep the legacy `side_panel` tool working. Scenario: Open a desktop panel Given the desktop UI capability is enabled When the panel tool spawns a panel from Markdown content Then the panel is listed by the panel tool -
FR-39ShouldThe system shall render an interactive native card through the `applet` tool and an inline Markdown answer through the `user_responseThe tool that returns a Markdown response to a Desktop-capable client.` tool, and shall expose both only when the desktop UI capability is enabled.
gherkin @FR-39ShouldThe system shall render an interactive native card through the `applet` tool and an inline Markdown answer through the `user_responseThe tool that returns a Markdown response to a Desktop-capable client.` tool, and shall expose both only when the desktop UI capability is enabled. Scenario: Desktop-only tools stay hidden elsewhere Given a registry with the desktop UI capability disabled When the tool definitions are published Then neither the applet tool nor the user_responseThe tool that returns a Markdown response to a Desktop-capable client. tool is advertised And a call to either name fails as an unknown tool -
FR-40ShouldThe system shall drive a real browser through the `browser` tool, covering navigation, content extraction, scripted evaluation, and interaction.
gherkin @FR-40ShouldThe system shall drive a real browser through the `browser` tool, covering navigation, content extraction, scripted evaluation, and interaction. Scenario: Drive a browser Given a browser provider that is ready When the browser tool navigates to a page and requests its content Then the output contains the page content -
FR-41ShouldThe system shall compile source in a remote sandbox through the `compile_remote` tool, reserving and settling metered usage against the subscription.
gherkin @FR-41ShouldThe system shall compile source in a remote sandbox through the `compile_remote` tool, reserving and settling metered usage against the subscription. Scenario: Compile remotely with metered usage Given a signed-in account with remote compilation entitlement When the compile_remote tool submits a build Then the output carries the compiler output and the metered usage -
FR-42ShouldThe system shall run a JavaScript program that calls other tools through the `codemode` tool, and shall register that tool only when it is enabled in the configuration.
gherkin @FR-42ShouldThe system shall run a JavaScript program that calls other tools through the `codemode` tool, and shall register that tool only when it is enabled in the configuration. Scenario: CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. chains tool calls Given codemode is enabled in the configuration When the codemode tool runs a script that calls the read tool twice Then the script result is returned and the two reads never enter the conversation And the codemode tool is absent when the feature is disabled -
FR-43ShouldThe system shall discover external integrations through the `integration_tools` tool, and shall register that tool only when integration discovery is enabled.
gherkin @FR-43ShouldThe system shall discover external integrations through the `integration_tools` tool, and shall register that tool only when integration discovery is enabled. Scenario: Discover an integration Given integration discovery is enabled When the integration_tools tool searches for a category Then the output lists matching integrations And the tool is absent when discovery is disabled -
FR-44ShouldThe system shall read and send mail through the `gmail` tool and manage calendars through the `calendar` tool.
gherkin @FR-44ShouldThe system shall read and send mail through the `gmail` tool and manage calendars through the `calendar` tool. Scenario: List calendars Given a connected Google account When the calendar tool lists the calendars Then the output names the available calendars -
FR-45ShouldThe system shall open or reveal a file, a folder, or a URL for the user through the `open` tool.
gherkin @FR-45ShouldThe system shall open or reveal a file, a folder, or a URL for the user through the `open` tool. Scenario: Reveal a file Given a file in the working directory When the open tool is called with action "reveal" and that path Then the tool reports that the file was revealed -
FR-46ShouldThe system shall build, reload, test, and inspect the project under development through the `selfdev`, `desktop_selfdev`, and `debug_socket` tools.
gherkin @FR-46ShouldThe system shall build, reload, test, and inspect the project under development through the `selfdev`, `desktop_selfdev`, and `debug_socket` tools. Scenario: The CLI self-dev tool refuses to run in a Desktop checkout Given a working directory that is a Jcode Desktop checkout When the selfdev tool is called Then the call fails and points at the desktop_selfdev tool -
FR-47ShouldThe system shall register the ambient-mode tools (`end_ambient_cycle`, `schedule_ambient`, `request_permission`, `send_message`, and `schedule`) only for ambient sessions.
gherkin @FR-47ShouldThe system shall register the ambient-mode tools (`end_ambient_cycle`, `schedule_ambient`, `request_permission`, `send_message`, and `schedule`) only for ambient sessions. Scenario: Ambient tools are ambient-only Given a session that is not an ambient session When the request_permission tool is called Then the call is rejected -
FR-48ShouldThe system shall control the macOS desktop through the `macos_computer_use` tool on macOS hosts only.
gherkin @FR-48ShouldThe system shall control the macOS desktop through the `macos_computer_use` tool on macOS hosts only. Scenario: The computer-use tool only exists on macOS Given a registry built on a macOS host When the tool definitions are published Then the macos_computer_use tool is advertised -
FR-49MayThe system shall let a client register session-scoped custom tool callbacks that the registry dispatches to instead of a built-in tool.
gherkin @FR-49MayThe system shall let a client register session-scoped custom tool callbacks that the registry dispatches to instead of a built-in tool. Scenario: A client-registered tool is dispatched Given a client that registered a custom tool for the session When the model calls that tool name Then the client callback runs And the callback result is returned to the caller -
FR-50MayThe system shall provide the `maintainer_feedback` and `invalid` tools for product feedback and for reporting malformed tool usage.
gherkin @FR-50MayThe system shall provide the `maintainer_feedback` and `invalid` tools for product feedback and for reporting malformed tool usage. Scenario: Report invalid tool usage Given a malformed tool call When the invalid tool is called Then the output records the malformed usage -
FR-51MayThe system shall keep the `initiative` and `patch` tool implementations available but unregistered, so they can be restored without a migration.
gherkin @FR-51MayThe system shall keep the `initiative` and `patch` tool implementations available but unregistered, so they can be restored without a migration. Scenario: Retained tools stay unregistered Given a registry with the base tool set When the tool definitions are published Then neither the initiative tool nor the patch tool is advertised -
NFR-1MustThe system shall build the stateless base tool set once per process and reuse it across sessions, so session startup does not pay per-tool construction cost.
gherkin @NFR-1MustThe system shall build the stateless base tool set once per process and reuse it across sessions, so session startup does not pay per-tool construction cost. Scenario: The base tool set is built once per process Given two sessions created in the same process When both registries are created Then the per-tool construction work happens only for the first session -
NFR-2MustA single tool result shall not exceed the smaller of 30% of the context budget and 50,000 tokens, so no one result can dominate a context window.
gherkin @NFR-2MustA single tool result shall not exceed the smaller of 30% of the context budget and 50,000 tokens, so no one result can dominate a context window. Scenario: A single huge result is capped Given a context budget of 1,000,000 tokens When a tool returns a result of 200,000 tokens Then the result is withheld And the refusal message states the cost -
NFR-3MustThe system shall resolve relative tool paths against the session working directory, and shall not let one tool write outside the paths its input names.
gherkin @NFR-3MustThe system shall resolve relative tool paths against the session working directory, and shall not let one tool write outside the paths its input names. Scenario: Relative paths resolve against the session working directory Given a session whose working directory holds a target file When the read tool is called with a relative path Then the file inside the working directory is read -
NFR-4MustThe system shall never write a configured credential, endpoint URL, or request body into a log line, an error message, or a hook payload.
gherkin @NFR-4MustThe system shall never write a configured credential, endpoint URL, or request body into a log line, an error message, or a hook payload. Scenario: Diagnostics carry no secrets Given a custom search endpoint configured with a header credential When the request fails Then neither the error message nor the log output contains the credential value -
NFR-5MustThe system shall serialize concurrent writes to the same file so that two tools cannot interleave a partial write.
gherkin @NFR-5MustThe system shall serialize concurrent writes to the same file so that two tools cannot interleave a partial write. Scenario: Concurrent writes to one file are serialized Given two write calls naming the same file When both run at the same time Then the file ends with one complete write, not an interleaved mixture -
NFR-6ShouldThe system shall skip the MCP alias rebuild when a reconnected server's tool catalog is unchanged, so a reload storm does not scale with the number of servers.
gherkin @NFR-6ShouldThe system shall skip the MCP alias rebuild when a reconnected server's tool catalog is unchanged, so a reload storm does not scale with the number of servers. Scenario: An unchanged reconnect does not rebuild the surface Given a connected MCP server whose catalog did not change When the server reconnects Then the alias set is left untouched -
NFR-7ShouldThe system shall publish tool definitions in a stable sorted order, so provider prompt caches are not invalidated by registry ordering.
gherkin @NFR-7ShouldThe system shall publish tool definitions in a stable sorted order, so provider prompt caches are not invalidated by registry ordering. Scenario: Definitions are emitted in a stable order Given a registry with several tools When the definitions are published twice Then both listings are in the same sorted order -
NFR-8ShouldThe system shall keep every tool description and every tool parameter description under a documented token cap, because the text rides on every request.
gherkin @NFR-8ShouldThe system shall keep every tool description and every tool parameter description under a documented token cap, because the text rides on every request. Scenario: Descriptions stay under the token cap Given the provider-facing definitions of the first-party tools When each description is measured Then no tool description exceeds the cap And no tool parameter description exceeds the cap -
NFR-9ShouldThe system shall not emit tool schemas that strict-mode providers reject, such as an array of a union type or a `required` entry with no matching property.
gherkin @NFR-9ShouldThe system shall not emit tool schemas that strict-mode providers reject, such as an array of a union type or a `required` entry with no matching property. Scenario: Schemas stay acceptable to strict providers Given the provider-facing definitions of the first-party tools When each schema is validated Then no array property is typed as a union And no required entry lacks a matching property -
NFR-10ShouldThe system shall emit one structured lifecycle event per tool call, so an operator can reconstruct which tool ran, with which arguments, and with what outcome.
gherkin @NFR-10ShouldThe system shall emit one structured lifecycle event per tool call, so an operator can reconstruct which tool ran, with which arguments, and with what outcome. Scenario: A tool run is reconstructable from the event log Given a tool that touches two files When the tool runs Then the lifecycle event names both touched paths and the outcome -
NFR-11ShouldA failing tool shall return a diagnostic error to the caller rather than terminating the turn.
gherkin @NFR-11ShouldA failing tool shall return a diagnostic error to the caller rather than terminating the turn. Scenario: A tool error does not end the turn Given a tool that always fails When the tool runs Then the failure is returned as a tool error And the surrounding turn continues -
NFR-12MayThe system shall keep platform-specific tools behind a target guard, so the same registry builds on Linux, macOS, and Windows.
gherkin @NFR-12MayThe system shall keep platform-specific tools behind a target guard, so the same registry builds on Linux, macOS, and Windows. Scenario: Platform-specific tools are guarded Given a registry built on a non-macOS host When the tool definitions are published Then no macOS-only tool is advertised
Conflicts
None identified yet.
Open Questions
- None. The feature is already implemented; any future change should be tracked as a new issue.
Specification: Agent Tool Suite
Overview
The tool runtime is split across three crates.
jcode-tool-types owns the shared data model (ToolOutput, ToolImage) and the canonical tool-name alias table.
jcode-tool-core owns the Tool trait, the ToolContext handed to every call, and the schema helpers that inject the shared intent and accept_large_output properties.
jcode-app-core owns the Registry and every concrete tool implementation under crates/jcode-app-core/src/tool/.
The registry resolves the requested name to a canonical name, enforces the session allow and deny policy, runs the pre-tool gate, dispatches to the tool, applies the post-tool hooks, and guards the result against the context budget.
This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
model turn
│
▼
jcode-app-core/src/tool/mod.rs
Registry
│
┌────────────────────────┼──────────────────────────┐
│ │ │
▼ ▼ ▼
name resolution session tool policy lifecycle logging
(resolve_tool_name (allow / deny, MCP (TOOL_LIFECYCLE
in jcode-tool-types alias history) start/done/error)
+ functions. prefix) │
│ │ │
└────────────┬───────────┘ │
▼ │
pre_tool hook gate ──► blocked ────────────────┤
│ │
▼ ▼
tool.execute(input, ToolContext) ──► ToolOutput
│ │
▼ ▼
post_tool observer / post_tool_feedback │
│ ▼
└──────────────────────────► context overflow guard
(90% of budget, 30% and
50k token single-output cap)
tool implementations (crates/jcode-app-core/src/tool/)
├── files read, write, edit, replace, apply_patch, ls, agentgrep
├── shell bash, bg
├── web websearch (ddg / bing / searxng / custom), webfetch
├── mcp mcp, mcp_search, mcp_call, mcp__SERVER__TOOL
├── agents batch, swarm, todo, conversation_search, session_search
├── knowledge memory, skill_manage, jcode_docs
├── desktop panel, side_panel, applet, user_responseThe tool that returns a Markdown response to a Desktop-capable client.
├── external browser, macos_computer_use, compile_remote, integration_tools
├── workspace gmail, calendar, open, invalid, maintainer_feedback
└── lifecycle selfdev, desktop_selfdev, debug_socket, ambient tools, codemode
shared contracts
├── jcode-tool-core Tool trait, ToolContext, intent / accept_large_output
├── jcode-tool-types ToolOutput, ToolImage, resolve_tool_name
└── jcode-config-types WebSearchConfig, CustomWebSearchConfig
Data Models
Tool definition (provider facing)
| Field | Type | Constraints | Description |
|---|---|---|---|
| name | string | not null, unique per registry | The registry key, which overrides the name the tool reports for itself. |
| description | string | not null, token-capped | Human-readable purpose of the tool. |
| input_schema | object | not null, must be an object schema | JSON Schema for the arguments, with intent injected and required. |
| defer_loading | bool | not null | Whether the provider may defer loading the tool definition. |
Tool input schema properties
| Property | Type | Required | Description |
|---|---|---|---|
| intent | string | yes | Short label shown in the UI explaining why the call is made. |
| accept_large_output | boolean | no | Opt in to the stated token cost of an otherwise withheld result. |
| tool-specific fields | varies | varies | Declared by each tool; unknown keys are ignored by the tool. |
Tool output
| Field | Type | Constraints | Description |
|---|---|---|---|
| output | string | not null | The text handed back to the model. |
| title | string | optional | Short label for the rendered result. |
| metadata | JSON value | optional | Tool-specific structured data. |
| images | list of ToolImage |
optional | Inline images produced by the tool. |
Tool image
| Field | Type | Constraints | Description |
|---|---|---|---|
| media_type | string | not null | MIME type of the image payload. |
| data | string | not null | Base64-encoded image bytes. |
| label | string | optional | Caption for the image. |
Tool context
| Field | Type | Constraints | Description |
|---|---|---|---|
| session_id | string | not null | The session the call belongs to. |
| message_id | string | not null | The assistant message that requested the call. |
| tool_call_id | string | not null | Unique call identity; subcalls derive a parent-scoped identity from it. |
| working_dir | path | optional | Base directory for relative paths. |
| stdin_request_tx | channel | optional | Channel used to ask the user for command input. |
| graceful_shutdown_signal | signal | optional | Raised when the session is shutting down. |
| execution_mode | enum | not null | AgentTurn or Direct. |
Tool execution mode
| Value | Description |
|---|---|
| AgentTurn | The call runs as part of a model turn. |
| Direct | The call runs outside a model turn, for example from the CLI. |
Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. configuration ([websearch.custom])
| Key | Type | Default | Description |
|---|---|---|---|
| endpoint | string | none | Absolute HTTP(S) URL of the search endpoint, without userinfo or a fragment. |
| method | GET or POST |
GET |
HTTP method used for the request. |
| query_param | string | q |
Literal key that receives the query. |
| count_param | string | none | Literal key that receives the result count; must differ from query_param. |
| params | map of string to string | empty | Static URL query parameters, applied to both methods. |
| body | JSON object | {} |
Static JSON body for POST requests. |
| headers | map of string to string | empty | Static header values. |
| header_env | map of string to string | empty | Header name to environment variable holding the complete header value. |
| results_pointer | JSON pointer | /results |
Pointer to the result array. |
| title_pointer | JSON pointer | /title |
Pointer to the title, relative to each result item. |
| url_pointer | JSON pointer | /url |
Pointer to the URL, relative to each result item. |
| snippet_pointer | JSON pointer | /snippet |
Pointer to the snippet, relative to each result item. |
Web search configuration ([websearch])
| Key | Type | Default | Description |
|---|---|---|---|
| engine | enum | duckduckgo |
Preferred local engine. |
| fallback_engines | list of enum | [bing] |
Engines tried in order after the preferred one. |
| prefer_native | bool | true |
Whether provider-side search replaces the local tool. |
| bing_api_key | string | none | API key for the primary Bing search. |
| bing_api_key_env | string | JCODE_BING_API_KEY |
Environment variable holding the Bing API key. |
| bing_market | string | en-US |
Bing market code. |
| searxng_url | string | none | Base URL of a SearXNG instance. |
| searxng_url_env | string | JCODE_SEARXNG_URL |
Environment variable holding the SearXNG base URL. |
API Contracts
This feature defines no HTTP API surface, so no api.yaml accompanies this document.
The contract below is the in-process tool contract, exposed as the Tool trait in jcode-tool-core.
| Operation | Signature | Purpose |
|---|---|---|
| Describe | Tool::name, Tool::description, Tool::parameters_schema |
The metadata the provider sees. |
| Convert | Tool::to_definition |
Produces the provider-facing ToolDefinition, with the shared properties injected. |
| Execute | Tool::execute(input: Value, ctx: ToolContext) -> Result<ToolOutput> |
Runs the tool and returns its result. |
| Identify | Tool::mcp_identity |
The original (server, tool) of an MCP proxy, independent of its registry alias. |
Error codes shared across tool calls:
| Condition | MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | Description |
|---|---|---|
| Unknown tool | Unknown tool: NAME. Did you mean: SUGGESTIONS? Available tools: LIST. |
The name resolved to no registered tool. |
| Tool not allowed | Tool 'NAME' is not allowed |
The session allow list excludes the tool. |
| Tool disabled | Tool 'NAME' is disabled |
The session deny list includes the tool. |
| Blocked by hook | Tool call blocked by pre_tool hook: REASON |
The user-configured pre-tool gate refused the call. |
| Product separation | Tool 'NAME' targets Jcode CLI, not Desktop. Use 'desktop_selfdev'. |
The tool does not apply to the current checkout. |
| Context exhausted | CONTEXT LIMIT REACHED: ... |
The result could not be returned because the window is full. |
| Output withheld | OUTPUT WITHHELD: this result is about N k tokens ... |
The result was too large and was not opted into. |
Sequences
Dispatching a tool call
sequenceDiagram
autonumber
participant A as Agent
participant R as Registry
participant P as Policy
participant H as pre_tool hook
participant T as Tool
participant G as Context guard
A->>R: execute(name, input, ctx)
R->>R: resolve_tool_name_for_session(name)
R->>P: allow / deny check
P-->>R: permitted
R->>H: run_pre_tool_gate
H-->>R: Allow or Block
R->>T: execute(input, ctx)
T-->>R: ToolOutput
R->>G: guard_context_overflow(output)
G-->>R: withheld, truncated, or unchanged
R-->>A: ToolOutput
Registering the tool surface
sequenceDiagram
autonumber
participant S as SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. start
participant R as Registry
participant B as Base tools
participant M as MCP manager
participant C as Schema cache
S->>R: new(provider)
R->>B: build base tool set (once per process)
B-->>R: stateless tools
R->>R: add per-session tools (batch, conversation_search)
R->>R: add codemode when enabled
R->>R: add integration_tools when discovery is enabled
R->>M: register_mcp_tools_for_dir
M->>C: load cached MCP schemas
C-->>M: cached tool definitions
M-->>R: advertise cached proxies
M->>M: connect servers in the background
M-->>R: per-server refresh and alias rebuild
Running a custom web search
sequenceDiagram
autonumber
participant M as Model
participant W as websearch tool
participant C as Config
participant E as Custom endpoint
M->>W: query, num_results, engine
W->>C: websearch config
C-->>W: engine order, custom settings
W->>E: GET or POST with query, count, headers
E-->>W: JSON body
W->>W: resolve results pointer and item pointers
W-->>M: numbered results
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Tool contract location | A Tool trait in jcode-tool-core with the output types in jcode-tool-types |
Keeps the data model usable by crates that must not depend on the app layer. |
| Alias table location | jcode-tool-types::resolve_tool_name |
The config layer can normalize tool names without depending on the tool subsystem. |
| Registry key as the provider name | The registry key overrides Tool::name |
MCP proxies are registered under mcp__server__tool while the tool still reports its raw name. |
| Schema injection in one place | ensure_intent_in_schema at definition conversion |
Every tool, including MCP proxies that never edit their own schema, asks for an intent. |
| Oversized-result policy | Refuse by default, truncate only on explicit opt-in | Truncating by default still charged the caller for a prefix that usually did not hold the answer. |
| Single-output cap | 30% of the budget and 50,000 tokens, whichever is smaller | 30% of a 1M-token window would otherwise permit a 300k-token single result. |
| Weak registry reference inside tools | WeakRegistry upgraded only for the duration of a call |
A tool that strongly owned its registry would create an Arc cycle. |
| Base tools cached process-wide | A OnceLock of stateless tools, cloned per session |
SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. startup must not pay per-tool construction cost. |
| Per-session compaction manager | Each registry clone gets a fresh CompactionManager |
Parallel subagents must not corrupt each other's message history accounting. |
| MCP advertise-early | Proxy tools registered from the on-disk schema cache before connections settle | The first tool snapshot then already contains MCP tools, so the prompt cache is not invalidated. |
| MCP alias rebuild is skipped when the catalog is unchanged | Identities and definitions are compared before rebuilding | Rebuilding about 400 aliases for each of about 13 connections was most of a reload storm's CPU. |
| MCP policy follows original identities | Alias history is retained for the life of the registry | An alias retired after a reconnect must not become callable again through its old name. |
| Deterministic definition ordering | Definitions are sorted by name | Stable ordering is required for provider prompt-cache hits. |
| Custom search never follows redirects | The request is issued with redirects disabled, including same-host ones | A redirect could forward a configured credential to another destination. |
| Custom search credentials from the environment | header_env maps header names to environment variables |
Credentials stay out of the config file and out of diagnostics. |
| Web search result cap | Default 8 results, maximum 20 | Keeps a search result from dominating a turn. |
| File writes are serialized per path | A per-path async lock around the read-modify-write | Two tools writing one file must not interleave a partial write. |
Tool inventory
Registered names, grouped by the surface that registers them.
| Tool name | Module | Registered when | Purpose |
|---|---|---|---|
| read | read.rs |
always | Read text, image, or PDF content from a file. |
| write | write.rs |
always | Create or overwrite a file. |
| edit | edit.rs |
always | Exact-match replacement edits, all or nothing. |
| replace | replace.rs |
always | Literal or regular-expression replacement across files. |
| apply_patch | apply_patch.rs |
always | Apply a Codex envelope or unified-diff patch. |
| ls | ls.rs |
always | List directory contents. |
| agentgrep | agentgrep.rs |
always | Search code and file names (grep, find, outline, trace). |
| bash | bash.rs |
always | Run a shell command. |
| bg | bg.rs |
always | Manage background tasks. |
| websearch | websearch.rs |
always | Search the web through a local engine. |
| webfetch | webfetch.rs |
always | Fetch a URL as text, Markdown, or HTML. |
| browser | browser.rs |
always | Drive a real browser. |
| open | open.rs |
always | Open or reveal a file, folder, or URL. |
| compile_remote | compile_remote.rs |
always | Compile in a remote sandbox with metered usage. |
| invalid | invalid.rs |
always | Report malformed tool usage. |
| maintainer_feedback | feedback.rs |
always | Send product feedback to the maintainer. |
| jcode_docs | jcode_docs.rs |
always | Search the bundled Jcode documentation. |
| todo | todo.rs |
always | Track structured work items and goal assessments. |
| session_search | session_search.rs |
always | Search past chat sessions. |
| memory | memory.rs |
always | Manage long-lived memory. |
| gmail | gmail.rs |
always | Read and send mail. |
| calendar | calendar.rs |
always | Manage Google calendars and events. |
| schedule | ambient.rs |
always | Schedule a wake-up for a session. |
| selfdev | selfdev/mod.rs |
always | Build, reload, and test the CLI in development. |
| desktop_selfdev | desktop_selfdev.rs |
always | Build, reload, test, and screenshot the Desktop app. |
| skill_manage | skill.rs |
always | Load, list, read, and reload skills. |
| swarm | communicate.rs |
always | Spawn and coordinate other agents. |
| panel | panel.rs |
always | Manage desktop panels. |
| side_panel | side_panel.rs |
always | Legacy panel management. |
| macos_computer_use | computer/mod.rs |
macOS only | Control the macOS desktop. |
| batch | batch.rs |
per session | Run independent tool calls in parallel. |
| conversation_search | conversation_search.rs |
per session | Search the current conversation history. |
| codemode | codemode.rs |
when [tools] codemode is enabled |
Run a JavaScript program that calls other tools. |
| integration_tools | discover.rs |
when integration discovery is enabled | Discover external integrations. |
| applet | applet.rs |
desktop UI capability enabled | Show an interactive native card. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | user_responseThe tool that returns a Markdown response to a Desktop-capable client..rs |
desktop UI capability enabled | Answer the user with inline Markdown. |
| mcp | mcp.rs |
MCP registration | Manage MCP servers. |
| mcp_search | mcp.rs |
MCP registration | Search the MCP tool catalog. |
| mcp_call | mcp.rs |
MCP registration | Call an MCP tool by name. |
| mcp__SERVER__TOOL | mcp.rs |
per connected server | Direct call surface for one server tool. |
| debug_socket | debug_socket.rs |
self-dev session | Access the debug socket. |
| end_ambient_cycle | ambient.rs |
ambient session | End the current ambient cycle. |
| schedule_ambient | ambient.rs |
ambient session | Schedule the next ambient cycle. |
| request_permission | ambient.rs |
ambient session | Ask the user for permission. |
| send_message | ambient.rs |
ambient session | Send a message to a channel. |
| client-defined | sdk.rs |
per session | Callback tools registered by a client. |
| initiative | goal.rs |
not registered | Durable initiatives, retained for a future re-enable. |
| patch | patch.rs |
not registered | Unified-diff tool, superseded by apply_patch. |
Risks and Unknowns
- The tool surface is wide, and the provider-facing schemas of 40-plus tools are paid on every request, so the token caps on descriptions are load-bearing.
- The
codemodetool re-enters the registry from inside a sandbox, so the recursion guard and the session policy inside the sandbox are the main correctness risk in that path. - The MCP alias scheme depends on sanitized names, so an alias cannot be split back into its
(server, tool)identity after the fact. - The custom web search engine trusts the configured endpoint; the request safeguards prevent credential forwarding but do not make an untrusted endpoint safe.
- The ambient, self-dev, and desktop tools have registration conditions spread across several call sites, so a new registration path can expose a tool in a context that should not have it.
- Several tools (browser, computer use, compile_remote, gmail, calendar) depend on external services whose availability and rate limits are not modelled anywhere in the tool layer.
Out of Scope
- The command-safety gate that blocks destructive shell commands, implemented in
crates/jcode-command-risk/andcrates/jcode-app-core/src/tool/bash_destructive_gate.rs, is a separate feature. - The CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox runtime, implemented in
crates/jcode-codemode/, is a separate feature. Only thecodemodetool that drives it is documented here. - The agent applet runtime, implemented in
crates/jcode-applet-types/, is a separate feature. Only theapplettool that mounts an applet is documented here. - The provider runtimes, the turn loop, the compaction engine, and the session store are documented by their own features.
- The MCP server implementations themselves, as opposed to the tool surface that connects to them.
Test Plan: Agent Tool Suite
Scope
This plan covers the tool runtime: the Tool trait and ToolContext in jcode-tool-core, the shared output model and alias table in jcode-tool-types, the Registry in crates/jcode-app-core/src/tool/mod.rs, and the tool implementations in crates/jcode-app-core/src/tool/.
The command-safety gate, the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox runtime, and the agent applet runtime are separate features and are not covered here, except where a tool test exercises the boundary.
The provider runtimes, the turn loop, the compaction engine, and the session store are covered by their own plans.
This plan was reverse-engineered from the existing test suite during an SDLC sync, so every file listed below already exists.
Known gaps in the current suite:
- The
lstool has no dedicated test file, and is only covered indirectly through registry-level tests. - The
writetool has no test that exercises the per-path file lock, so concurrent-write serialization is not proven. - The
webfetchtool has no test that exercises a response larger than the 5 MB cap. - The
patchtool is retained without being registered, but no test asserts its absence. - The
codemodetool is registered only when it is enabled in the configuration, but no test asserts that the disabled state leaves it unregistered.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | The registry publishes sorted definitions and injects the required intent property |
crates/jcode-app-core/src/tool/tests.rs |
Definitions are sorted by name and every object schema lists intent as required |
| TC-2 | Tool descriptions and parameter descriptions stay under the token cap | crates/jcode-app-core/src/tool/tests.rs |
No tool description and no parameter description exceeds the cap |
| TC-3 | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-facing schemas avoid constructs that strict-mode providers reject | crates/jcode-app-core/src/tool/tests.rs |
No array is typed as a union, no required entry lacks a matching property, and every built-in schema is sendable to every registered provider dialect |
| TC-4 | Alias resolution maps provider names, functions. prefixes, and PascalCase OAuthOpen Authorization names |
crates/jcode-app-core/src/tool/tests.rs, crates/jcode-tool-types/src/lib.rs |
Each alias resolves to its canonical registry name |
| TC-5 | Registry execution enforces the session allow and deny policy after alias resolution | crates/jcode-app-core/src/tool/tests.rs |
A denied or non-allowed tool fails with a policy error |
| TC-6 | The pre-tool hook can block a call and can allow a call | crates/jcode-app-core/src/tool/tests.rs |
A blocked call never reaches the tool and the reason is reported |
| TC-7 | The context guard withholds a huge result by default and truncates it on opt-in | crates/jcode-app-core/src/tool/tests.rs |
The default result is a refusal, the opted-in result is truncated with a notice |
| TC-8 | The context guard refuses when the context is exhausted and reports the real cost | crates/jcode-app-core/src/tool/tests.rs |
The refusal states the cost and the context level, and spends no more than it reports |
| TC-9 | An unknown tool name produces an error with the available tools and near-miss suggestions | crates/jcode-app-core/src/tool/tests.rs |
The error names the unknown tool, lists the available tools, and suggests the near match |
| TC-10 | MCP allow and deny lists cover dynamic server tools and the fixed surfaces | crates/jcode-app-core/src/tool/mod.rs (inline mcp_allow_list_tests) |
mcp in a list covers mcp__server__tool names, and a lookalike prefix does not match |
| TC-11 | MCP alias collisions, catalog refresh, and legacy deny precedence | crates/jcode-app-core/src/tool/tests/mcp_collision.rs |
A colliding name gets a distinct alias, a refresh drops the stale alias, and a legacy deny still blocks |
| TC-12 | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. SDKSoftware Development Kit tool selection, replacement, validation, and isolation | crates/jcode-app-core/src/tool/tests/sdk.rs |
A client-defined tool is selected, validated, and scoped to its own session |
| TC-13 | The read tool normalizes line ranges and advertises a provider-safe schema | crates/jcode-app-core/src/tool/read/tests.rs |
start_line/end_line and offset/limit are both supported, mixing them is rejected, and the schema has no union-typed array |
| TC-14 | The read tool converts images and refuses undecodable ones | crates/jcode-app-core/src/tool/read/tests.rs |
A BMP becomes a PNG image block, and an undecodable image is refused without an image block |
| TC-15 | The write tool summarizes diffs and previews file touches | crates/jcode-app-core/src/tool/write.rs (inline tests) |
The diff uses the 42- old / 42+ new form, truncates after 20 lines, and is empty for identical content |
| TC-16 | The edit tool applies every edit or none | crates/jcode-app-core/src/tool/edit.rs (inline tests) |
A partially matching edit set leaves the file unchanged |
| TC-17 | The replace tool applies every replacement or none | crates/jcode-app-core/src/tool/replace.rs (inline tests) |
A replacement that cannot apply to one file leaves every file unchanged |
| TC-18 | The bash tool advertises search guidance and handles optional arguments | crates/jcode-app-core/src/tool/bash_tests.rs |
The description points at agentgrep, omitted optionals take their defaults, and an invalid optional type is rejected |
| TC-19 | The bash tool forwards standard input and captures standard error | crates/jcode-app-core/src/tool/bash_tests.rs |
A command that reads one line receives it, and standard error appears in the output |
| TC-20 | The bash tool promotes a timed-out or reload-persistable command to the background | crates/jcode-app-core/src/tool/bash_tests.rs |
The call returns a background task identifier and the command keeps running |
| TC-21 | The bash tool terminates the whole process group on timeout | crates/jcode-app-core/src/tool/bash_tests.rs |
A descendant process of a timed-out command does not survive |
| TC-22 | Progress markers and heuristics are parsed into task progress | crates/jcode-app-core/src/tool/bash_tests/progress_parsing.rs |
Marker payloads, ratios, percentages, phases, and byte ratios are all classified correctly |
| TC-23 | The agentgrep builders scope searches to the requested paths | crates/jcode-app-core/src/tool/agentgrep_tests.rs |
Scope flags are included, a match-all glob is dropped, and an unscoped empty query is rejected |
| TC-24 | The agentgrep executor runs each mode and compacts large output | crates/jcode-app-core/src/tool/agentgrep_tests.rs |
Grep runs when the mode is omitted, a file field excludes sibling files, and long lines are compacted |
| TC-25 | The apply_patch tool parses and applies Codex and unified-diff patches | crates/jcode-app-core/src/tool/apply_patch_tests.rs |
Add, update, delete, move, multiple-chunk, and end-of-file patches apply correctly |
| TC-26 | The apply_patch tool refuses to delete a protected path | crates/jcode-app-core/src/tool/apply_patch_tests.rs |
The protected path survives while an ordinary file is still deleted |
| TC-27 | The batch tool normalizes malformed subcall shapes and keeps a generic schema | crates/jcode-app-core/src/tool/batch_tests.rs |
name, arguments, and flat parameters are all normalized, and the schema stays generic |
| TC-28 | The batch tool dispatches through a surviving registry clone and fails cleanly when the registry is gone | crates/jcode-app-core/src/tool/batch_tests.rs |
A surviving clone still executes, and a dropped registry produces a clean error |
| TC-29 | The custom web search builds requests and maps JSON pointers | crates/jcode-app-core/src/tool/websearch_tests.rs |
GET encodes the query, POST merges the body and the count, and nested and escaped pointers resolve |
| TC-30 | The custom web search validates configuration without exposing credentials | crates/jcode-app-core/src/tool/websearch_tests.rs |
A bad configuration fails with a message that contains no credential |
| TC-31 | The local search engines parse results and detect anti-bot pages | crates/jcode-app-core/src/tool/websearch_tests.rs |
Bing HTML, Bing API, DuckDuckGo, and SearXNG results parse, and a captured anti-bot fixture is detected |
| TC-32 | The webfetch extraction satisfies the corpus invariants | crates/jcode-app-core/src/tool/webfetch_corpus_tests.rs |
The extracted text drops tags, keeps code blocks intact, and matches the corpus expectations |
| TC-33 | The MCP management and deferred search tools behave as specified | crates/jcode-app-core/src/tool/mcp_tests.rs |
Listing shows a disabled server, an unknown action fails, and the search results fit an adaptive budget |
| TC-34 | The session search ranks, filters, groups, and locates matches | crates/jcode-app-core/src/tool/session_search_tests.rs |
Phrase and token matches are ranked, the current session is excluded by default, and locators are stable |
| TC-35 | The todo tool tracks structured items and goal assessments | crates/jcode-app-core/src/tool/todo.rs (inline tests) |
Item status, grouping, confidence, and the goal assessment fields round-trip |
| TC-36 | The initiative tool round-trips and keeps its schema stable | crates/jcode-app-core/src/tool/goal_tests.rs |
An initiative can be created and resumed, and the schema omits the public enums |
| TC-37 | The memory tool stores and queries long-lived memory | crates/jcode-app-core/src/tool/memory.rs (inline tests) |
A remembered entry is recalled with its category and scope |
| TC-38 | The skill tool loads, lists, reads, and reloads skills | crates/jcode-app-core/src/tool/skill.rs (inline tests) |
Each action returns the expected result and an unknown action is rejected |
| TC-39 | A write that lands on the active config reports what changed | crates/jcode-app-core/src/tool/config_edit_notice_tests.rs |
The notice names the changed settings, says when a restart is required, and reports a broken config loudly |
| TC-40 | The open tool parses and resolves its target | crates/jcode-app-core/src/tool/open_tests.rs |
A file URL becomes a local path, a missing path is rejected, and a removed parameter is rejected |
| TC-41 | The panel and side_panel tools manage their lifecycle | crates/jcode-app-core/src/tool/panel_tests.rs, crates/jcode-app-core/src/tool/side_panel_tests.rs |
A panel registers, is listed, and validates its inputs |
| TC-42 | The applet tool requires the desktop capability and validates its shapes | crates/jcode-app-core/src/tool/applet_tests.rs |
The call is refused without the capability, and the documented shapes validate |
| TC-43 | The codemode script composes registry tools and respects the session policy | crates/jcode-app-core/src/tool/codemode_tests.rs |
A script calls registry tools, a policy inside the script is enforced, and an uncaught error becomes a tool error |
| TC-44 | The swarm tool runs plans and guards the driver | crates/jcode-app-core/src/tool/communicate_tests.rs |
The driver guard blocks a second live driver, releases on drop, and the summary reports failed nodes |
| TC-45 | The swarm tool assigns tasks and spawns workers | crates/jcode-app-core/src/tool/communicate_tests/assignment.rs |
The next runnable task is assigned, slots are topped up, and a fresh spawn can be preferred |
| TC-46 | The swarm tool detects a credential-failure wave | crates/jcode-app-core/src/tool/communicate_tests/credential_failures.rs |
A wave needs at least two recent auth failures and ignores stale or foreign members |
| TC-47 | The swarm tool input format and member rendering | crates/jcode-app-core/src/tool/communicate_tests/input_format.rs |
The delivery and share flags are accepted and duplicate member names are disambiguated |
| TC-48 | The ambient tools parse their inputs and build the permission context | crates/jcode-app-core/src/tool/ambient/tests.rs |
String numbers and booleans are coerced, the schedule target defaults correctly, and a non-ambient session is rejected |
| TC-49 | The compile_remote tool gates access and bounds responses | crates/jcode-app-core/src/tool/compile_remote/tests.rs |
Signed-out, subscription-required, and ready states are distinguished, and the response is bounded |
| TC-50 | The macOS computer-use tool validates actions and its schema | crates/jcode-app-core/src/tool/computer/tests.rs |
An unknown action is rejected, a move needs coordinates, a dry run does not mutate, and the schema declares every field |
| TC-51 | The macOS computer-use tool covers the platform surface | crates/jcode-app-core/src/tool/computer/coverage_tests.rs |
Text editing, observation, input, accessibility, windows, apps, clipboard, and scripting are all reachable |
| TC-52 | The self-dev tool queues builds and saves the reload context | crates/jcode-app-core/src/tool/selfdev/tests.rs |
The build lock is released on drop, the request history is archived, and the reload context round-trips |
| TC-53 | The desktop self-dev tool builds, reloads, and screenshots safely | crates/jcode-app-core/src/tool/desktop_selfdev_tests.rs |
Every action refuses a non-desktop context, the reload is read-only, and a symlinked screenshot destination is rejected |
| TC-54 | The browser tool maps requests and exposes the advanced fields | crates/jcode-app-core/src/tool/browser_tests.rs |
A snapshot maps to an annotated content request, an eval maps to a script, and the advanced fields are in the schema |
| TC-55 | The browser fast path observes, decides, and hands back | crates/jcode-app-core/src/tool/browser_fast_tests.rs |
The loop observes after each action, an uncertain decision never executes, and a stall returns control |
| TC-56 | The browser session reuses one daemon across calls | crates/jcode-app-core/src/tool/browser_session_tests.rs |
Five calls share one daemon and concurrent calls start only one |
| TC-57 | The browser user-browser surfaces every window | crates/jcode-app-core/src/tool/browser_user_browser_tests.rs |
A closed agent window is restarted and retried once, and an explicit tab is not retried |
| TC-58 | The integration catalog is searched and filtered | crates/jcode-app-core/src/tool/discover.rs (inline tests) |
Search, details, select, and suggest each return their expected shape |
| TC-59 | The Gmail and calendar tools parse their inputs and render results | crates/jcode-app-core/src/tool/gmail.rs, crates/jcode-app-core/src/tool/calendar.rs (inline tests) |
Each action parses and its result renders |
| TC-60 | The shared intent and escape-hatch injection applies to every object schema | crates/jcode-tool-core/src/lib.rs |
intent is added and required, the escape hatch is optional, and a tool's own declaration survives |
| TC-61 | The shared output model and alias table behave as specified | crates/jcode-tool-types/src/lib.rs |
The output builders set their fields and the alias table maps every documented alias |
| TC-62 | Background taskServer-side job running independently of the current turn. management, in-flight tracking, and per-path locking | crates/jcode-app-core/src/tool/bg.rs, crates/jcode-app-core/src/tool/inflight.rs, crates/jcode-app-core/src/tool/file_lock.rs (inline tests) |
A task is listed and cancelled, an in-flight call is marked and cleared, and a path lock is exclusive |
| TC-63 | The conversation history search filters and formats | crates/jcode-app-core/src/tool/conversation_search.rs (inline tests) |
A query returns the matching turns and an empty history returns no result rather than panicking |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-64 | The swarm tool drives a real agent session end to end | crates/jcode-app-core/src/tool/communicate_tests/end_to_end.rs |
Members are listed and awaited, a background await returns immediately, a spawn reports back to the spawner, and a direct message is routed as a direct message |
| TC-65 | The browser live handoff completes local navigation and search | crates/jcode-app-core/src/tool/browser_fast_live_tests.rs, against the local fixture server |
The handoff navigates, searches, and resumes after a requested script, and a sensitive fixture is handed back without actions |
| TC-66 | The browser live acceptance check for the reported defect passes | crates/jcode-app-core/src/tool/browser_live_1743_tests.rs, against a live browser |
Every acceptance item reports success |
| TC-67 | A browser observation timeout retains the last connection error and dispatches nothing | crates/jcode-app-core/src/tool/browser_fast_tests/reconnect_timeout.rs |
The result is a hand-back whose reason carries the last connection error, and the transport receives no request |
| TC-68 | The custom web search exchanges a real request with a local HTTP server | crates/jcode-app-core/src/tool/websearch_tests.rs, with a local HTTP server |
The query and count arrive as configured, a redirect is not followed, and the transport and JSON errors hide the URL and its secrets |
| TC-69 | Remote MCP management connects, discovers, calls, and disconnects over real HTTP | crates/jcode-app-core/src/tool/mcp_remote_management_tests.rs, with a local HTTP server |
The transport and static headers are preserved, the call reaches the server, and the status output carries no secret |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-70 | The ambient end-cycle tool runs inside a full agent turn | tests/e2e/ambient.rs: a mock provider queues an end_ambient_cycle tool call, the agent runs, the provider is called again |
The turn completes and the cycle result holds the summary and counters the tool reported |
| TC-71 | The ambient request-permission tool runs inside a full agent turn | tests/e2e/ambient.rs: a mock provider queues a request_permission tool call |
The permission request reaches the caller with the action, the description, the rationale, and the urgency |
| TC-72 | The ambient schedule tool runs inside a full agent turn | tests/e2e/ambient.rs: a mock provider queues a schedule tool call |
The wake-up is scheduled with the requested target and priority |
| TC-73 | Tool names are classified into permission tiers | tests/e2e/safety.rs: classify a list of tool names |
Read, glob, grep, memory, and the todo tools are auto-allowed, while bash, edit, and write require permission, and the classification is case-insensitive |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-74 | The read tool is given both range styles, or a zero start line | The call is rejected with a message naming the two styles, and a zero start_line is rejected as one-based |
| TC-75 | The read tool is given a path that does not exist | The error names the missing file and suggests the closest existing path when one is close enough |
| TC-76 | The write tool is given a path whose parent directory does not exist | The parent directories are created and the file is written |
| TC-77 | The apply_patch tool is asked to delete a protected path | The deletion is refused and the file is untouched, while an ordinary file is still deleted |
| TC-78 | The bash tool is given a timeout of 5000 ms or less | The timeout message spells out the seconds and states that the parameter is in milliseconds |
| TC-79 | Every web search engine returns nothing | The tool returns a no-results message that names the SearXNG workaround instead of failing silently |
| TC-80 | A custom search header names an environment variable that is missing or empty | The call fails before any network access and the message contains no credential |
| TC-81 | The webfetch tool is given a URL that is not HTTP or HTTPS | The call is rejected before any request is made |
| TC-82 | An MCP tool is denied under its legacy name but called through the deferred surface | The dispatch is refused, and a deny on either spelling wins |
| TC-83 | Two MCP servers expose a tool with the same name | The two tools get distinct aliases and each alias maps back to its own server |
| TC-84 | The batch tool is given more than ten calls, or is asked to call itself | The oversized batch is rejected, and a function-namespaced or self-referential batch is refused |
| TC-85 | A codemode script calls the codemode tool or the batch tool | The call is refused, so a script cannot recurse into itself or fan out through the batch |
| TC-86 | The initiative tool is absent from the registry | crates/jcode-app-core/src/tool/tests.rs |
| TC-87 | The registry is built without the desktop UI capability | The applet tool and the user_responseThe tool that returns a Markdown response to a Desktop-capable client. tool are absent, and a call to either name fails as an unknown tool |
| TC-88 | The request_permission tool is called from a session that is not an ambient session | The call is rejected |
| TC-89 | The compile_remote tool is pointed at an insecure or credential-bearing endpoint | The endpoint is rejected before any upload happens |
| TC-90 | The browser fast path is handed a sensitive page | The page never reaches the transport and the result is a hand-back |
| TC-91 | A batch subcall returns an image while a sibling subcall fails (crates/jcode-app-core/src/tool/batch_tests.rs) |
The images are preserved in input order despite the failure |
| TC-92 | Integration discovery is disabled | The integration_tools tool is never registered and no discovery endpoint is contacted |
Test Infrastructure
- Tests are in-crate
#[cfg(test)]modules, with the larger suites mounted with#[path = "..."] mod tests;so that a file stays inside the CIContinuous Integration test-size budget. - The tool registry is built with
Registry::new(provider)in the tests, and aToolContextis built per test with the session, message, tool-call, and working-directory fields the tool needs. crates/jcode-app-core/src/tool/testdata/holds the captured DuckDuckGo fixtures:ddg_results.htmlandddg_anomaly.html.- The browser suites use a mock browser and a mock transport so that no real browser is required; the live suites need a browser daemon and a local fixture server and are skipped otherwise.
- The custom web search and the remote MCP suites run a local HTTP server on a loopback port.
- The webfetch corpus is a directory of captured pages, and the corpus test is skipped when the directory is absent.
- The macOS computer-use suites need a macOS host with accessibility permissions and are skipped elsewhere.
- The ambient end-to-end tests use the mock provider in
tests/e2e/mock_provider.rsto queue a tool call and then a final answer. - The per-path file lock and the in-flight registry are exercised through their own modules, so no external service is needed.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall expose a registry that registers, unregisters, lists, and executes tools by name, and that publishes provider-facing tool definitions. | TC-1, TC-27, TC-28, TC-63 |
| FR-2MustThe system shall inject a shared `intent` property into every object-shaped tool schema and mark it required, so every call carries a human-readable reason. | TC-1, TC-60 |
| FR-3MustThe system shall advertise an optional `accept_large_output` property on every object-shaped tool schema and honor it when the caller sets it. | TC-7, TC-27, TC-60 |
| FR-4MustThe system shall resolve provider and namespace tool-name aliases (including `functions.` prefixes, Claude Code names, and PascalCase OAuthOpen Authorization names) to canonical registry names before dispatch. | TC-4, TC-27 |
| FR-5MustThe system shall enforce the per-session tool allow list and deny list at execution time, including for MCP tools addressed through aliases retired after a reconnect. | TC-5, TC-10, TC-11, TC-12, TC-82 |
| FR-6MustThe system shall reject a call to an unknown tool with an error that lists the available tools and suggests near-miss names. | TC-9 |
| FR-7MustThe system shall withhold a tool result that would exceed the context budget, and shall only return a truncated result when the caller explicitly opted in. | TC-7, TC-8 |
| FR-8MustThe system shall read files as text, image, or PDF, and shall report binary files without attempting to decode them. | TC-13, TC-14, TC-74, TC-75 |
| FR-9MustThe system shall write files, creating parent directories as needed, and shall report a diff summary plus a unified diff. | TC-15, TC-39, TC-76 |
| FR-10MustThe system shall apply exact-match edits so that all edits in a call apply or none do. | TC-16 |
| FR-11MustThe system shall apply multi-file patches in both the Codex envelope format and the unified-diff format, including file creation, deletion, and moves. | TC-25, TC-26, TC-77 |
| FR-12MustThe system shall perform literal or regular-expression replacement across files, applying every replacement or none. | TC-17 |
| FR-13MustThe system shall list directory contents on request. | Not covered. The ls tool has no dedicated test file. |
| FR-14MustThe system shall search code and file names, supporting grep, find, outline, and trace modes. | TC-23, TC-24 |
| FR-15MustThe system shall run shell commands, capturing standard output and standard error separately and reporting exit status. | TC-18, TC-19 |
| FR-16MustThe system shall forward standard input to a running command when the command reads from it. | TC-19 |
| FR-17MustThe system shall promote a command that exceeds the foreground timeout into a background task instead of discarding it. | TC-20, TC-78 |
| FR-18MustThe system shall parse progress markers and progress heuristics from command output and surface them as task progress. | TC-22, TC-31, TC-79 |
| FR-19MustThe system shall terminate the whole process group of a timed-out command so that no descendant survives. | TC-29, TC-30, TC-68, TC-80 |
| FR-20MustThe system shall search the web through DuckDuckGo, Bing, SearXNG, or a custom engine, and shall try the configured fallback engines in order. | TC-31, TC-79 |
| FR-21MustThe system shall call a custom HTTP JSON search endpoint configured under `[websearch.custom]`, mapping the JSON response into title, URL, and snippet results. | TC-29, TC-32, TC-81 |
| FR-22MustThe system shall keep custom-search credentials out of diagnostics and shall not forward credentials across redirects. | TC-30, TC-68, TC-80 |
| FR-23MustThe system shall fetch a URL and return it as text, Markdown, or HTML, subject to a response size cap and an output size cap. | TC-32, TC-81 |
| FR-24MustThe system shall manage MCP servers through the `mcp` tool, supporting listing, connecting, disconnecting, reloading, status, and logout. | TC-33, TC-69 |
| FR-25MustThe system shall expose the MCP tool catalog through a deferred search tool and a deferred call tool, so that a model can find and invoke a server tool by name. | TC-33, TC-82 |
| FR-26MustThe system shall register connected MCP server tools as callable tools under a namespaced alias, resolving alias collisions deterministically. | TC-11, TC-83 |
| FR-27MustThe system shall cache MCP tool schemas on disk so that a new session can advertise the MCP surface before the connections settle. | TC-11 |
| FR-28MustThe system shall run independent tool calls in parallel through the `batch` tool, and shall accept the common malformed shapes models produce. | TC-27, TC-84 |
| FR-29MustThe system shall coordinate multiple agents through the `swarm` tool, covering spawn, assignment, run plans, awaiting, status, and messaging. | TC-44, TC-45, TC-46, TC-47, TC-64 |
| FR-30MustThe system shall track structured work items through the `todo` tool, including status, grouping, confidence, and goal-level assessment fields. | TC-35, TC-36 |
| FR-31MustThe system shall manage background tasks through the `bg` tool, including listing, status, output, tail, cancel, cleanup, and waiting. | TC-62 |
| FR-32MustThe system shall persist and query long-lived memory through the `memory` tool, supporting remember, recall, search, list, forget, tag, link, and related actions. | TC-37 |
| FR-33MustThe system shall search past chat sessions through the `session_search` tool and in-conversation history through the `conversation_search` tool, with filters and grouping. | TC-34, TC-63 |
| FR-34MustThe system shall load, list, read, and reload skills through the `skill_manage` tool. | TC-38 |
| FR-35MustThe system shall search the bundled Jcode documentation through the `jcode_docs` tool. | TC-1, TC-58 |
| FR-36MustThe system shall record a structured lifecycle event for every tool call, covering the requested name, the resolved name, the status, the latency, the output size, and the touched paths. | TC-1, TC-9, TC-5, TC-6 |
| FR-37MustThe system shall let a user-configured pre-tool hook block a call, and shall let post-tool observers and post-tool feedback hooks observe the outcome and append feedback to the result. | TC-6 |
| FR-38ShouldThe system shall open desktop panels from Markdown or Markdown/PDF files and manage their lifecycle through the `panel` tool, and shall keep the legacy `side_panel` tool working. | TC-41 |
| FR-39ShouldThe system shall render an interactive native card through the `applet` tool and an inline Markdown answer through the `user_responseThe tool that returns a Markdown response to a Desktop-capable client.` tool, and shall expose both only when the desktop UI capability is enabled. | TC-42, TC-87 |
| FR-40ShouldThe system shall drive a real browser through the `browser` tool, covering navigation, content extraction, scripted evaluation, and interaction. | TC-54, TC-55, TC-56, TC-57, TC-65, TC-66, TC-67, TC-90 |
| FR-41ShouldThe system shall compile source in a remote sandbox through the `compile_remote` tool, reserving and settling metered usage against the subscription. | TC-49, TC-89 |
| FR-42ShouldThe system shall run a JavaScript program that calls other tools through the `codemode` tool, and shall register that tool only when it is enabled in the configuration. | TC-43, TC-85 |
| FR-43ShouldThe system shall discover external integrations through the `integration_tools` tool, and shall register that tool only when integration discovery is enabled. | TC-58, TC-92 |
| FR-44ShouldThe system shall read and send mail through the `gmail` tool and manage calendars through the `calendar` tool. | TC-59 |
| FR-45ShouldThe system shall open or reveal a file, a folder, or a URL for the user through the `open` tool. | TC-40 |
| FR-46ShouldThe system shall build, reload, test, and inspect the project under development through the `selfdev`, `desktop_selfdev`, and `debug_socket` tools. | TC-52, TC-53 |
| FR-47ShouldThe system shall register the ambient-mode tools (`end_ambient_cycle`, `schedule_ambient`, `request_permission`, `send_message`, and `schedule`) only for ambient sessions. | TC-48, TC-88, TC-70, TC-71, TC-72 |
| FR-48ShouldThe system shall control the macOS desktop through the `macos_computer_use` tool on macOS hosts only. | TC-50, TC-51 |
| FR-49MayThe system shall let a client register session-scoped custom tool callbacks that the registry dispatches to instead of a built-in tool. | TC-12 |
| FR-50MayThe system shall provide the `maintainer_feedback` and `invalid` tools for product feedback and for reporting malformed tool usage. | TC-58, TC-73 |
| FR-51MayThe system shall keep the `initiative` and `patch` tool implementations available but unregistered, so they can be restored without a migration. | TC-86 |
| NFR-1MustThe system shall build the stateless base tool set once per process and reuse it across sessions, so session startup does not pay per-tool construction cost. | TC-1 |
| NFR-2MustA single tool result shall not exceed the smaller of 30% of the context budget and 50,000 tokens, so no one result can dominate a context window. | TC-7, TC-8 |
| NFR-3MustThe system shall resolve relative tool paths against the session working directory, and shall not let one tool write outside the paths its input names. | TC-13, TC-40, TC-48 |
| NFR-4MustThe system shall never write a configured credential, endpoint URL, or request body into a log line, an error message, or a hook payload. | TC-30, TC-68, TC-80, TC-89 |
| NFR-5MustThe system shall serialize concurrent writes to the same file so that two tools cannot interleave a partial write. | Not covered. The per-path file lock has a unit test but no concurrent-write test. |
| NFR-6ShouldThe system shall skip the MCP alias rebuild when a reconnected server's tool catalog is unchanged, so a reload storm does not scale with the number of servers. | TC-11 |
| NFR-7ShouldThe system shall publish tool definitions in a stable sorted order, so provider prompt caches are not invalidated by registry ordering. | TC-1 |
| NFR-8ShouldThe system shall keep every tool description and every tool parameter description under a documented token cap, because the text rides on every request. | TC-2 |
| NFR-9ShouldThe system shall not emit tool schemas that strict-mode providers reject, such as an array of a union type or a `required` entry with no matching property. | TC-3, TC-13 |
| NFR-10ShouldThe system shall emit one structured lifecycle event per tool call, so an operator can reconstruct which tool ran, with which arguments, and with what outcome. | TC-1, TC-9 |
| NFR-11ShouldA failing tool shall return a diagnostic error to the caller rather than terminating the turn. | TC-43 |
| NFR-12MayThe system shall keep platform-specific tools behind a target guard, so the same registry builds on Linux, macOS, and Windows. | TC-50, TC-87 |
requirements
- None. The feature is already implemented; any future change should be tracked as a new issue.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Desktop Companion and Voice
Overview
The harness server and the agent runtime must never own a screen, a keyboard, a microphone or a lid.
Every desktop effect that the agent needs (opening a URL, revealing a file, spawning a terminal window, keeping the machine awake, push-to-talk dictation) is brokered to a per-login companion process that runs inside the user's graphical session and answers over a local socket.
A headless or remote server simply has no companion, so the caller falls back to its own local behavior instead of popping a window on the wrong machine.
This feature documents the companion, the desktop-open helpers, the voice subsystem, the jcode companion and jcode dictate CLI surfaces, and the /dictate, /dictation and /voice TUITerminal User Interface commands.
It was reverse-engineered from the existing codebase during an SDLC sync, so it describes already-implemented functionality rather than planned work.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End user on a desktop | Agent actions open windows, files and terminals in the session they are actually looking at |
| Remote or headless operator | The server never touches the wrong machine's screen, and every desktop effect degrades to a local fallback |
| Agent runtime and harness | Desktop effects are requested over one small, versioned, local protocol instead of being embedded in the agent loop |
| Voice user | Push-to-talk dictation reaches the focused jcode session, with a visible recording indicator |
| Platform maintainer | Lid-close and power settings are always restored, even after a crash |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall provide a per-login companion process (`jcode companion`) that runs inside the user's graphical session and owns every desktop-only effect: opening URLs and files, revealing paths, spawning terminal windows, the lid-close override, and the global push-to-talk listener. | Must | The system shall provide a per-login companion process (jcode companion) that runs inside the user's graphical session and owns every desktop-only effect: opening URLs and files, revealing paths, spawning terminal windows, the lid-close override, and the global push-to-talk listener. |
| FR-2MustThe harness server and the agent runtime shall request desktop effects over a local socket using one JSON request per line answered by one JSON response per line, and shall never open a screen, a keyboard, a microphone or a lid themselves. | Must | The harness server and the agent runtime shall request desktop effects over a local socket using one JSON request per line answered by one JSON response per line, and shall never open a screen, a keyboard, a microphone or a lid themselves. |
| FR-3MustThe companion shall answer a status request with its version, its protocol version, and the list of capabilities it provides on the current platform. | Must | The companion shall answer a status request with its version, its protocol version, and the list of capabilities it provides on the current platform. |
| FR-4MustThe companion shall open a URL or a local path with the desktop's default application, and shall report which opener ran. | Must | The companion shall open a URL or a local path with the desktop's default application, and shall report which opener ran. |
| FR-5MustThe companion shall show a local path in the file manager, selecting the file when the platform supports it. | Must | The companion shall show a local path in the file manager, selecting the file when the platform supports it. |
| FR-6MustThe companion shall run a program in a new terminal window in the user's session, preserving the program, the arguments, the working directory, the title, the kind, the session id, and the environment metadata. | Must | The companion shall run a program in a new terminal window in the user's session, preserving the program, the arguments, the working directory, the title, the kind, the session id, and the environment metadata. |
| FR-7MustA caller shall fall back to its own local behavior when no companion answers, so the system still works on a machine with no graphical session. | Must | A caller shall fall back to its own local behavior when no companion answers, so the system still works on a machine with no graphical session. |
| FR-8MustThe companion shall engage the lid-close override while a session is working, and shall release it when the work stops, when the activity lease expires, or when the companion exits. | Must | The companion shall engage the lid-close override while a session is working, and shall release it when the work stops, when the activity lease expires, or when the companion exits. |
| FR-9MustThe companion shall write the original power settings to a recovery journal before changing them, and shall restore them when the owning process dies, so a killed process cannot leave the machine unable to sleep. | Must | The companion shall write the original power settings to a recovery journal before changing them, and shall restore them when the owning process dies, so a killed process cannot leave the machine unable to sleep. |
| FR-10MustThe companion shall provide a global push-to-talk listener on Linux that records only while a jcode CLI session is focused, shows a visible recording indicator, and sends the finished transcript to that session. | Must | The companion shall provide a global push-to-talk listener on Linux that records only while a jcode CLI session is focused, shows a visible recording indicator, and sends the finished transcript to that session. |
| FR-11MustThe global push-to-talk listener shall be opt-in through the configured keyboard event devices, and shall be disabled at runtime by a command-line flag or by an environment variable. | Must | The global push-to-talk listener shall be opt-in through the configured keyboard event devices, and shall be disabled at runtime by a command-line flag or by an environment variable. |
| FR-12MustThe companion shall refuse to open the microphone when no visible recording indicator can be shown. | Must | The companion shall refuse to open the microphone when no visible recording indicator can be shown. |
| FR-13ShouldThe system shall run the configured dictation command and apply the resulting transcript according to the configured mode, either sending it to the focused jcode client or typing it into the focused application. | Should | The system shall run the configured dictation command and apply the resulting transcript according to the configured mode, either sending it to the focused jcode client or typing it into the focused application. |
| FR-14ShouldThe voice subsystem shall transcribe captured audio with the Nari streaming API, sourcing the audio from either native capture or an external recorder process. | Should | The voice subsystem shall transcribe captured audio with the Nari streaming API, sourcing the audio from either native capture or an external recorder process. |
| FR-15ShouldThe companion shall refresh an installed browser bridge on a periodic schedule, off the browser tool's hot path. | Should | The companion shall refresh an installed browser bridge on a periodic schedule, off the browser tool's hot path. |
| FR-16MayOpening a URL on the niri compositor shall raise the browser window that handled it. | May | Opening a URL on the niri compositor shall raise the browser window that handled it. |
| FR-17MayThe global push-to-talk listener shall share a routing registry with Jcode Desktop, so the most recently focused registrant wins a press. | May | The global push-to-talk listener shall share a routing registry with Jcode Desktop, so the most recently focused registrant wins a press. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustA companion request shall be answered within the caller's timeout, and a liveness probe shall be answered in under 500 ms. | Must | Performance | A companion request shall be answered within the caller's timeout, and a liveness probe shall be answered in under 500 ms. |
| NFR-2MustThe microphone shall be opened only after an explicit user press, and the capture shall be released on key release, on cancel, on drop, on device failure, on the byte cap, and at the five-minute cap. | Must | Privacy | The microphone shall be opened only after an explicit user press, and the capture shall be released on key release, on cancel, on drop, on device failure, on the byte cap, and at the five-minute cap. |
| NFR-3MustNo audio, transcript, credential, provider error, or response body shall be written to the log, to an error message, or to a notification. | Must | Privacy | No audio, transcript, credential, provider error, or response body shall be written to the log, to an error message, or to a notification. |
| NFR-4MustThe companion socket shall live in the per-user runtime directory, a request line shall be capped at 64 KiB, and a malformed request shall be answered with an error instead of taking the server down. | Must | Security | The companion socket shall live in the per-user runtime directory, a request line shall be capped at 64 KiB, and a malformed request shall be answered with an error instead of taking the server down. |
| NFR-5MustThe power-activity lease shall expire 30 seconds after the last renewal and the override shall be released at the next five-second reconcile tick, and a stale lid override left by a dead owner shall be repaired by the next companion that starts. | Must | Reliability | The power-activity lease shall expire 30 seconds after the last renewal and the override shall be released at the next five-second reconcile tick, and a stale lid override left by a dead owner shall be repaired by the next companion that starts. |
| NFR-6ShouldThe system shall check the session lock state before every press and before delivery, and shall refuse to record while the session is locked. | Should | Privacy | The system shall check the session lock state before every press and before delivery, and shall refuse to record while the session is locked. |
| NFR-7ShouldThe system shall keep working with no companion installed, and every voice failure shall map to one specific short user-facing message. | Should | Availability | The system shall keep working with no companion installed, and every voice failure shall map to one specific short user-facing message. |
| NFR-8ShouldThe companion shall run on Linux, macOS, and Windows, and the reported capability list shall match what the current platform can do. | Should | Portability | The companion shall run on Linux, macOS, and Windows, and the reported capability list shall match what the current platform can do. |
Constraints
- The companion socket path comes from
JCODE_COMPANION_SOCKET, elsejcode-companion.sockin the runtime directory. - The protocol version is
1, and it is bumped when a request's meaning changes incompatibly. - Global voice is Linux-only, and the lid override is macOS and Windows only.
- The macOS lid override needs a
sudoersrule forpmset, runssudo -nso it never prompts, and is skipped with a one-time hint when the rule is missing. - Linux blocks the lid through
systemd-inhibit, which needs no persistent setting change. - Voice transcription needs a Nari API key, supplied through
NARI_API_KEYor~/.config/jcode/nari.env. - The global voice device list comes from
[dictation] global_devicesin~/.jcode/config.toml. docs/MESSAGE_VOICE.mdwas checked and does not apply, it governs how jcode phrases user-facing messages rather than how voice input works.docs/REMOTE_HANDOFF.mdwas checked and does not apply, it is an unimplemented design sketch for moving sessions between hosts.
Acceptance Criteria
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
-
FR-1MustThe system shall provide a per-login companion process (`jcode companion`) that runs inside the user's graphical session and owns every desktop-only effect: opening URLs and files, revealing paths, spawning terminal windows, the lid-close override, and the global push-to-talk listener.
gherkin @FR-1MustThe system shall provide a per-login companion process (`jcode companion`) that runs inside the user's graphical session and owns every desktop-only effect: opening URLs and files, revealing paths, spawning terminal windows, the lid-close override, and the global push-to-talk listener. Scenario: Companion owns the desktop effects Given a user logged in to a graphical session When the companion starts Then it binds its local socket and advertises the open, reveal and spawn-terminal capabilities -
FR-2MustThe harness server and the agent runtime shall request desktop effects over a local socket using one JSON request per line answered by one JSON response per line, and shall never open a screen, a keyboard, a microphone or a lid themselves.
gherkin @FR-2MustThe harness server and the agent runtime shall request desktop effects over a local socket using one JSON request per line answered by one JSON response per line, and shall never open a screen, a keyboard, a microphone or a lid themselves. Scenario: Desktop effect travels over the socket Given a server with no screen of its own When it asks the companion to open a URL Then the request is one JSON line and the reply is one JSON line -
FR-3MustThe companion shall answer a status request with its version, its protocol version, and the list of capabilities it provides on the current platform.
gherkin @FR-3MustThe companion shall answer a status request with its version, its protocol version, and the list of capabilities it provides on the current platform. Scenario: Status reports version, protocol and capabilities Given a running companion When a status request is sent Then the reply carries the companion version, protocol version 1, and a capability list -
FR-4MustThe companion shall open a URL or a local path with the desktop's default application, and shall report which opener ran.
gherkin @FR-4MustThe companion shall open a URL or a local path with the desktop's default application, and shall report which opener ran. Scenario: Opening a URL uses the desktop's own tool Given a running companion on a desktop When an open request carries a URL Then the reply names the opener that ran -
FR-5MustThe companion shall show a local path in the file manager, selecting the file when the platform supports it.
gherkin @FR-5MustThe companion shall show a local path in the file manager, selecting the file when the platform supports it. Scenario: Revealing a path opens the file manager Given a running companion and an existing file When a reveal request carries that path Then the reply names the backend that showed the path -
FR-6MustThe companion shall run a program in a new terminal window in the user's session, preserving the program, the arguments, the working directory, the title, the kind, the session id, and the environment metadata.
gherkin @FR-6MustThe companion shall run a program in a new terminal window in the user's session, preserving the program, the arguments, the working directory, the title, the kind, the session id, and the environment metadata. Scenario: Spawning a terminal keeps the caller's context Given a running companion When a spawn-terminal request carries a program, arguments, working directory, title and session id Then a new terminal window runs in the user's session with that context -
FR-7MustA caller shall fall back to its own local behavior when no companion answers, so the system still works on a machine with no graphical session.
gherkin @FR-7MustA caller shall fall back to its own local behavior when no companion answers, so the system still works on a machine with no graphical session. Scenario: No companion means a local fallback Given no companion is listening on the socket When a caller asks to open a URL Then the caller opens it with its own local opener instead of failing -
FR-8MustThe companion shall engage the lid-close override while a session is working, and shall release it when the work stops, when the activity lease expires, or when the companion exits.
gherkin @FR-8MustThe companion shall engage the lid-close override while a session is working, and shall release it when the work stops, when the activity lease expires, or when the companion exits. Scenario: Lid override follows the work Given a running companion on macOS or Windows When a power-activity request activates and then deactivates the override Then the lid close is blocked while active and the original setting is put back afterwards -
FR-9MustThe companion shall write the original power settings to a recovery journal before changing them, and shall restore them when the owning process dies, so a killed process cannot leave the machine unable to sleep.
gherkin @FR-9MustThe companion shall write the original power settings to a recovery journal before changing them, and shall restore them when the owning process dies, so a killed process cannot leave the machine unable to sleep. Scenario: A killed owner is repaired by the next process Given a companion that was killed while holding the lid override When the next companion starts Then the original lid setting from the recovery journal is restored -
FR-10MustThe companion shall provide a global push-to-talk listener on Linux that records only while a jcode CLI session is focused, shows a visible recording indicator, and sends the finished transcript to that session.
gherkin @FR-10MustThe companion shall provide a global push-to-talk listener on Linux that records only while a jcode CLI session is focused, shows a visible recording indicator, and sends the finished transcript to that session. Scenario: Push-to-talk reaches the focused session Given a running companion with a configured global device and a focused jcode CLI session When the user holds the push-to-talk key and releases it Then a recording indicator is shown, the audio is transcribed, and the transcript is sent to that session -
FR-11MustThe global push-to-talk listener shall be opt-in through the configured keyboard event devices, and shall be disabled at runtime by a command-line flag or by an environment variable.
gherkin @FR-11MustThe global push-to-talk listener shall be opt-in through the configured keyboard event devices, and shall be disabled at runtime by a command-line flag or by an environment variable. Scenario: Global voice is opt-in and can be turned off Given no global device is configured When the companion starts Then no global push-to-talk listener is started -
FR-12MustThe companion shall refuse to open the microphone when no visible recording indicator can be shown.
gherkin @FR-12MustThe companion shall refuse to open the microphone when no visible recording indicator can be shown. Scenario: Recording is refused without an indicator Given a press on the push-to-talk key And the desktop notification cannot be shown Then the microphone is not opened -
FR-13ShouldThe system shall run the configured dictation command and apply the resulting transcript according to the configured mode, either sending it to the focused jcode client or typing it into the focused application.
gherkin @FR-13ShouldThe system shall run the configured dictation command and apply the resulting transcript according to the configured mode, either sending it to the focused jcode client or typing it into the focused application. Scenario: Configured dictation applies the configured mode Given a dictation command configured to print a transcript When the dictate command runs Then the transcript is sent to the focused jcode client or typed into the focused application -
FR-14ShouldThe voice subsystem shall transcribe captured audio with the Nari streaming API, sourcing the audio from either native capture or an external recorder process.
gherkin @FR-14ShouldThe voice subsystem shall transcribe captured audio with the Nari streaming API, sourcing the audio from either native capture or an external recorder process. Scenario: Audio is transcribed by the streaming service Given a recording opened from native capture or an external recorder When the audio is streamed for transcription Then a final transcript or a specific failure is reported -
FR-15ShouldThe companion shall refresh an installed browser bridge on a periodic schedule, off the browser tool's hot path.
gherkin @FR-15ShouldThe companion shall refresh an installed browser bridge on a periodic schedule, off the browser tool's hot path. Scenario: Browser bridge stays current off the hot path Given an installed browser bridge When the companion's periodic update runs Then the bridge is updated without adding a network round trip to a browser action -
FR-16MayOpening a URL on the niri compositor shall raise the browser window that handled it.
gherkin @FR-16MayOpening a URL on the niri compositor shall raise the browser window that handled it. Scenario: The browser window that handled the URL is raised Given a niri session with a browser window When the companion opens a URL Then the browser window that handled the URL is focused -
FR-17MayThe global push-to-talk listener shall share a routing registry with Jcode Desktop, so the most recently focused registrant wins a press.
gherkin @FR-17MayThe global push-to-talk listener shall share a routing registry with Jcode Desktop, so the most recently focused registrant wins a press. Scenario: The most recently focused registrant wins a press Given two registrants in the shared routing registry When the press-to-talk key is pressed Then the most recently focused eligible registrant handles the press -
NFR-1MustA companion request shall be answered within the caller's timeout, and a liveness probe shall be answered in under 500 ms.
gherkin @NFR-1MustA companion request shall be answered within the caller's timeout, and a liveness probe shall be answered in under 500 ms. Scenario: Liveness probe is fast Given a running companion When a status probe is sent Then the reply arrives in under 500 ms -
NFR-2MustThe microphone shall be opened only after an explicit user press, and the capture shall be released on key release, on cancel, on drop, on device failure, on the byte cap, and at the five-minute cap.
gherkin @NFR-2MustThe microphone shall be opened only after an explicit user press, and the capture shall be released on key release, on cancel, on drop, on device failure, on the byte cap, and at the five-minute cap. Scenario: Capture never outlives the press Given a user presses the push-to-talk key When the key is released, cancelled, or the five-minute cap is reached Then the microphone is released and no further audio is captured -
NFR-3MustNo audio, transcript, credential, provider error, or response body shall be written to the log, to an error message, or to a notification.
gherkin @NFR-3MustNo audio, transcript, credential, provider error, or response body shall be written to the log, to an error message, or to a notification. Scenario: Transcripts and keys never leak Given a transcription that fails When the failure is reported Then the message names no audio, no transcript, no key, and no provider response body -
NFR-4MustThe companion socket shall live in the per-user runtime directory, a request line shall be capped at 64 KiB, and a malformed request shall be answered with an error instead of taking the server down.
gherkin @NFR-4MustThe companion socket shall live in the per-user runtime directory, a request line shall be capped at 64 KiB, and a malformed request shall be answered with an error instead of taking the server down. Scenario: A malformed request does not stop the server Given a running companion When a request line that is not valid JSON arrives Then the reply is an error and the server keeps serving later requests -
NFR-5MustThe power-activity lease shall expire 30 seconds after the last renewal and the override shall be released at the next five-second reconcile tick, and a stale lid override left by a dead owner shall be repaired by the next companion that starts.
gherkin @NFR-5MustThe power-activity lease shall expire 30 seconds after the last renewal and the override shall be released at the next five-second reconcile tick, and a stale lid override left by a dead owner shall be repaired by the next companion that starts. Scenario: A silent server releases the override Given a companion holding the lid override When the server stops renewing the activity lease Then the 30 second lease expires and the override is released at the next reconcile tick -
NFR-6ShouldThe system shall check the session lock state before every press and before delivery, and shall refuse to record while the session is locked.
gherkin @NFR-6ShouldThe system shall check the session lock state before every press and before delivery, and shall refuse to record while the session is locked. Scenario: A locked session is not recorded Given a locked desktop session When the user presses the push-to-talk key Then the press is denied and no audio is captured -
NFR-7ShouldThe system shall keep working with no companion installed, and every voice failure shall map to one specific short user-facing message.
gherkin @NFR-7ShouldThe system shall keep working with no companion installed, and every voice failure shall map to one specific short user-facing message. Scenario: Every voice failure has its own message Given a missing API key, an exhausted credit balance, a timeout and a missing microphone When each failure is reported Then each one shows a distinct short message -
NFR-8ShouldThe companion shall run on Linux, macOS, and Windows, and the reported capability list shall match what the current platform can do.
gherkin @NFR-8ShouldThe companion shall run on Linux, macOS, and Windows, and the reported capability list shall match what the current platform can do. Scenario: Capabilities match the platform Given a companion running on Linux When the status request is answered Then the capability list contains voice and does not contain lid
Conflicts
None identified.
Open Questions
None.
Specification: Desktop Companion and Voice
Overview
The technical approach is a brokered split between a screen-free runtime and a per-login desktop companion.
The harness server and the agent runtime keep no screen, keyboard, microphone, or lid dependency.
When they need a desktop effect they send one JSON request over a local socket to jcode companion, a small process that runs as the user inside the graphical login session and owns the desktop integrations.
The companion answers with one JSON response line, so the wire format is a line-delimited JSON request/response protocol with a versioned request set.
The voice subsystem is a separate crate, jcode-voice, that captures microphone audio (natively through cpal, or through an external recorder process), resamples it to mono 16 kHz PCM16, and streams it to the Nari realtime transcription API over a websocket.
The companion's global push-to-talk listener, the TUITerminal User Interface's /voice and /dictate commands, and the jcode dictate CLI all feed that same capture and transcription path.
This specification documents already-implemented code, reverse-engineered during an SDLC sync.
Architecture
The runtime and the companion are separate processes that talk over one local socket.
+----------------------------+ +---------------------------------+
| harness server |---------->| jcode companion (per-login) |
| (no screen, no keyboard, |---------->| runs in the graphical session |
| no microphone, no lid) |---------->| |
| |---------->| socket server, JSON per line |
| open tool +---------->| open / reveal |
| terminal spawn +---------->| spawn_terminal |
| power monitor +---------->| power_activity |
| auth browser +---------->| global voice |
| |---------->| browser bridge updater |
| |---------->| lid override (macOS, Windows) |
| no companion listening? |---------->| |
| -> local fallback |---------->| |
+----------------------------+ +---------------------------------+
The socket lives at JCODE_COMPANION_SOCKET, else jcode-companion.sock in the runtime directory.
The companion sets JCODE_COMPANION=1 in its own environment, so a terminal it spawns does not call back into it.
voice capture and transcription (jcode-voice)
push-to-talk key (evdev) TUITerminal User Interface /voice jcode dictate
| | |
+----------------+----------------+
|
capture start, on an explicit press
|
+-----------------------------------+
| |
native cpal capture external recorder
(jcode-voice capture) pw-record, parecord,
arecord, rec, ffmpeg
| |
+--------> mono 16 kHz PCM16 <------+
|
resample, downmix, level
|
nari_pcm_channel (bounded)
|
NariRecording, websocket to Nari
|
NariEvent::Transcript / ::Finished
|
+-----------------------------------+
| |
TUITerminal User Interface session global companion voice
voice input send over the jcode debug socket
Data Models
CompanionRequest
Defined in crates/jcode-base/src/companion_client.rs and shared by the client and the server.
| Field | Type | Constraints | Description |
|---|---|---|---|
| op | string | required, one of the known operations | Discriminator of the tagged enum. |
| target | string | required for open |
URL or local path to open. |
| path | path | required for reveal |
Local path to show in the file manager. |
| program | path | required for spawn_terminal |
Program to run in the new window. |
| args | list of string | required for spawn_terminal |
Arguments for the program. |
| cwd | path | required for spawn_terminal |
Working directory for the program. |
| title | string | optional | Window title for the new terminal. |
| kind | string | optional | Caller-defined kind such as resume. |
| session_id | string | optional | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. the new terminal belongs to. |
| env | list of pairs | optional, omitted when empty | JCODE_SPAWN_* metadata exported to hooks and the terminal. |
| client_terminal_env | list of pairs | optional, omitted when empty | Terminal environment of the client that asked, so the window lands in the terminal the user is attached to. |
| active | bool | required for power_activity |
Whether a session is actively working. |
CompanionResponse
| Field | Type | Constraints | Description |
|---|---|---|---|
| ok | bool | required | Whether the request completed. |
| message | string | default empty | Human-readable result, such as the opener that ran, or the error text. |
| protocol | u32 | default 0 | Protocol version of the responder, currently PROTOCOL_VERSION = 1. |
| capabilities | list of string | omitted when empty | Capabilities the responder handles, such as open, reveal, spawn_terminal, lid, voice. |
CompanionOptions
| Field | Type | Constraints | Description |
|---|---|---|---|
| socket | path | defaults to socket_path() |
Where the companion binds its listener. |
| voice | bool | defaults to true | Run the global push-to-talk listener, Linux only. |
| browser_updates | bool | defaults to true | Periodically update an installed browser bridge. |
LidSnapshot
The original power settings captured before the override changes them, tagged by platform.
| Field | Type | Constraints | Description |
|---|---|---|---|
| platform | string | macos, windows, or fake |
Discriminator of the tagged enum. |
| sleep_disabled | bool | macOS only | Original pmset sleep state. |
| scheme | string | Windows only | Active power scheme GUID in canonical form. |
| ac_lid_action | u32 | Windows only | Original lid-close action on AC power. |
| dc_lid_action | u32 | Windows only | Original lid-close action on battery. |
| value | u32 | test backend only | Original value of the in-memory stand-in. |
Journal
| Field | Type | Constraints | Description |
|---|---|---|---|
| owner_pid | u32 | required | Process id that owns the override, used to detect a dead owner. |
| snapshot | LidSnapshot | required | Original settings to restore. |
Target and LocalTargetKind
| Field | Type | Constraints | Description |
|---|---|---|---|
| path | path | local targets only | Existing local path. |
| kind | LocalTargetKind | file or directory |
Whether the path is a file or a directory, decided by LocalTargetKind::of. |
| url | string | url targets only | The URL to hand to the system opener. |
DictationConfig
Configured under [dictation] in ~/.jcode/config.toml.
| Field | Type | Constraints | Description |
|---|---|---|---|
| command | string | empty means dictation is not configured | Shell command that prints the transcript to stdout. |
| mode | TranscriptMode | insert, append, replace, or send |
How the transcript is applied inside jcode. |
| key | string | default off |
Optional in-app hotkey that triggers dictation. |
| timeout_secs | u64 | default 90, 0 means no timeout | Maximum time to wait for the dictation command. |
| vocabulary | list of string | optional | Extra recognition context sent to the transcription service. |
| recorder | string | empty means auto-detect | Custom command that prints raw mono 16 kHz s16le PCM. |
| global_devices | list of path | empty disables global voice | Keyboard event devices the companion watches for push-to-talk. |
NariEvent
| Field | Type | Constraints | Description |
|---|---|---|---|
| Started | variant | emitted once | The transcription session is open. |
| Transcript | string | aggregate revision, not a delta | The latest full transcript so far. |
| Finished | result | emitted exactly once | The final transcript, or the failure that ended the session. |
Edge
| Field | Type | Constraints | Description |
|---|---|---|---|
| Press | variant | physical key down | Start a capture. |
| Release | variant | physical key up | Stop the capture and deliver the transcript. |
| Cancel | variant | safety or failure | Abort without finalizing a transcript. |
| Spawn | variant | Shift plus push-to-talk | Open a new window that records the hold. |
| Tap | variant | hold already ended | Start a click-style recording instead of losing the request. |
API Contracts
This feature defines no HTTP API, so there is no api.yaml alongside this document.
The normative contracts are the two local interfaces below: the companion socket protocol, and the command-line and TUITerminal User Interface surfaces that reach it.
Companion socket protocol
- TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI).: a Unix domain socket at
JCODE_COMPANION_SOCKET, elsejcode-companion.sockin the runtime directory. On Windows the transport is a named pipe. - Framing: one JSON object per line. A request line is answered by exactly one response line, and the connection stays open for further requests.
- The request is a tagged enum on
op; the response carriesok,message,protocol, andcapabilities. - A line longer than 64 KiB is rejected, and a line that is not a known request is answered with
ok: falseand aninvalid requestmessage.
| Operation | Request fields | Response message | Purpose |
|---|---|---|---|
status |
none | the companion version string | Liveness probe, reports the protocol version and the capabilities. |
open |
target |
name of the opener that ran | Open a URL or local path with the desktop's default application. |
reveal |
path |
name of the backend that showed it | Show a local path in the file manager. |
spawn_terminal |
program, args, cwd, optional title, kind, session_id, env, client_terminal_env |
terminal |
Run a program in a new terminal window in the user's session. |
power_activity |
active |
engaged or released |
Hold or release the lid-close override while a session works. |
Client-side error mapping:
| Condition | Error | Caller behavior |
|---|---|---|
| No companion is listening | CompanionError::Unavailable |
Fall back to the local behavior. |
The companion answered with ok: false |
CompanionError::Failed(message) |
Report the message, or fall back for open and spawn_terminal. |
| The connection broke mid-request | CompanionError::Io |
Report the failure. |
CLI surface
| Command | Options | Effect |
|---|---|---|
jcode companion |
none | Run the companion in the current login session. |
jcode companion --status |
--status |
Report whether a companion is running, with its socket path and capabilities, then exit. |
jcode companion --no-voice |
--no-voice |
Run the companion without the global push-to-talk listener. |
jcode dictate |
none | Run the configured dictation command and apply the transcript in the configured mode. |
jcode dictate --type |
--type |
Run the configured dictation command and type the transcript into the focused application with wtype. |
TUITerminal User Interface command surface
| Command | Effect |
|---|---|
/dictate |
Run the configured dictation command and apply the transcript. |
/dictation |
Alias of /dictate. |
/voice |
Toggle the built-in voice input: press to record, press again to send, Esc to cancel. |
Sequences
Desktop effect requested by the server
sequenceDiagram
autonumber
participant S as Harness server
participant C as Companion socket
participant D as Desktop tool
S->>C: CompanionRequest::Open with the target
C->>C: parse the target as a url or a local path
C->>D: spawn detached opener
D-->>C: exit status
C-->>S: CompanionResponse with ok and the backend name
S-->>S: report the backend to the agent
Global push-to-talk capture and delivery
sequenceDiagram
autonumber
participant U as User
participant K as Hotkey listener
participant V as Companion voice worker
participant N as Nari streaming
participant T as Focused jcode session
U->>K: hold the push-to-talk key
K->>K: poll focus, check the session lock
K-->>V: Edge::Press
V->>V: show the recording indicator
V->>N: open the websocket and stream PCM
U->>K: release the key
K-->>V: Edge::Release
V->>N: stop and wait for the final transcript
N-->>V: NariEvent::Finished(text)
V->>T: Request::Transcript over the debug socket
T-->>V: ServerEvent::Done
V->>V: show the delivery result
Lid override engaged and released
sequenceDiagram
autonumber
participant V as Server power monitor
participant C as Companion
participant L as lid_override
participant J as Recovery journal
V->>C: CompanionRequest::PowerActivity with active true
C->>L: set_active(true)
L->>J: write the original settings and the owner pid
L->>L: block the lid close
V->>C: CompanionRequest::PowerActivity with active true, as a renewal
C->>L: renew the 30 second lease
V->>C: CompanionRequest::PowerActivity with active false
C->>L: set_active(false)
L->>J: read the journal
L->>L: restore the original settings
L->>J: remove the journal
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Where desktop effects live | A separate per-login companion process over a local socket | Keeps the harness server and the agent runtime free of screens, keyboards, microphones, and lids, so a headless or remote server never pops a window on the wrong machine. |
| Wire format | Line-delimited JSON, one request per line, one response per line | Matches the form of the rest of the jcode socket protocols, needs no framing library, and is trivial to inspect by hand. |
| Protocol versioning | A single PROTOCOL_VERSION constant, bumped on an incompatible change |
The client and the companion can be different builds during a hot reload, and the status reply reports the version. |
| Fallback behavior | The caller opens or spawns locally when no companion answers | A standalone jcode on a machine with no graphical session must keep working. |
| Single-instance enforcement | A status probe before binding, and a refusal to replace a live socket | Two companions on one login session would fight over the lid override and the routing registry. |
| Recursive spawn guard | The companion sets JCODE_COMPANION=1 in its own environment |
A terminal spawned by the companion must not call back into the companion socket. |
| Power-activity lease | A 30 second lease, renewed by the server and expired by a 5 second tick | A crashed server must not leave the machine unable to sleep. |
| Crash recovery | A journal file holding the original settings and the owner pid, written before the change | The macOS and Windows settings outlive the process, so the originals have to survive a kill. |
| Ownership arbitration | A live foreign owner is left alone, a dead owner is repaired | Two jcode processes on one machine must not undo each other's override. |
| Linux lid handling | systemd-inhibit with handle-lid-switch |
It is a per-process lock that is released when the helper dies, so no persistent setting and no journal are needed. |
| macOS elevation | sudo -n /usr/bin/pmset -a disablesleep with a sudoers hint |
The command must never prompt for a password inside an agent turn. |
| Windows elevation | The active power plan is edited directly | Standard users may change their own plan, so no elevation is needed. |
| Global voice platform | Linux only, through evdev polling | A hold listener needs the raw key events, which the Linux input devices provide. |
| Key event privacy | Only the configured event devices are opened, and no ordinary key events are read | The listener is scoped to the push-to-talk chord so it never observes ordinary typing. |
| Routing arbitration | A shared registry under the runtime directory, with the newest focus winning | Jcode Desktop and the companion both offer push-to-talk, and the most recently focused one should handle the press. |
| Recording indicator | A desktop notification, and recording is refused when it cannot be shown | The user must always be able to see that the microphone is live. |
| Voice transcription | Nari realtime over a websocket, with aggregate transcript revisions | Partial results are needed while the user is still speaking, and the final result is authoritative. |
| Audio sources | Native cpal capture, or an external recorder printing raw PCM | Terminal builds do not link a native audio stack, and a custom recorder keeps the capture scriptable. |
| Audio format | Mono 16 kHz PCM16, at most 5 minutes and 10 MiB | One format across capture paths, and a hard bound on what can be sent or stored. |
| Browser bridge updates | A periodic task in the companion | The browser tool used to check for a newer bridge inline, which added a GitHub round trip to every agent turn. |
| Browser window raising | niri IPCInter-Process Communication, with a new window preferred over the most recently focused one | A newly created browser window is the one that handled the URL, and raising it is what the user expects. |
| Browser window raising scope | niri only, other compositors are skipped | The compositor interface is not yet abstracted, and the fallback open still works everywhere. |
Risks and Unknowns
- The macOS lid override depends on a
sudoersrule the user must add by hand, and the override is silently skipped without it. The one-time hint inMACOS_SUDOERS_HINTis the only signal. - The Windows lid override rewrites the active power plan. Restoring it never switches the user back to a plan they changed in the meantime, so the restore is skipped when the plan is no longer active.
- The global voice listener and the focus lookup depend on the niri compositor. On another Linux desktop the listener still registers, but the focused session cannot be resolved, so the press is ignored.
- The external recorder path depends on one of
pw-record,parecord,arecord,rec, orffmpegbeing installed and behaving as documented. - The Nari websocket is a third-party dependency, and a failure mid-session can leave the capture released without a transcript, which the user sees as a cancelled recording.
- The 64 KiB request cap and the 10 MiB audio cap are fixed constants. A future request with a large payload would need a different framing.
- The browser bridge refresh runs hourly inside the companion, so a companion that is rarely started keeps the bridge stale.
- The companion protocol has no authentication beyond filesystem permissions on the runtime directory, so any process running as the same user can drive the desktop.
Out of Scope
- The Jcode Desktop application itself, which shares the voice and routing code but lives in another repository.
- The server-side browser tool, the browser bridge implementation, and the browser bridge download itself.
- The remote handoff and session migration design sketched in
docs/REMOTE_HANDOFF.md, which is not implemented. - The wording rules for user-facing messages, which are covered by
docs/MESSAGE_VOICE.md. - The macOS and Windows global hotkey listeners, which belong to the platform hotkey feature.
- Subscription entitlement and billing for the transcription service.
Test Plan: Desktop Companion and Voice
Scope
Covers the companion socket protocol, the lid-close override and its crash recovery, the desktop-open helpers, the global push-to-talk hotkey listener, the microphone capture and streaming transcription path, and the configured dictation command. Every test listed here is an existing test in the repository. Out of scope: the live macOS and Windows power-plan changes, the live Nari service, the live notification daemon, and physical evdev devices, which are exercised manually rather than in an automated test.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Companion requests and responses round-trip as tagged JSON | crates/jcode-base/src/companion_client.rs -> requests_round_trip_as_tagged_json |
The request serializes with an op tag and deserializes back to the same value. |
| TC-2 | Lid override engages and restores the original setting | crates/jcode-companion/src/lid_override.rs -> engages_then_restores_original_setting |
The setting is blocked while engaged, the original value comes back, and the journal is removed. |
| TC-3 | Dropping the override restores the original setting | crates/jcode-companion/src/lid_override.rs -> drop_restores_setting |
The original value is restored and the journal is removed when the owner goes out of scope. |
| TC-4 | A crashed owner is repaired by the next process | crates/jcode-companion/src/lid_override.rs -> crashed_owner_is_recovered_by_next_process |
The next idle tick restores the original value and clears the journal. |
| TC-5 | The originals survive a crash and a later engagement | crates/jcode-companion/src/lid_override.rs -> crashed_owner_originals_are_kept_when_next_process_engages |
The restored value is the user's value, not the value the crash left behind. |
| TC-6 | A live foreign owner is left alone | crates/jcode-companion/src/lid_override.rs -> live_foreign_owner_is_left_alone |
The second process does not engage and does not undo the owner's override. |
| TC-7 | A re-exec with the same pid reuses the saved originals | crates/jcode-companion/src/lid_override.rs -> reexec_with_same_pid_reuses_saved_originals |
The re-exec'd process engages and restores the original value. |
| TC-8 | A failed block rolls back and stops retrying until idle | crates/jcode-companion/src/lid_override.rs -> failed_block_rolls_back_and_stops_retrying_until_idle |
The override is not engaged, the journal is removed, and the retry latch resets on the idle transition. |
| TC-9 | The pmset -g sleep flag is parsed |
crates/jcode-companion/src/lid_override.rs -> pmset_output_parsing |
SleepDisabled 1 is detected, and the other shapes are not. |
| TC-10 | The Windows power-scheme GUID round-trips | crates/jcode-companion/src/lid_override.rs -> guid_round_trips |
A canonical GUID parses into its parts and formats back unchanged, and a bad string is rejected. |
| TC-11 | The recovery journal format is stable | crates/jcode-companion/src/lid_override.rs -> snapshot_journal_format_is_stable |
The journal serializes with the platform tag and deserializes back to the same snapshot. |
| TC-12 | The power-activity lease expires without renewal | crates/jcode-companion/src/server.rs -> power_lease_expires_without_renewal |
The lease is live halfway through the window and released once it expires. |
| TC-13 | The status reply carries the protocol and the capabilities | crates/jcode-companion/src/server.rs -> status_reports_protocol_and_capabilities |
The reply is successful and lists the configured capabilities. |
| TC-14 | Voice failures map to short labels | crates/jcode-companion/src/voice.rs -> failure_labels_are_short |
A missing configuration and a timeout each map to their own short message. |
| TC-15 | A target is classified as a URL or a local path | crates/jcode-desktop-open/src/lib_tests.rs -> target_parse_distinguishes_urls_and_paths |
A URL stays a URL, an existing directory is a local directory target, and a missing path is an error. |
| TC-16 | A desktop entry is normalized into application id stems | crates/jcode-desktop-open/src/lib_tests.rs -> normalize_desktop_entry_strips_suffix_and_adds_stem |
The .desktop suffix is stripped and the last segment is added as a second stem. |
| TC-17 | Browser application ids are matched case-insensitively | crates/jcode-desktop-open/src/lib_tests.rs -> app_id_matches_is_case_insensitive_and_guards_short_ids |
A matching id matches, a different id does not, and very short ids never match. |
| TC-18 | A newly created browser window is preferred | crates/jcode-desktop-open/src/lib_tests.rs -> select_window_prefers_newly_created_browser_window |
The window that appeared after the open wins over the more recently focused one. |
| TC-19 | The most recently focused window is the fallback | crates/jcode-desktop-open/src/lib_tests.rs -> select_window_falls_back_to_most_recently_focused |
With no new window, the window with the newest focus timestamp is chosen. |
| TC-20 | No browser window means nothing to raise | crates/jcode-desktop-open/src/lib_tests.rs -> select_window_returns_none_without_browser_windows |
The selection returns no window. |
| TC-21 | The dictation command output is trimmed | crates/jcode-voice/src/dictation_tests.rs -> run_command_trims_trailing_newlines |
The printed transcript comes back without its trailing newline. |
| TC-22 | The session short name is read from the window title | crates/jcode-voice/src/dictation_tests.rs -> extract_session_short_name_from_jcode_window_title |
The title format with live metrics still yields the short name. |
| TC-23 | The session short name is normalized | crates/jcode-voice/src/dictation_tests.rs -> normalize_session_short_name_strips_wrapping_punctuation |
Bracketed and hyphenated names become the bare lowercase token. |
| TC-24 | The client candidate matching the title is selected | crates/jcode-voice/src/dictation_tests.rs -> select_candidate_prefers_title_match |
The candidate whose name appears in the title wins. |
| TC-25 | The parent pid is read from the process status | crates/jcode-voice/src/dictation_tests.rs -> parse_ppid_from_proc_status |
The PPid field is parsed. |
| TC-26 | A resumed session id is read from the command line | crates/jcode-voice/src/dictation_tests.rs -> read_resumed_session_id_from_cmdline_for_current_process |
The reader runs against a live process command line without error. |
| TC-27 | The push-to-talk chord is decoded | crates/jcode-voice/src/global/hotkey/tests.rs -> decoder_chords_repeat_and_release |
A press and a release are produced, repeats and modifier noise are ignored, and the assistant key works alone. |
| TC-28 | Shift plus the push-to-talk key spawns instead of holding | crates/jcode-voice/src/global/hotkey/tests.rs -> shift_before_copilot_spawns_but_synthetic_shift_holds |
A user Shift before the key produces a spawn edge, and right Shift is never synthesized. |
| TC-29 | A key already held when the listener opens is ignored | crates/jcode-voice/src/global/hotkey/tests.rs -> held_at_open_is_ignored |
The snapshot of the held keys suppresses the spurious press, and a later press is still detected. |
| TC-30 | The global chord rejects control, alt and partial modifiers | crates/jcode-voice/src/global/hotkey/tests.rs -> global_chord_rejects_control_alt_and_partial_synthetic_modifiers |
The chord is refused for every disallowed modifier, and only keyboard event device paths are allowed. |
| TC-31 | The capability bitmap and the native input ABI are correct | crates/jcode-voice/src/global/hotkey/tests.rs -> capability_bitmap_and_native_abi |
The advertised bitmap decodes the expected keys, and the event struct sizes and the ioctl number match the kernel ABI. |
| TC-32 | The newest focus wins and the lease is stable | crates/jcode-voice/src/global/hotkey/tests.rs -> newest_focus_and_stable_lease |
A newer registrant takes the capture, a repeated heartbeat does not steal it back, and the lease is released on drop. |
| TC-33 | Stale and unready registrations are excluded | crates/jcode-voice/src/global/hotkey/tests.rs -> stale_and_unready_registrations_are_excluded |
A registration that is not ready or whose timestamp is expired never wins the capture. |
| TC-34 | A delayed press cannot recapture after the focus changed | crates/jcode-voice/src/global/hotkey/tests.rs -> delayed_press_cannot_recapture_after_focus_changes |
A press stamped before the focus change is refused, and a later stamp succeeds. |
| TC-35 | The heartbeat is throttled but focus and eligibility publish at once | crates/jcode-voice/src/global/hotkey/tests.rs -> heartbeat_is_throttled_but_focus_and_eligibility_publish_immediately |
A repeated active update does not rewrite the registration, and an eligibility change does. |
| TC-36 | A malformed peer registration does not block a valid capture | crates/jcode-voice/src/global/hotkey/tests.rs -> malformed_peer_registration_does_not_block_valid_capture |
The unreadable peer file is ignored and the capture still succeeds. |
| TC-37 | An unsafe routing directory is rejected | crates/jcode-voice/src/global/hotkey/tests.rs -> unsafe_directory_is_rejected |
A world-readable routing directory is refused at registration. |
| TC-38 | A poisoned event queue keeps its wakeup and its final event | crates/jcode-voice/src/streaming_capture/tests.rs -> poisoned_event_queue_preserves_original_wakeup_and_finished_event |
The queue recovers from a panicking producer and still delivers the finished event. |
| TC-39 | A cancelled constructor never opens the microphone | crates/jcode-voice/src/streaming_capture/tests.rs -> cancelled_constructors_never_open_microphone |
Both the native recorder and the streaming recorder refuse to start and report the cancellation. |
| TC-40 | The chunks are bounded, downmixed, and fail on backpressure | crates/jcode-voice/src/streaming_capture/tests.rs -> bounded_chunks_downmix_and_fail_on_backpressure |
Every chunk stays within the bound, the samples are downmixed, and a full queue marks the capture failed. |
| TC-41 | The filter tail never exceeds the duration cap | crates/jcode-voice/src/streaming_capture/tests.rs -> filter_tail_never_exceeds_duration_cap |
The delivered sample count equals the cap at every supported sample rate. |
| TC-42 | The final upsampled frame cannot exceed the cap | crates/jcode-voice/src/streaming_capture/tests.rs -> upsampling_final_frame_cannot_exceed_cap |
The sample count stops exactly at the cap with one residual sample buffered. |
| TC-43 | The reported level is the latest RMS | crates/jcode-voice/src/streaming_capture/tests.rs -> callback_level_is_latest_rms_not_peak_or_signed_average |
The level matches the RMS of the newest samples and returns to zero for silence. |
| TC-44 | The level downmixes and normalizes the native formats | crates/jcode-voice/src/streaming_capture/tests.rs -> callback_level_downmixes_and_normalizes_native_formats |
Stereo, integer, and float samples all produce the expected level. |
| TC-45 | The level stays finite for invalid float samples | crates/jcode-voice/src/streaming_capture/tests.rs -> callback_level_is_finite_and_bounded_for_invalid_float_samples |
Out-of-range and non-finite samples produce a bounded level. |
| TC-46 | The level is read without consuming events | crates/jcode-voice/src/streaming_capture/tests.rs -> recording_level_reads_callback_atomic_without_consuming_events |
The level is stable across reads, the queued event survives, and it drops to zero after stop or cancel. |
| TC-47 | Stop unparks the capture thread at once | crates/jcode-voice/src/streaming_capture/tests.rs -> stop_unparks_capture_thread_immediately |
The finish call returns well under the parked timeout. |
| TC-48 | The event wait wakes on push and keeps an early permit | crates/jcode-voice/src/streaming_capture/tests.rs -> event_ready_wakes_on_push_and_keeps_early_permit |
An event pushed before the wait is not lost, and a later push wakes a pending wait. |
| TC-49 | Events coalesce but the lifecycle is preserved | crates/jcode-voice/src/streaming_capture/tests.rs -> events_coalesce_but_preserve_lifecycle |
A thousand transcript revisions collapse to one, and the started and finished events stay in place. |
| TC-50 | Stop keeps the token and drop cancels without joining | crates/jcode-voice/src/streaming_capture/tests.rs -> stop_preserves_token_drop_cancels_without_joining |
A successful stop leaves the shared token untouched, and a drop sets the cancel token. |
| TC-51 | Native samples are downmixed and capped without a device | crates/jcode-voice/src/lib.rs -> downmix_and_cap_without_microphone_access |
The buffer downmixes to mono, clamps, and stops at the cap. |
| TC-52 | A cancelled start never opens a device | crates/jcode-voice/src/lib.rs -> cancelled_start_never_opens_a_device |
The constructor reports the cancellation before any device call. |
| TC-53 | Stop joins the worker and returns the audio | crates/jcode-voice/src/lib.rs -> stop_joins_and_returns_audio |
The audio comes back and the shared cancel token is not set. |
| TC-54 | Cancel and drop signal the worker and join it | crates/jcode-voice/src/lib.rs -> cancel_and_drop_signal_worker_and_join |
Both paths set the cancel token and wait for the worker to finish. |
| TC-55 | The WAV encoding and its bounds are enforced | crates/jcode-voice/src/lib.rs -> wav_encoding_and_bounds |
The header is written correctly, every truncation is rejected, and the duration cap is enforced. |
| TC-56 | Invalid input is rejected before the network call | crates/jcode-voice/src/lib.rs -> invalid_input_is_rejected_before_network |
Empty audio, a malformed language code, and an unreachable host all fail without leaking the input. |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-57 | A missing socket reports that the companion is unavailable | crates/jcode-base/src/companion_client.rs -> missing_socket_reports_unavailable |
The request returns the Unavailable error so the caller can fall back. |
| TC-58 | A failure reply is mapped to the failed error | crates/jcode-base/src/companion_client.rs -> failed_reply_maps_to_failed_error |
The request returns the Failed error carrying the companion's message. |
| TC-59 | The companion serves requests over the socket | crates/jcode-companion/src/server.rs -> serves_requests_over_the_socket |
A status request over a bound socket returns a successful reply. |
| TC-60 | A second companion refuses to replace a live one | crates/jcode-companion/src/server.rs -> refuses_to_replace_a_live_companion |
The second bind fails with an "already running" error, and a stale socket file is replaced. |
| TC-61 | Opening a missing path fails without launching anything | crates/jcode-companion/src/server.rs -> open_rejects_missing_paths_without_launching |
The reply is a failure that names the missing path. |
| TC-62 | The configured transcription API needs a key and uses the configured base | crates/jcode-voice/src/lib.rs -> configured_public_api_requires_key_and_uses_configured_base |
Without a key the call is refused, and with a key the request carries the bearer token. |
| TC-63 | The multipart upload matches the backend contract | crates/jcode-voice/src/lib.rs -> multipart_and_bearer_auth_match_backend_contract |
The request posts the WAV as a file part with the bearer token and the optional language field. |
| TC-64 | The language field is optional | crates/jcode-voice/src/lib.rs -> language_is_optional |
No language field is sent when none is requested. |
| TC-65 | The capability probe defaults to false | crates/jcode-voice/src/lib.rs -> capabilities_default_false_and_use_bearer_header |
Only an explicit voice_transcription: true makes voice available, and the probe uses the bearer header. |
| TC-66 | Failures never expose credentials or server bodies | crates/jcode-voice/src/lib.rs -> failures_never_expose_credentials_or_server_bodies |
Each error status maps to a typed error whose rendering contains no key and no base URL. |
| TC-67 | Requests time out and redirects are not followed | crates/jcode-voice/src/lib.rs -> requests_time_out_and_redirects_are_not_followed |
A slow response times out, and a redirect is reported as an HTTP error. |
| TC-68 | An oversized response is rejected | crates/jcode-voice/src/lib.rs -> oversized_response_is_rejected |
A body above the size limit is refused. |
| TC-69 | The focused session is resolved from the niri window title | crates/jcode-voice/src/dictation_tests.rs -> focused_jcode_session_uses_niri_window_title_when_process_name_is_generic |
A fake niri and a named child process resolve the session from the title. |
| TC-70 | The focused session is resolved from the client registry | crates/jcode-voice/src/dictation_tests.rs -> focused_cli_session_uses_client_registry_for_task_titled_windows |
A task-titled window still resolves the session through the registry. |
| TC-71 | The last focused session is remembered and read back | crates/jcode-voice/src/dictation_tests.rs -> remember_and_read_last_focused_session |
The session id survives the write and the read. |
| TC-72 | The hotkey listener survives a dropped event stream, a disconnect and a deadline | crates/jcode-voice/src/global/hotkey/tests.rs -> poll_dropped_disconnect_deadline_and_drop |
Each condition produces a cancel edge, and the capture lock is released afterwards. |
| TC-73 | A resync after dropped events keeps a held key and releases a lifted one | crates/jcode-voice/src/global/hotkey/tests.rs -> dropped_events_resync_keeps_a_held_key_and_releases_a_lifted_one |
The resync reports the held state, and the trigger is set only while the key is down. |
| TC-74 | Losing eligibility cancels, but a physical key-up still releases | crates/jcode-voice/src/global/hotkey/tests.rs -> eligibility_cancels_but_physical_key_up_releases |
The eligible case yields a release edge, and the ineligible case yields a cancel edge. |
| TC-75 | A registry failure cancels, and an invalid device list is refused | crates/jcode-voice/src/global/hotkey/tests.rs -> registry_failure_cancels_and_invalid_allowlist_fails |
The capture is cancelled, the listener reports not ready, and the constructor rejects the bad paths. |
| TC-76 | Routing contention retries only while the key is still down | crates/jcode-voice/src/global/hotkey/tests.rs -> routing_contention_retries_only_while_physical_key_remains_down |
The press is delivered after the contention clears when the key is held, and dropped when it was released. |
| TC-77 | A spawned window adopts the held key, or falls back to a tap | crates/jcode-voice/src/global/hotkey/tests.rs -> spawned_window_adopts_a_held_key_or_falls_back_to_a_tap |
The adoption produces a press when the key is held and a tap otherwise, and it happens only once. |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-78 | The capture opens during the transcription handshake and is released on a network error | crates/jcode-voice/src/streaming_capture/tests.rs -> orchestration_opens_capture_during_handshake_then_releases_on_network_error |
The microphone is live before the session is configured, the provider error is reported as a rejection, and the capture is released. |
| TC-79 | A setup error releases the capture and reports the provider error | crates/jcode-voice/src/streaming_capture/tests.rs -> orchestration_setup_error_releases_capture_and_reports_provider_error |
The exhausted-credit error surfaces and the capture is released. |
| TC-80 | The construction returns before the microphone or the network are ready | crates/jcode-voice/src/streaming_capture/tests.rs -> construction_returns_before_microphone_or_network_are_ready |
The call returns in under 100 ms while the handshake is still pending. |
| TC-81 | A cancelled slow factory finishes cancelled, without a stale capture | crates/jcode-voice/src/streaming_capture/tests.rs -> cancelled_slow_factory_finishes_cancelled_without_starting_stale_capture |
The recording finishes as cancelled, and the factory observes the cancel token so no stale capture starts. |
| TC-82 | The unified stop finalizes the session, and a drop afterwards keeps the token | crates/jcode-voice/src/streaming_capture/tests.rs -> unified_stop_finalizes_and_drop_after_finished_preserves_token |
The commit is sent, the final empty transcript is delivered, and the drop leaves the shared token untouched. |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-83 | No companion is listening, on a headless or remote server | The caller falls back to its own local behavior, and the request reports the companion as unavailable (TC-57, TC-58). |
| TC-84 | The target path does not exist | The open request fails with a message naming the path, and no opener is launched (TC-61, TC-15). |
| TC-85 | A second companion starts while one is already running | The second bind is refused with an "already running" error, and a stale socket file is replaced (TC-60). |
| TC-86 | The server stops renewing the activity lease | The override is released when the lease expires, and the release is logged (TC-12). |
| TC-87 | The owner is killed while holding the lid override | The next process restores the original settings from the journal, and never restores the blocked value (TC-4, TC-5, TC-7). |
| TC-88 | The macOS pmset call fails because the sudoers rule is missing |
The override is skipped, the failure is logged once, and the sudoers hint is shown; the retry latch resets on the idle transition (TC-8, TC-9). |
| TC-89 | The block fails and the rollback also fails | The journal is kept so a later run can restore it, and the combined failure is reported. This branch has no automated test and is verified manually. |
| TC-90 | No global device is configured | The companion starts no push-to-talk listener at all. This path has no automated test and is verified manually. |
| TC-91 | The desktop notification daemon is unavailable | The recording is refused before the microphone is opened. This path has no automated test and is verified manually. |
| TC-92 | The desktop session is locked | The press is denied and the transcript is not delivered. This path has no automated test and is verified manually. |
| TC-93 | The Nari key is missing, the credits are exhausted, or the request times out | Each failure maps to its own short message, and the capture is released in every case (TC-14, TC-66, TC-67, TC-79). |
| TC-94 | The focused window is not a jcode client | No session is resolved, and the press is ignored (TC-71, and focused_cli_session_ignores_unrelated_windows in crates/jcode-voice/src/dictation_tests.rs). |
| TC-95 | An ordinary key is pressed, or a control, alt or partial modifier is held | The chord is refused, and only the configured keyboard event devices are ever opened (TC-30, TC-31, TC-37). |
| TC-96 | The request line is not valid JSON, or is longer than 64 KiB | The companion answers with an error instead of dropping the connection, and the server keeps serving later requests. The malformed-request reply has no automated test. |
| TC-97 | The transcript contains a key, and the provider returns a body with a key | Neither the rendered error nor the log contains the key or the base URL (TC-66). |
Test Infrastructure
- The test files that back this plan, all of which exist in the repository:
crates/jcode-base/src/companion_client.rs, inline#[cfg(test)] mod tests: the socket client.crates/jcode-companion/src/server.rs, inline#[cfg(test)] mod tests: the socket server and its request handlers.crates/jcode-companion/src/lid_override.rs, inline#[cfg(test)] mod tests: the lid override, its journal, and the platform parsers.crates/jcode-companion/src/voice.rs, inline#[cfg(test)] mod tests: the global voice failure labels.crates/jcode-desktop-open/src/lib_tests.rs: the target parsing and the browser window selection.crates/jcode-voice/src/dictation_tests.rs: the dictation command, the session resolution, and the process inspection helpers.crates/jcode-voice/src/global/hotkey/tests.rs: the evdev hotkey decoder, the routing registry, and the device allowlist.crates/jcode-voice/src/streaming_capture/tests.rs: the streaming orchestration, the event queue, and the audio level.crates/jcode-voice/src/lib.rs, inline#[cfg(test)] mod tests: the transcription HTTP client, the WAV validation, and the native capture buffer.- The
Fakebackend in the lid override tests stands in for the macOS and Windows power settings, so no test touches the machine's power plan. - The hotkey tests use a private anonymous pipe and a fake
niriscript, so no test opens a physical input device or touches a live compositor. - The transcription tests use a local TCP mock server, so no test reaches the live transcription service.
- The
voice-capturefeature gates the native capture and level tests, and thelinuxandunixtargets gate the evdev, socket, and/proctests. - Fixtures needed: a temporary
JCODE_HOMEwith anactive_pidsdirectory and aclient_sessionsregistry, a temporary socket directory, and a temporary routing directory. - Run the whole area with
cargo test -p jcode-companion -p jcode-voice -p jcode-desktop-open, and the client withcargo test -p jcode-base companion_client.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall provide a per-login companion process (`jcode companion`) that runs inside the user's graphical session and owns every desktop-only effect: opening URLs and files, revealing paths, spawning terminal windows, the lid-close override, and the global push-to-talk listener. | TC-13, TC-59, TC-60 |
| FR-2MustThe harness server and the agent runtime shall request desktop effects over a local socket using one JSON request per line answered by one JSON response per line, and shall never open a screen, a keyboard, a microphone or a lid themselves. | TC-1, TC-57, TC-58, TC-59 |
| FR-3MustThe companion shall answer a status request with its version, its protocol version, and the list of capabilities it provides on the current platform. | TC-13, TC-31, TC-85 |
| FR-4MustThe companion shall open a URL or a local path with the desktop's default application, and shall report which opener ran. | TC-15, TC-61, TC-84 |
| FR-5MustThe companion shall show a local path in the file manager, selecting the file when the platform supports it. | TC-15, TC-16 |
| FR-6MustThe companion shall run a program in a new terminal window in the user's session, preserving the program, the arguments, the working directory, the title, the kind, the session id, and the environment metadata. | TC-1, TC-59 |
| FR-7MustA caller shall fall back to its own local behavior when no companion answers, so the system still works on a machine with no graphical session. | TC-57, TC-58, TC-83 |
| FR-8MustThe companion shall engage the lid-close override while a session is working, and shall release it when the work stops, when the activity lease expires, or when the companion exits. | TC-2, TC-3, TC-6, TC-12, TC-86 |
| FR-9MustThe companion shall write the original power settings to a recovery journal before changing them, and shall restore them when the owning process dies, so a killed process cannot leave the machine unable to sleep. | TC-4, TC-5, TC-7, TC-8, TC-11, TC-87, TC-88, TC-89 |
| FR-10MustThe companion shall provide a global push-to-talk listener on Linux that records only while a jcode CLI session is focused, shows a visible recording indicator, and sends the finished transcript to that session. | TC-22, TC-23, TC-24, TC-25, TC-26, TC-27, TC-28, TC-29, TC-69, TC-70, TC-72, TC-73, TC-74, TC-77, TC-94 |
| FR-11MustThe global push-to-talk listener shall be opt-in through the configured keyboard event devices, and shall be disabled at runtime by a command-line flag or by an environment variable. | TC-30, TC-37, TC-75, TC-90, TC-95 |
| FR-12MustThe companion shall refuse to open the microphone when no visible recording indicator can be shown. | TC-90, TC-91 |
| FR-13ShouldThe system shall run the configured dictation command and apply the resulting transcript according to the configured mode, either sending it to the focused jcode client or typing it into the focused application. | TC-21, TC-22, TC-23, TC-24, TC-25, TC-26, TC-71 |
| FR-14ShouldThe voice subsystem shall transcribe captured audio with the Nari streaming API, sourcing the audio from either native capture or an external recorder process. | TC-38, TC-39, TC-40, TC-48, TC-55, TC-62, TC-63, TC-64, TC-78, TC-79, TC-81, TC-82 |
| FR-15ShouldThe companion shall refresh an installed browser bridge on a periodic schedule, off the browser tool's hot path. | TC-18, TC-19, TC-20 |
| FR-16MayOpening a URL on the niri compositor shall raise the browser window that handled it. | TC-17, TC-18, TC-19, TC-20 |
| FR-17MayThe global push-to-talk listener shall share a routing registry with Jcode Desktop, so the most recently focused registrant wins a press. | TC-32, TC-33, TC-34, TC-35, TC-36, TC-75, TC-76, TC-77 |
| NFR-1MustA companion request shall be answered within the caller's timeout, and a liveness probe shall be answered in under 500 ms. | TC-59, TC-80 |
| NFR-2MustThe microphone shall be opened only after an explicit user press, and the capture shall be released on key release, on cancel, on drop, on device failure, on the byte cap, and at the five-minute cap. | TC-38, TC-39, TC-41, TC-42, TC-43, TC-44, TC-45, TC-46, TC-47, TC-49, TC-50, TC-51, TC-52, TC-53, TC-54, TC-81, TC-82 |
| NFR-3MustNo audio, transcript, credential, provider error, or response body shall be written to the log, to an error message, or to a notification. | TC-14, TC-55, TC-56, TC-65, TC-66, TC-67, TC-68, TC-97 |
| NFR-4MustThe companion socket shall live in the per-user runtime directory, a request line shall be capped at 64 KiB, and a malformed request shall be answered with an error instead of taking the server down. | TC-30, TC-31, TC-37, TC-64, TC-65, TC-68, TC-95, TC-96 |
| NFR-5MustThe power-activity lease shall expire 30 seconds after the last renewal and the override shall be released at the next five-second reconcile tick, and a stale lid override left by a dead owner shall be repaired by the next companion that starts. | TC-4, TC-5, TC-8, TC-12, TC-85, TC-87 |
| NFR-6ShouldThe system shall check the session lock state before every press and before delivery, and shall refuse to record while the session is locked. | TC-92 |
| NFR-7ShouldThe system shall keep working with no companion installed, and every voice failure shall map to one specific short user-facing message. | TC-14, TC-57, TC-83, TC-88, TC-93 |
| NFR-8ShouldThe companion shall run on Linux, macOS, and Windows, and the reported capability list shall match what the current platform can do. | TC-9, TC-10, TC-11, TC-13 |
requirements
None.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Remote Client Gateway
Overview
The remote client gateway exposes a running jcode server to devices on other machines, currently the iOS app and a web client. It listens on a TCP port, accepts a WebSocket upgrade from a client, and bridges that connection onto the same newline-delimited JSON session protocol that local Unix-socket clients use. Trust is established by a short-lived pairing code that the operator mints on the machine running the server, and by a per-device auth token that the server stores only as a hash. This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Operator running jcode on their own machine | Reach a running session from a phone or a second computer without extra network setup |
| iOS and web client authors | A stable pairing and WebSocket contract to build a client against |
| Security-conscious operator | Only explicitly authorized devices may open a session, and revocation takes effect on the next connection |
| Maintainer | One owner for the remote-access trust boundary so the CLI and the TUITerminal User Interface cannot drift apart |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall run a WebSocket gateway listener on the configured TCP port, 7643 by default, whenever the gateway is enabled. | Must | The system shall run a WebSocket gateway listener on the configured TCP port, 7643 by default, whenever the gateway is enabled. |
| FR-2MustThe system shall mint a random six-digit pairing code that expires five minutes after it is minted, and shall show the operator the code, the address to dial, and a `jcode://pair` URI. | Must | The system shall mint a random six-digit pairing code that expires five minutes after it is minted, and shall show the operator the code, the address to dial, and a jcode://pair URI. |
| FR-3MustThe system shall exchange a valid pairing code for a per-device auth token over `POST /pair`, and shall persist only a SHA-256 hash of that token. | Must | The system shall exchange a valid pairing code for a per-device auth token over POST /pair, and shall persist only a SHA-256 hash of that token. |
| FR-4MustThe system shall reject a `POST /pair` request whose code is unknown, already consumed, or expired with HTTP 401, and shall not issue a token. | Must | The system shall reject a POST /pair request whose code is unknown, already consumed, or expired with HTTP 401, and shall not issue a token. |
| FR-5MustThe system shall validate the auth token of every WebSocket upgrade against the device registry, and shall reject an unknown, malformed, or revoked token with HTTP 401 during the handshake. | Must | The system shall validate the auth token of every WebSocket upgrade against the device registry, and shall reject an unknown, malformed, or revoked token with HTTP 401 during the handshake. |
| FR-6MustThe system shall bridge each authorized WebSocket connection onto the newline-delimited JSON session protocol over a virtual socket pair, so a remote client drives a session exactly like a local client. | Must | The system shall bridge each authorized WebSocket connection onto the newline-delimited JSON session protocol over a virtual socket pair, so a remote client drives a session exactly like a local client. |
| FR-7MustThe system shall list the paired devices with their id, name, pairing time, and last-seen time. | Must | The system shall list the paired devices with their id, name, pairing time, and last-seen time. |
| FR-8MustThe system shall revoke a paired device by id or by exact name, and a revoked device's token shall be rejected on its next connection attempt. | Must | The system shall revoke a paired device by id or by exact name, and a revoked device's token shall be rejected on its next connection attempt. |
| FR-9MustThe system shall reject a WebSocket upgrade whose path is not `/ws` with HTTP 404. | Must | The system shall reject a WebSocket upgrade whose path is not /ws with HTTP 404. |
| FR-10MustThe system shall serve several remote clients at the same time, giving each client its own session stream. | Must | The system shall serve several remote clients at the same time, giving each client its own session stream. |
| FR-11ShouldThe system shall accept the auth token from an `Authorization: Bearer <token>` header or from a `token=` query parameter, and shall reject a request that carries two different tokens. | Should | The system shall accept the auth token from an Authorization: Bearer <token> header or from a token= query parameter, and shall reject a request that carries two different tokens. |
| FR-12ShouldThe system shall answer `GET /health` with the server status and version, and shall answer CORS preflight requests so that browser clients can reach the gateway. | Should | The system shall answer GET /health with the server status and version, and shall answer CORS preflight requests so that browser clients can reach the gateway. |
| FR-13ShouldThe system shall resolve the address a remote client should dial, preferring the explicit bind address, then `JCODE_GATEWAY_HOST`, then the Tailscale MagicDNS name, then the system hostname. | Should | The system shall resolve the address a remote client should dial, preferring the explicit bind address, then JCODE_GATEWAY_HOST, then the Tailscale MagicDNS name, then the system hostname. |
| FR-14ShouldThe system shall let an operator enable the gateway, disable the gateway, pair a device, and revoke a device from the TUITerminal User Interface through `/remote`, using the same logic as the `jcode pair` CLI. | Should | The system shall let an operator enable the gateway, disable the gateway, pair a device, and revoke a device from the TUITerminal User Interface through /remote, using the same logic as the jcode pair CLI. |
| FR-15ShouldThe system shall record the time of the most recent successful connection as the device's last-seen timestamp. | Should | The system shall record the time of the most recent successful connection as the device's last-seen timestamp. |
| FR-16MayThe system shall send a WebSocket ping every 20 seconds and answer a client ping with a pong, so that idle and broken connections are detected. | May | The system shall send a WebSocket ping every 20 seconds and answer a client ping with a pong, so that idle and broken connections are detected. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustA pairing code shall expire five minutes after it is minted and shall be consumed on first successful use, so that a leaked or replayed code cannot mint a second token. | Must | Security | A pairing code shall expire five minutes after it is minted and shall be consumed on first successful use, so that a leaked or replayed code cannot mint a second token. |
| NFR-2MustThe system shall never persist a raw auth token, and shall store only a SHA-256 hash of a 32-byte random token. | Must | Security | The system shall never persist a raw auth token, and shall store only a SHA-256 hash of a 32-byte random token. |
| NFR-3MustThe system shall reject every WebSocket upgrade that carries no token, a malformed token, an unknown token, or a revoked token with HTTP 401, before any session stream is created. | Must | Security | The system shall reject every WebSocket upgrade that carries no token, a malformed token, an unknown token, or a revoked token with HTTP 401, before any session stream is created. |
| NFR-4MustThe gateway shall rely on the underlying network for transport confidentiality, and the system shall warn the operator when the bind address is a wildcard address. | Must | Security | The gateway shall rely on the underlying network for transport confidentiality, and the system shall warn the operator when the bind address is a wildcard address. |
| NFR-5ShouldOne failing client shall not stop the gateway listener, and the gateway shall keep serving the remaining clients. | Should | Availability | One failing client shall not stop the gateway listener, and the gateway shall keep serving the remaining clients. |
| NFR-6ShouldThe bridge shall add no framing beyond the newline delimiter, and shall emit a keepalive ping every 20 seconds. | Should | Performance | The bridge shall add no framing beyond the newline delimiter, and shall emit a keepalive ping every 20 seconds. |
| NFR-7ShouldThe WebSocket transport shall carry the same newline-delimited JSON protocol as the Unix-socket transport, so that one client implementation works over both. | Should | Compatibility | The WebSocket transport shall carry the same newline-delimited JSON protocol as the Unix-socket transport, so that one client implementation works over both. |
| NFR-8ShouldThe system shall log gateway lifecycle events, covering listener start, pairing, connection, disconnection, and revocation, through `crate::logging`. | Should | Operability | The system shall log gateway lifecycle events, covering listener start, pairing, connection, disconnection, and revocation, through crate::logging. |
Constraints
- The gateway binds its port when the server starts, so enabling the gateway requires a server restart.
- The default bind address is
0.0.0.0, which listens on every interface. - The pairing code is six decimal digits, short enough to read aloud and to type on a phone.
- The gateway speaks plain TCP and is expected to sit on a trusted network such as Tailscale.
- The paired device registry lives in
~/.jcode/devices.json, next to the rest of the jcode home state. - The gateway is disabled by default.
Acceptance Criteria
Every FR and NFR shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
-
FR-1MustThe system shall run a WebSocket gateway listener on the configured TCP port, 7643 by default, whenever the gateway is enabled.
gherkin @FR-1MustThe system shall run a WebSocket gateway listener on the configured TCP port, 7643 by default, whenever the gateway is enabled. Scenario: Gateway listens when it is enabled Given the gateway is enabled with a configured port When the server starts Then a TCP listener accepts connections on that port -
FR-2MustThe system shall mint a random six-digit pairing code that expires five minutes after it is minted, and shall show the operator the code, the address to dial, and a `jcode://pair` URI.
gherkin @FR-2MustThe system shall mint a random six-digit pairing code that expires five minutes after it is minted, and shall show the operator the code, the address to dial, and a `jcode://pair` URI. Scenario: Pairing code is minted Given an operator on the machine running the server When the operator runs the pairing command Then a six-digit code is shown together with the dial address and a jcode://pair URI -
FR-3MustThe system shall exchange a valid pairing code for a per-device auth token over `POST /pair`, and shall persist only a SHA-256 hash of that token.
gherkin @FR-3MustThe system shall exchange a valid pairing code for a per-device auth token over `POST /pair`, and shall persist only a SHA-256 hash of that token. Scenario: A code is exchanged for a token Given a valid pairing code When a client posts it to /pair with a device id and a device name Then the response carries an auth token and the server stores only a hash of it -
FR-4MustThe system shall reject a `POST /pair` request whose code is unknown, already consumed, or expired with HTTP 401, and shall not issue a token.
gherkin @FR-4MustThe system shall reject a `POST /pair` request whose code is unknown, already consumed, or expired with HTTP 401, and shall not issue a token. Scenario: A consumed code is refused Given a pairing code that was already consumed When a client posts it to /pair Then the response is 401 and no token is issued -
FR-5MustThe system shall validate the auth token of every WebSocket upgrade against the device registry, and shall reject an unknown, malformed, or revoked token with HTTP 401 during the handshake.
gherkin @FR-5MustThe system shall validate the auth token of every WebSocket upgrade against the device registry, and shall reject an unknown, malformed, or revoked token with HTTP 401 during the handshake. Scenario: A revoked device cannot upgrade Given a paired device whose token was revoked When the device requests a WebSocket upgrade on /ws Then the upgrade is rejected with 401 and no session stream is created -
FR-6MustThe system shall bridge each authorized WebSocket connection onto the newline-delimited JSON session protocol over a virtual socket pair, so a remote client drives a session exactly like a local client.
gherkin @FR-6MustThe system shall bridge each authorized WebSocket connection onto the newline-delimited JSON session protocol over a virtual socket pair, so a remote client drives a session exactly like a local client. Scenario: WebSocket frames drive a session Given an authorized remote client When the client sends a session request as a WebSocket text frame Then the server answers with session events in the same newline-delimited JSON format used by local clients -
FR-7MustThe system shall list the paired devices with their id, name, pairing time, and last-seen time.
gherkin @FR-7MustThe system shall list the paired devices with their id, name, pairing time, and last-seen time. Scenario: Paired devices are listed Given two paired devices When the operator lists the paired devices Then each device is shown with its id, name, pairing time, and last-seen time -
FR-8MustThe system shall revoke a paired device by id or by exact name, and a revoked device's token shall be rejected on its next connection attempt.
gherkin @FR-8MustThe system shall revoke a paired device by id or by exact name, and a revoked device's token shall be rejected on its next connection attempt. Scenario: A revoked device cannot reconnect Given a paired device When the operator revokes it by name Then the device is removed from the registry and its token is refused on the next connection attempt -
FR-9MustThe system shall reject a WebSocket upgrade whose path is not `/ws` with HTTP 404.
gherkin @FR-9MustThe system shall reject a WebSocket upgrade whose path is not `/ws` with HTTP 404. Scenario: The wrong upgrade path is refused Given a client holding a valid token When the client requests a WebSocket upgrade on a path other than /ws Then the upgrade is rejected with 404 -
FR-10MustThe system shall serve several remote clients at the same time, giving each client its own session stream.
gherkin @FR-10MustThe system shall serve several remote clients at the same time, giving each client its own session stream. Scenario: Two clients at the same time Given one authorized remote client attached to a session When a second authorized remote client connects Then both clients receive their own session events -
FR-11ShouldThe system shall accept the auth token from an `Authorization: Bearer <token>` header or from a `token=` query parameter, and shall reject a request that carries two different tokens.
gherkin @FR-11ShouldThe system shall accept the auth token from an `Authorization: Bearer <token>` header or from a `token=` query parameter, and shall reject a request that carries two different tokens. Scenario: A token in the query string Given a browser client that cannot set request headers When the client connects with a token query parameter Then the upgrade is authorizedgherkin @FR-11ShouldThe system shall accept the auth token from an `Authorization: Bearer <token>` header or from a `token=` query parameter, and shall reject a request that carries two different tokens. Scenario: Conflicting tokens are refused Given a request that carries a different token in the header and in the query string When the client requests a WebSocket upgrade Then the upgrade is rejected with 401 -
FR-12ShouldThe system shall answer `GET /health` with the server status and version, and shall answer CORS preflight requests so that browser clients can reach the gateway.
gherkin @FR-12ShouldThe system shall answer `GET /health` with the server status and version, and shall answer CORS preflight requests so that browser clients can reach the gateway. Scenario: Health check Given a running gateway When a client requests GET /health Then the response reports an ok status and the server version -
FR-13ShouldThe system shall resolve the address a remote client should dial, preferring the explicit bind address, then `JCODE_GATEWAY_HOST`, then the Tailscale MagicDNS name, then the system hostname.
gherkin @FR-13ShouldThe system shall resolve the address a remote client should dial, preferring the explicit bind address, then `JCODE_GATEWAY_HOST`, then the Tailscale MagicDNS name, then the system hostname. Scenario: The dial address is resolved Given the gateway binds to a wildcard address on a machine that has a Tailscale MagicDNS name When the operator asks for the address to dial Then the Tailscale name is used -
FR-14ShouldThe system shall let an operator enable the gateway, disable the gateway, pair a device, and revoke a device from the TUITerminal User Interface through `/remote`, using the same logic as the `jcode pair` CLI.
gherkin @FR-14ShouldThe system shall let an operator enable the gateway, disable the gateway, pair a device, and revoke a device from the TUITerminal User Interface through `/remote`, using the same logic as the `jcode pair` CLI. Scenario: The gateway is toggled from the TUITerminal User Interface Given a user in a TUITerminal User Interface session When the user runs the remote on command Then the gateway setting is persisted and the pairing and revocation logic of the CLI is used -
FR-15ShouldThe system shall record the time of the most recent successful connection as the device's last-seen timestamp.
gherkin @FR-15ShouldThe system shall record the time of the most recent successful connection as the device's last-seen timestamp. Scenario: Last seen is recorded Given a paired device When the device connects to the gateway Then the last-seen timestamp of the device is updated -
FR-16MayThe system shall send a WebSocket ping every 20 seconds and answer a client ping with a pong, so that idle and broken connections are detected.
gherkin @FR-16MayThe system shall send a WebSocket ping every 20 seconds and answer a client ping with a pong, so that idle and broken connections are detected. Scenario: Keepalive ping Given an idle gateway connection When 20 seconds pass without traffic Then the server sends a WebSocket ping and the connection stays open -
NFR-1MustA pairing code shall expire five minutes after it is minted and shall be consumed on first successful use, so that a leaked or replayed code cannot mint a second token.
gherkin @NFR-1MustA pairing code shall expire five minutes after it is minted and shall be consumed on first successful use, so that a leaked or replayed code cannot mint a second token. Scenario: Pairing code lifetime Given a pairing code that was minted five minutes ago When a client posts it to /pair Then the response is 401 and no token is issued -
NFR-2MustThe system shall never persist a raw auth token, and shall store only a SHA-256 hash of a 32-byte random token.
gherkin @NFR-2MustThe system shall never persist a raw auth token, and shall store only a SHA-256 hash of a 32-byte random token. Scenario: The raw token is not persisted Given a device that has been paired When the device registry file is read Then it holds a hash of the token and not the token itself -
NFR-3MustThe system shall reject every WebSocket upgrade that carries no token, a malformed token, an unknown token, or a revoked token with HTTP 401, before any session stream is created.
gherkin @NFR-3MustThe system shall reject every WebSocket upgrade that carries no token, a malformed token, an unknown token, or a revoked token with HTTP 401, before any session stream is created. Scenario: A missing token is refused Given a WebSocket upgrade request that carries no token When the client requests the upgrade Then the upgrade is rejected with 401 before any session stream is created -
NFR-4MustThe gateway shall rely on the underlying network for transport confidentiality, and the system shall warn the operator when the bind address is a wildcard address.
gherkin @NFR-4MustThe gateway shall rely on the underlying network for transport confidentiality, and the system shall warn the operator when the bind address is a wildcard address. Scenario: Wildcard bind warning Given the gateway binds to a wildcard address When the operator views the remote status Then the status warns that the port accepts connections from any address -
NFR-5ShouldOne failing client shall not stop the gateway listener, and the gateway shall keep serving the remaining clients.
gherkin @NFR-5ShouldOne failing client shall not stop the gateway listener, and the gateway shall keep serving the remaining clients. Scenario: One client fails Given a gateway with one client attached When the connection of that client fails Then the listener keeps serving the other clients -
NFR-6ShouldThe bridge shall add no framing beyond the newline delimiter, and shall emit a keepalive ping every 20 seconds.
gherkin @NFR-6ShouldThe bridge shall add no framing beyond the newline delimiter, and shall emit a keepalive ping every 20 seconds. Scenario: Bridge framing Given an authorized remote client When the client sends one request as a text frame Then the server reads exactly one newline-terminated request from the bridge -
NFR-7ShouldThe WebSocket transport shall carry the same newline-delimited JSON protocol as the Unix-socket transport, so that one client implementation works over both.
gherkin @NFR-7ShouldThe WebSocket transport shall carry the same newline-delimited JSON protocol as the Unix-socket transport, so that one client implementation works over both. Scenario: Protocol parity Given a client that speaks the newline-delimited JSON protocol When the same client runs over the Unix socket and over the WebSocket gateway Then both runs produce the same session payloads -
NFR-8ShouldThe system shall log gateway lifecycle events, covering listener start, pairing, connection, disconnection, and revocation, through `crate::logging`.
gherkin @NFR-8ShouldThe system shall log gateway lifecycle events, covering listener start, pairing, connection, disconnection, and revocation, through `crate::logging`. Scenario: Lifecycle logging Given a gateway that pairs a device and then receives a connection from it When the events are recorded Then the pairing and the connection are written to the log
Conflicts
None identified yet.
Open Questions
- Should an open WebSocket session be terminated when its device is revoked? Today revocation only blocks new connections.
- Should the gateway terminate TLS itself, or is a trusted network such as Tailscale the intended transport? Today it speaks plain TCP.
- Should
POST /pairrate-limit pairing-code attempts? A six-digit code can be guessed within its five-minute lifetime. - Is the remote protocol meant to be versioned for third-party clients, or is the versioned harness API the surface intended for them? The answer decides whether the remote protocol needs a compatibility policy.
Specification: Remote Client Gateway
Overview
The gateway lives in crates/jcode-base/src/gateway.rs with three supporting modules, gateway/auth.rs for the WebSocket handshake, gateway/control.rs for the shared /remote and jcode pair control logic, and gateway/registry.rs for the persisted device records.
The wire types PairedDevice and PairingCode live in the jcode-gateway-types crate so that both the server and client-facing code can depend on them without pulling in the rest of jcode-base.
The server starts the listener from crates/jcode-app-core/src/server.rs and accepts each gateway client in crates/jcode-app-core/src/server/runtime.rs, where the bridged stream is handed to the same client handler that serves Unix-socket clients.
This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
remote client (iOS app or web client)
|
| TCP on the configured port, default 7643
v
+---------------------------------------------------+
| jcode-base/src/gateway.rs |
| handle_connection() |
| peek the first bytes, look for "Upgrade:" |
| no -> handle_http() |
| GET /health |
| POST /pair |
| OPTIONS (CORS preflight) |
| yes -> handle_ws_connection() |
+---------------------------------------------------+
| tungstenite accept_hdr_async, auth inside the
| upgrade callback
v
+---------------------------------------------------+
| gateway/auth.rs |
| extract_ws_auth() Authorization: Bearer or ?token=
| authorize_ws_device() 401 for unknown or revoked |
+---------------------------------------------------+
| authorized device
v
+---------------------------------------------------+
| transport::stream_pair() |
| (server_stream, bridge_stream) |
+----+----------------------------------------+-----+
| client_tx | relay tasks
v v
+----------------------------+ +-------------------------------+
| jcode-app-core server | | ws <-> NDJSONNewline-Delimited JSON relay |
| runtime, one task per | | text frame, newline appended |
| client, same handle_client | | ping/pong, 20s keepalive |
| path as a local client | | 401 handshake rejections |
+----------------------------+ +-------------------------------+
|
v
+---------------------------------------------------+
| ~/.jcode/devices.json (DeviceRegistry) |
| devices[] PairedDevice, token_hash only |
| pending_codes[] PairingCode, five minute TTL |
+---------------------------------------------------+
The relay is deliberately thin. A WebSocket text frame carries exactly one newline-delimited JSON request, and the relay appends the newline the server-side reader expects. In the other direction the relay reads one newline-terminated line from the bridge and sends it as one text frame. Because the framing is identical on both sides of the bridge, the session server cannot tell whether its client arrived over a Unix socket or over a WebSocket.
Data Models
Pairing code (jcode_gateway_types::PairingCode)
| Field | Type | Constraints | Description |
|---|---|---|---|
| code | string | not null, six decimal digits | Code shown to the operator and entered or scanned by the client. |
| created_at | string | not null, RFC 3339 | Mint time in UTC. |
| expires_at | string | not null, RFC 3339 | Expiry time, five minutes after created_at. |
Paired device (jcode_gateway_types::PairedDevice)
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | string | PK, not null | Client-supplied device id; pairing the same id again replaces the record. |
| name | string | not null | Human-readable device name shown in the device list. |
| token_hash | string | not null, sha256: prefix |
SHA-256 hash of the auth token; the raw token is never stored. |
| apns_token | string | optional, omitted when absent | APNsApple Push Notification service push token for the iOS client. |
| paired_at | string | not null, RFC 3339 | Time the device was paired. |
| last_seen | string | not null, RFC 3339 | Time of the most recent successful gateway connection. |
Device registry (jcode_base::gateway::DeviceRegistry)
Persisted at ~/.jcode/devices.json.
| Field | Type | Constraints | Description |
|---|---|---|---|
| devices | list of PairedDevice | not null, default empty | Devices that hold a valid token. |
| pending_codes | list of PairingCode | not null, default empty | Unconsumed pairing codes; expired entries are pruned when the next code is minted. |
A missing, unreadable, or malformed devices.json loads as an empty registry rather than raising an error.
Gateway config (jcode_config_types::GatewayConfig)
| Field | Type | Constraints | Description |
|---|---|---|---|
| enabled | bool | default false | Whether the server binds the gateway listener at startup. |
| port | u16 | default 7643 | TCP port to listen on. |
| bind_addr | string | default 0.0.0.0 |
Bind address; a wildcard binds every interface. |
Pairing invite (jcode_base::gateway::control::PairingInvite)
| Field | Type | Constraints | Description |
|---|---|---|---|
| code | string | not null, six decimal digits | The minted pairing code. |
| dial_address | string | not null, host:port |
The address a remote client should dial. |
| uri | string | not null | jcode://pair?host=<host>&port=<port>&code=<code>, rendered as a QR code. |
| gateway_enabled | bool | not null | Whether the gateway is currently enabled, so the UI can warn when the code cannot be used yet. |
API Contracts
The gateway surface is not a REST API, so there is no OpenAPI document for it.
The normative contract is this section, and docs/IOS_APP.md records the same pairing and WebSocket flow for client authors.
CLI surface
jcode pair is a top-level subcommand of the jcode binary.
| Command | Purpose |
|---|---|
jcode pair |
Mint a six-digit pairing code and print it, the connect host, the bind address, and a QR code of the jcode://pair URI. |
jcode pair --list |
List the paired devices with their id, name, pairing time, last-seen time, and a truncated APNsApple Push Notification service token. |
jcode pair --revoke <target> |
Remove the device whose id or exact name equals <target>, and report whether anything matched. |
jcode pair prints a warning when the gateway is disabled, because a code cannot be used until the port is open.
The TUITerminal User Interface exposes the same operations as /remote status, /remote on, /remote off, /remote pair, and /remote revoke <device>.
HTTP and WebSocket endpoints
| Method | Path | Purpose |
|---|---|---|
| GET | /health | Return the server status, the server version, and the gateway flag. |
| POST | /pair | Exchange a pairing code for an auth token. |
| OPTIONS | any | Answer the CORS preflight with the allowed methods and headers. |
| GET (Upgrade) | /ws | Upgrade to a WebSocket that carries the session protocol. |
Error codes shared across endpoints:
| Status | Code | Description |
|---|---|---|
| 400 | INVALID_JSON | The POST /pair body is not valid JSON. |
| 401 | INVALID_PAIRING_CODE | The pairing code is unknown, already consumed, or expired. |
| 401 | MISSING_TOKEN | The upgrade carried neither an Authorization header nor a token query parameter. |
| 401 | MALFORMED_TOKEN | The token is not 64 hexadecimal characters. |
| 401 | CONFLICTING_TOKENS | The header token and the query token are different. |
| 401 | UNKNOWN_TOKEN | The token does not match a paired device, or the device was revoked. |
| 404 | NOT_FOUND | The upgrade path is not /ws, or the HTTP path is unknown. |
POST /pair request and response
Request body:
{
"code": "123456",
"device_id": "<client-supplied device id>",
"device_name": "Jeremy's iPhone",
"apns_token": "<optional push token>"
}
Success response, status 200:
{
"token": "<64 hexadecimal characters>",
"server_name": "jcode",
"server_version": "<version>"
}
The pairing code is consumed by a successful exchange, so it cannot be replayed.
The registry is reloaded from disk before the code is validated, so a code minted by a separate jcode pair invocation is accepted.
WebSocket upgrade handshake
Request:
GET /ws HTTP/1.1
Host: <host>:<port>
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: <key>
Sec-WebSocket-Version: 13
Authorization: Bearer <64 hexadecimal characters>
Browser clients that cannot set headers may instead pass the token as a token= query parameter on the /ws path.
A request that carries both with different values is rejected.
A successful upgrade answers 101 Switching Protocols, and each text frame then carries one newline-delimited JSON request or event. A rejected upgrade answers 401 with a plain-text body that names the reason, and no session stream is created.
Sequences
Pair, then connect
sequenceDiagram
autonumber
actor U as Operator
participant CLI as jcode pair
participant R as DeviceRegistry
participant C as Client
participant G as Gateway
participant S as Server runtime
U->>CLI: jcode pair
CLI->>R: generate_pairing_code()
R-->>CLI: six-digit code, five minute expiry
CLI-->>U: code, connect host, jcode://pair URI and QR
C->>G: POST /pair with code, device_id, device_name
G->>R: load from disk, validate_code(code)
R-->>G: valid, the code is consumed
G->>R: pair_device(), stores a sha256 hash
G-->>C: 200 with token, server_name, server_version
C->>G: GET /ws with Authorization Bearer token
G->>R: load from disk, validate_token(token)
R-->>G: PairedDevice
G->>R: touch_device(token)
G->>S: GatewayClient with stream, device_name, device_id
S-->>C: session events as WebSocket text frames
Revoke, then reconnect
sequenceDiagram
autonumber
actor U as Operator
participant CLI as jcode pair --revoke
participant R as DeviceRegistry
participant C as Client
participant G as Gateway
U->>CLI: jcode pair --revoke "my phone"
CLI->>R: load, drop the matching device, save
CLI-->>U: revoked
C->>G: GET /ws with Authorization Bearer revoked token
G->>R: load from disk, validate_token(token)
R-->>G: no matching device
G-->>C: 401 with a body that asks the client to re-pair
The registry is reloaded from disk on every handshake, so the revocation applies to the next connection attempt without a server restart. A session that is already open when the device is revoked is not closed.
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | Plain TCP with a WebSocket upgrade on port 7643 | Browsers and the iOS app cannot speak the Unix-socket transport, and both can speak WebSocket. |
| Protocol bridging | A virtual socket pair plus a relay task | Reuses the existing client handler, so remote and local clients share one session implementation. |
| Frame format | One newline-delimited JSON request per WebSocket text frame | Matches the Unix-socket wire format exactly, so no second protocol is needed. |
| Authorization point | The token is validated inside the upgrade callback | A refused upgrade returns a real 401 the client can act on, instead of an accepted and then dropped socket that looks like a network fault. |
| Token storage | SHA-256 hash of a 32-byte random token | A leaked devices.json does not leak usable tokens. |
| Pairing code | Six random decimal digits, five minute lifetime, consumed on use | Short enough to read aloud, and stale soon enough that a shoulder-surfed code is worthless. |
| Token transport | Authorization: Bearer preferred, ?token= accepted for browsers |
Browsers cannot set headers on a WebSocket, so both forms are needed; the query form is logged as deprecated. |
| Registry freshness | The registry is reloaded from disk on every handshake and pair request | A revocation from the CLI takes effect without restarting the server. |
| Dial-address resolution | Bind address, then JCODE_GATEWAY_HOST, then Tailscale MagicDNS, then the system hostname |
A wildcard bind address says nothing about how another machine reaches this one. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). encryption | Not provided by the gateway | The gateway is meant to sit on a trusted network such as Tailscale, and the status output warns about a wildcard bind. |
| Control logic in one place | gateway/control.rs is shared by the TUITerminal User Interface, the CLI, and the server runtime |
The TUITerminal User Interface and the CLI cannot drift apart on gateway state, pairing, or revocation. |
Risks and Unknowns
- The gateway speaks plain TCP, so transport confidentiality depends on the network. A wildcard bind that is reachable from the public internet exposes session traffic to anyone who can reach the port.
- The pairing code is six decimal digits, and there is no attempt counter or rate limit on
POST /pair, so a code can be guessed inside its five-minute lifetime. - Revoking a device removes its record, but a session that is already open for that device is not terminated.
- The
?token=query form puts the token in the URL, where intermediaries can log it. The header form is preferred and the query form is logged as deprecated. DeviceRegistry::loadreturns an empty registry whendevices.jsonis unreadable or malformed, which silently drops every pairing instead of failing loudly.- The listener binds at server startup, so enabling the gateway needs a server restart that the tooling does not perform on its own.
- The remote protocol is not versioned. Third-party clients that need a stable, versioned surface are expected to use the harness API instead.
- The trust model is a shared secret that the operator hands to the client, and the code is entered on the client device, so a compromised client device can pair itself within the code lifetime.
Out of Scope
- The versioned harness API bridge:
jcode api-bridge,crates/jcode-harness-api/,crates/jcode-harness-api-server/,crates/jcode-sdk/, andsdk/typescript/. That is a separate feature and is not described here. - The iOS app itself:
ios/, including JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. and JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views.. - TLS termination and transport encryption for the gateway listener.
- Jcode Cloud activation and the managed-host control plane behind
/remote cloud. - The public HTTP API surface of the jcode server.
Test Plan: Remote Client Gateway
Scope
Covers pairing code minting and consumption, device registration and token validation, the WebSocket upgrade authorization path, the newline-delimited JSON bridge, device listing, revocation, the /remote control surface, and the dial-address resolution helper.
Test files that exist for this feature:
crates/jcode-base/src/gateway_tests.rs, mounted asmod gateway_testsfromcrates/jcode-base/src/gateway.rs.- The inline
mod testsblock incrates/jcode-base/src/gateway/control.rs. - The inline
mod testsblock incrates/jcode-tui/src/tui/app/commands_remote.rs. src/cli/commands_tests.rs, for the Tailscale MagicDNS helper that the gateway re-exports.tests/e2e/transport.rs, with the gateway helpers intests/e2e/test_support/mod.rs.
Crates and files with no test coverage for this feature:
crates/jcode-gateway-types/has no test file and no test module. It only holds thePairedDeviceandPairingCodestructs, so its behavior is covered indirectly throughcrates/jcode-base/src/gateway_tests.rs.crates/jcode-base/src/gateway/registry.rsandcrates/jcode-base/src/gateway/auth.rshave no inline test modules. Their behavior is covered fromcrates/jcode-base/src/gateway_tests.rs.- There is no test file for the
jcode pairCLI command itself.run_pair_commandinsrc/cli/commands.rsis not exercised by any test. crates/jcode-app-core/src/server.rsandcrates/jcode-app-core/src/server/runtime.rshave no gateway-specific test file. The gateway startup and accept loop are covered only through the end-to-end scenario.
Out of scope: the versioned harness API bridge, the iOS app, and the Tailscale or network layer itself.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Bearer token parsing | crates/jcode-base/src/gateway_tests.rs (test_parse_bearer_token) |
Bearer <token> is accepted whatever the case of the scheme; Basic, a missing token, and extra parts are rejected |
| TC-2 | Query token parsing | crates/jcode-base/src/gateway_tests.rs (test_parse_query_token) |
The token parameter is extracted from a query string; an empty value and a query without token yield nothing |
| TC-3 | Token shape validation | crates/jcode-base/src/gateway_tests.rs (test_hex_token_validation) |
A 64-character hexadecimal string is accepted; short and non-hexadecimal strings are rejected |
| TC-4 | WebSocket auth extraction and source tracking | crates/jcode-base/src/gateway_tests.rs (test_extract_ws_auth_prefers_header_and_falls_back_to_query) |
The header token wins and is reported as the header source; the query token is used and reported as the query source when there is no header |
| TC-5 | Conflicting auth sources | crates/jcode-base/src/gateway_tests.rs (test_extract_ws_auth_rejects_conflicting_sources) |
A request that carries a different token in the header and in the query string is rejected |
| TC-6 | HTTP header terminator detection | crates/jcode-base/src/gateway_tests.rs (test_find_header_end) |
The offset of the \r\n\r\n terminator is returned; incomplete headers and empty input return nothing |
| TC-7 | Device authorization for a paired token | crates/jcode-base/src/gateway_tests.rs (test_authorize_ws_device_valid_token) |
The paired device name and id are returned for a valid token |
| TC-8 | Device authorization for an unknown or revoked token | crates/jcode-base/src/gateway_tests.rs (test_authorize_ws_device_rejects_unknown_and_revoked_with_401) |
A 401 error response is produced and its body tells the client to re-pair |
| TC-9 | /remote subcommand parsing |
crates/jcode-base/src/gateway/control.rs (mod tests) |
The subcommands, their aliases, case-insensitive input, and the error cases for a missing revoke target and stray arguments parse as documented |
| TC-10 | /remote command boundary |
crates/jcode-base/src/gateway/control.rs (mod tests) |
/remote-release, /remotely, /resume, and unrelated input are not claimed by the parser |
| TC-11 | Gateway status rendering | crates/jcode-base/src/gateway/control.rs (mod tests) |
The status markdown reports the gateway state, the dial address, the paired devices, and the setup guidance for an empty device list |
| TC-12 | Wildcard bind and unknown host warnings | crates/jcode-base/src/gateway/control.rs (mod tests) |
A wildcard bind produces the trusted-network warning, an explicit bind address is used verbatim, and an undeterminable host is flagged |
| TC-13 | Pairing code display format | crates/jcode-base/src/gateway/control.rs (mod tests) |
A six-digit code is grouped as 082 641 for reading aloud |
| TC-14 | Tailscale MagicDNS name parsing | src/cli/commands_tests.rs (test_parse_tailscale_dns_name_trims_trailing_dot, test_parse_tailscale_dns_name_handles_missing_or_empty, test_parse_tailscale_dns_name_invalid_json) |
The trailing dot is trimmed; a missing, blank, or non-JSON payload yields no name |
| TC-15 | /remote parser boundary and help text in the TUITerminal User Interface |
crates/jcode-tui/src/tui/app/commands_remote.rs (mod tests) |
/remote-release is not claimed, and the help text lists every subcommand the parser accepts |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-16 | Pairing code minting, consumption, and single use | crates/jcode-base/src/gateway_tests.rs (test_device_registry_pairing) |
A six-digit code is minted, validates once, is removed from the pending list, and fails on the second attempt |
| TC-17 | Device pairing and token authentication | crates/jcode-base/src/gateway_tests.rs (test_device_registry_token_auth) |
The issued token validates, a wrong token does not, and the device record holds a sha256: hash rather than the token |
| TC-18 | Re-pairing the same device id | crates/jcode-base/src/gateway_tests.rs (test_device_re_pairing) |
The earlier record is replaced, the earlier token stops validating, and the new token validates |
| TC-19 | Gateway enable and disable persistence | crates/jcode-base/src/gateway/control.rs (mod tests) with a temporary JCODE_HOME |
The config file is rewritten with the new value, unrelated settings survive the rewrite, and a no-op toggle reports Unchanged |
| TC-20 | Revocation removes only the named device | crates/jcode-base/src/gateway/control.rs (mod tests) with a temporary JCODE_HOME |
Only the targeted device is removed, the result is persisted, and an unknown target removes nothing |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-21 | WebSocket transport parity with the Unix socket | tests/e2e/transport.rs (test_websocket_transport_matches_unix_socket_for_subscribe_history_message_and_resume) with the helpers in tests/e2e/test_support/mod.rs |
A paired device opens ws://127.0.0.1:<port>/ws with a bearer token, subscribes, sends a message, reads history, and resumes, and the history and resume payloads match the Unix-socket run |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-22 | A pairing code is replayed after it was consumed | The second POST /pair with the same code is refused with 401 and no token is issued |
| TC-23 | A pairing code is used after the five-minute expiry | The code is refused with 401 and no token is issued |
| TC-24 | A WebSocket upgrade carries no token | The upgrade is refused with 401 and the body names the missing token |
| TC-25 | A WebSocket upgrade carries a malformed token | The upgrade is refused with 401 before any session stream is created |
| TC-26 | A WebSocket upgrade carries a revoked device token | The upgrade is refused with 401 and the client is told to re-pair |
| TC-27 | A WebSocket upgrade targets a path other than /ws |
The upgrade is refused with 404 |
| TC-28 | The header token and the query token disagree | The upgrade is refused with 401 |
| TC-29 | The POST /pair body is not valid JSON |
The request is refused with 400 and no token is issued |
| TC-30 | A second client connects while the first is attached | Both clients keep their own session stream and both receive their own events |
| TC-31 | One gateway client disconnects mid-session | The relay tasks stop, the disconnect is logged, and the listener keeps serving the other clients |
| TC-32 | The gateway is disabled while devices are paired | The paired device records are kept, so the devices can reconnect once the gateway is enabled again |
| TC-33 | devices.json is missing, empty, or malformed |
The registry loads as empty instead of failing the gateway |
| TC-34 | A pairing code is minted while expired codes are pending | The expired codes are pruned and only the new code stays pending |
Test Infrastructure
- The gateway unit tests run under
cargo testin thejcode-basecrate, and thejcode-tuiand root-crate tests run in their own crates. - The end-to-end scenario runs under
cargo testin the root crate, in thetests/e2esuite, with aMockProviderand a reserved TCP port. - The end-to-end helper
pair_test_deviceintests/e2e/test_support/mod.rswrites a device record with a known token hash, so the test does not need a real pairing exchange. - The registry helpers in
crates/jcode-base/src/gateway/registry.rspersist to~/.jcode/devices.jsonas a side effect, so the registry tests touch the real jcode home. - The config and revocation tests in
crates/jcode-base/src/gateway/control.rsredirectJCODE_HOMEto a temporary directory and serialize on the shared test environment lock. - The
jcode pairCLI command has no automated test, so its output and its--listand--revokebranches are checked manually. - The edge cases TC-23, TC-24, TC-25, TC-27, TC-29, TC-30, TC-31, TC-32, TC-33, and TC-34 record required behavior that no automated test proves today. In the coverage matrix they are listed as the expected-behavior reference rather than as an automated proof.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall run a WebSocket gateway listener on the configured TCP port, 7643 by default, whenever the gateway is enabled. | TC-19, TC-21 |
| FR-2MustThe system shall mint a random six-digit pairing code that expires five minutes after it is minted, and shall show the operator the code, the address to dial, and a `jcode://pair` URI. | TC-13, TC-16, TC-34 |
| FR-3MustThe system shall exchange a valid pairing code for a per-device auth token over `POST /pair`, and shall persist only a SHA-256 hash of that token. | TC-17, TC-21 |
| FR-4MustThe system shall reject a `POST /pair` request whose code is unknown, already consumed, or expired with HTTP 401, and shall not issue a token. | TC-16, TC-22, TC-23 |
| FR-5MustThe system shall validate the auth token of every WebSocket upgrade against the device registry, and shall reject an unknown, malformed, or revoked token with HTTP 401 during the handshake. | TC-3, TC-7, TC-8, TC-26 |
| FR-6MustThe system shall bridge each authorized WebSocket connection onto the newline-delimited JSON session protocol over a virtual socket pair, so a remote client drives a session exactly like a local client. | TC-21 |
| FR-7MustThe system shall list the paired devices with their id, name, pairing time, and last-seen time. | TC-11, TC-20 |
| FR-8MustThe system shall revoke a paired device by id or by exact name, and a revoked device's token shall be rejected on its next connection attempt. | TC-20, TC-8, TC-26 |
| FR-9MustThe system shall reject a WebSocket upgrade whose path is not `/ws` with HTTP 404. | TC-27 |
| FR-10MustThe system shall serve several remote clients at the same time, giving each client its own session stream. | TC-30 |
| FR-11ShouldThe system shall accept the auth token from an `Authorization: Bearer <token>` header or from a `token=` query parameter, and shall reject a request that carries two different tokens. | TC-1, TC-2, TC-4, TC-5, TC-28 |
| FR-12ShouldThe system shall answer `GET /health` with the server status and version, and shall answer CORS preflight requests so that browser clients can reach the gateway. | none, see TC-6 for the header parsing that the endpoints rely on |
| FR-13ShouldThe system shall resolve the address a remote client should dial, preferring the explicit bind address, then `JCODE_GATEWAY_HOST`, then the Tailscale MagicDNS name, then the system hostname. | TC-12, TC-14 |
| FR-14ShouldThe system shall let an operator enable the gateway, disable the gateway, pair a device, and revoke a device from the TUITerminal User Interface through `/remote`, using the same logic as the `jcode pair` CLI. | TC-9, TC-10, TC-15, TC-19, TC-20 |
| FR-15ShouldThe system shall record the time of the most recent successful connection as the device's last-seen timestamp. | none, see TC-21 for the connection that triggers the update |
| FR-16MayThe system shall send a WebSocket ping every 20 seconds and answer a client ping with a pong, so that idle and broken connections are detected. | none, see TC-31 for the connection lifecycle |
| NFR-1MustA pairing code shall expire five minutes after it is minted and shall be consumed on first successful use, so that a leaked or replayed code cannot mint a second token. | TC-16, TC-22, TC-23 |
| NFR-2MustThe system shall never persist a raw auth token, and shall store only a SHA-256 hash of a 32-byte random token. | TC-17 |
| NFR-3MustThe system shall reject every WebSocket upgrade that carries no token, a malformed token, an unknown token, or a revoked token with HTTP 401, before any session stream is created. | TC-5, TC-7, TC-8, TC-24, TC-25, TC-26 |
| NFR-4MustThe gateway shall rely on the underlying network for transport confidentiality, and the system shall warn the operator when the bind address is a wildcard address. | TC-12 |
| NFR-5ShouldOne failing client shall not stop the gateway listener, and the gateway shall keep serving the remaining clients. | TC-31 |
| NFR-6ShouldThe bridge shall add no framing beyond the newline delimiter, and shall emit a keepalive ping every 20 seconds. | TC-21 |
| NFR-7ShouldThe WebSocket transport shall carry the same newline-delimited JSON protocol as the Unix-socket transport, so that one client implementation works over both. | TC-21 |
| NFR-8ShouldThe system shall log gateway lifecycle events, covering listener start, pairing, connection, disconnection, and revocation, through `crate::logging`. | none, verified by reading the gateway log during a manual run |
requirements
- Should an open WebSocket session be terminated when its device is revoked? Today revocation only blocks new connections.
- Should the gateway terminate TLS itself, or is a trusted network such as Tailscale the intended transport? Today it speaks plain TCP.
- Should
POST /pairrate-limit pairing-code attempts? A six-digit code can be guessed within its five-minute lifetime. - Is the remote protocol meant to be versioned for third-party clients, or is the versioned harness API the surface intended for them? The answer decides whether the remote protocol needs a compatibility policy.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Command Safety Gate
Overview
The command safety gate stands between a model's shell and file-mutation tool calls and the user's data. It is a two-stage cascade: stage 1 is a deterministic, offline classifier that judges a command by its blast radius, and stage 2 turns an ambiguous verdict into a reflection prompt that the model must satisfy with a justification. Catastrophic targets such as the filesystem root, the home directory, credential stores, and device nodes are denied outright, and no justification can unlock them. This feature documents already-implemented code that was reverse-engineered during an SDLC sync, so every requirement below describes behaviour that exists today.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | Confidence that an agent cannot silently destroy their home directory, credentials, or system files |
| Model authors | Refusal text that names the offending target and tells the model what to check before it retries |
| Maintainers | One auditable policy for what a destructive command may touch, backed by adversarial test coverage |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall assess every shell command submitted to the `bash` tool with a deterministic, offline blast-radius assessment before the command is executed. | Must | The system shall assess every shell command submitted to the bash tool with a deterministic, offline blast-radius assessment before the command is executed. |
| FR-2MustThe system shall classify a command by what it would destroy and whether that can be undone, rather than by command name, so that `find -delete`, `shred`, `truncate`, `dd`, and truncating redirects are covered alongside `rm -rf`. | Must | The system shall classify a command by what it would destroy and whether that can be undone, rather than by command name, so that find -delete, shred, truncate, dd, and truncating redirects are covered alongside rm -rf. |
| FR-3MustThe system shall deny a catastrophic target outright, and no justification shall ever unlock it. | Must | The system shall deny a catastrophic target outright, and no justification shall ever unlock it. |
| FR-4MustThe system shall treat the filesystem root, protected system paths and their contents, the user's home directory, credential stores and their contents, and raw device nodes as catastrophic targets. | Must | The system shall treat the filesystem root, protected system paths and their contents, the user's home directory, credential stores and their contents, and raw device nodes as catastrophic targets. |
| FR-5MustThe system shall convert a `Confirm` verdict into a reflection prompt that the model must satisfy by re-issuing the call with a substantive `justification` naming the user request the command serves. | Must | The system shall convert a Confirm verdict into a reflection prompt that the model must satisfy by re-issuing the call with a substantive justification naming the user request the command serves. |
| FR-6MustThe system shall refuse a blind retry of a held command, so that repeating the identical call without a justification produces the same refusal. | Must | The system shall refuse a blind retry of a held command, so that repeating the identical call without a justification produces the same refusal. |
| FR-7MustThe system shall escalate to `Confirm` whenever the set of affected paths cannot be determined statically, including unresolved variables, command substitution, globs, operands supplied by a pipe, opaque wrappers, and inline shell scripts. | Must | The system shall escalate to Confirm whenever the set of affected paths cannot be determined statically, including unresolved variables, command substitution, globs, operands supplied by a pipe, opaque wrappers, and inline shell scripts. |
| FR-8MustThe system shall apply the same classifier to `apply_patch` deletion targets, and shall refuse to delete a protected path. | Must | The system shall apply the same classifier to apply_patch deletion targets, and shall refuse to delete a protected path. |
| FR-9ShouldThe system shall unwrap command wrappers such as `sudo`, `env`, `nice`, `ionice`, `timeout`, `nohup`, `xargs`, `command`, and `exec`, so that the destructive program underneath is the one that gets classified. | Should | The system shall unwrap command wrappers such as sudo, env, nice, ionice, timeout, nohup, xargs, command, and exec, so that the destructive program underneath is the one that gets classified. |
| FR-10ShouldThe system shall split a command line into segments on shell separators and assess each segment independently, so that chaining cannot launder a catastrophic command. | Should | The system shall split a command line into segments on shell separators and assess each segment independently, so that chaining cannot launder a catastrophic command. |
| FR-11ShouldThe system shall treat a truncating redirect to a protected path as a destructive write, and shall treat an append (`>>`) and the standard sinks (`/dev/null`, `/dev/stdout`, `/dev/stderr`, `NUL`) as non-destructive. | Should | The system shall treat a truncating redirect to a protected path as a destructive write, and shall treat an append (>>) and the standard sinks (/dev/null, /dev/stdout, /dev/stderr, NUL) as non-destructive. |
| FR-12ShouldThe system shall let routine in-project cleanup run without a reflection turn, so that the gate does not train users to bypass it. | Should | The system shall let routine in-project cleanup run without a reflection turn, so that the gate does not train users to bypass it. |
| FR-13ShouldThe system shall apply the gate at the single `Tool::execute` chokepoint of the `bash` tool, before background dispatch, so that foreground, background, and batch dispatch paths cannot bypass it. | Should | The system shall apply the gate at the single Tool::execute chokepoint of the bash tool, before background dispatch, so that foreground, background, and batch dispatch paths cannot bypass it. |
| FR-14ShouldThe system shall record each gate decision in the log, distinguishing a denial from a hold for justification. | Should | The system shall record each gate decision in the log, distinguishing a denial from a hold for justification. |
| FR-15MayThe system shall expose the protected path lists (home subpaths, credential subpaths, system paths, and recursively protected system paths) so that other tools and documentation can reuse the same policy. | May | The system shall expose the protected path lists (home subpaths, credential subpaths, system paths, and recursively protected system paths) so that other tools and documentation can reuse the same policy. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustThe assessment shall run entirely offline, with no model call and no network call, and shall complete in under 5 ms for a typical command line. | Must | Performance | The assessment shall run entirely offline, with no model call and no network call, and shall complete in under 5 ms for a typical command line. |
| NFR-2MustThe system shall reason only from the command text and path strings, and shall not read, log, or transmit the contents of any file that a command names. | Must | Security | The system shall reason only from the command text and path strings, and shall not read, log, or transmit the contents of any file that a command names. |
| NFR-3MustThe assessment shall be total: any input, including empty, malformed, or garbage input, shall yield a verdict rather than an error or a panic. | Must | Reliability | The assessment shall be total: any input, including empty, malformed, or garbage input, shall yield a verdict rather than an error or a panic. |
| NFR-4MustThe same command string and the same risk context shall always produce the same verdict, independent of wall-clock time, randomness, or network state. | Must | Determinism | The same command string and the same risk context shall always produce the same verdict, independent of wall-clock time, randomness, or network state. |
| NFR-5MustThe classifier crate shall declare no runtime dependency and shall make no network call, so that the safety decision cannot be subverted by an upstream service. | Must | Security | The classifier crate shall declare no runtime dependency and shall make no network call, so that the safety decision cannot be subverted by an upstream service. |
| NFR-6ShouldA refusal shall name the offending path or target, shall ask the model to check the command against the user's actual request, and shall tell the model to ask the user when it is unsure. | Should | Usability | A refusal shall name the offending path or target, shall ask the model to check the command against the user's actual request, and shall tell the model to ask the user when it is unsure. |
| NFR-7ShouldThe safe path shall add no model round trip and no extra tool call, so an ordinary command costs only the assessment itself. | Should | Performance | The safe path shall add no model round trip and no extra tool call, so an ordinary command costs only the assessment itself. |
| NFR-8ShouldThe classifier shall be consumable by any tool without pulling in the agent runtime, so the destructive-command policy has one source of truth. | Should | Architecture | The classifier shall be consumable by any tool without pulling in the agent runtime, so the destructive-command policy has one source of truth. |
Constraints
- The gate is defense in depth, not a sandbox.
- The classifier is a static parser: it does not execute, expand, or resolve the command it is given.
- Path resolution is lexical, so it never touches the filesystem and is not symlink-aware.
- The
bashtool on Windows runscmd.exe, whose syntax the POSIX-shaped classifier does not model. - The gate must not read file contents, so it can only reason about command text and path strings.
- The policy is deliberately biased toward recall, because a false positive costs one reflection turn while a false negative costs the user's data.
Acceptance Criteria
Every FR and NFR shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
Acceptance criteria verify how a requirement is proven done, they do not restate it.
Write concrete, scenario-based criteria (happy path, edge cases and error states where applicable).
Write each criterion as a fenced gherkin block with a tag matching its requirement ID, so the criteria are parseable and later executable via BDD tooling (pytest-bdd, cucumber).
Multiple scenarios per requirement are allowed; tag each with the requirement ID.
-
FR-1MustThe system shall assess every shell command submitted to the `bash` tool with a deterministic, offline blast-radius assessment before the command is executed.
gherkin @FR-1MustThe system shall assess every shell command submitted to the `bash` tool with a deterministic, offline blast-radius assessment before the command is executed. Scenario: Command is assessed before any process starts Given a tool call to the `bash` tool carrying the command `rm -rf /home/u` When the tool call is executed Then the assessment runs before a process is spawned And the command does not execute -
FR-2MustThe system shall classify a command by what it would destroy and whether that can be undone, rather than by command name, so that `find -delete`, `shred`, `truncate`, `dd`, and truncating redirects are covered alongside `rm -rf`.
gherkin @FR-2MustThe system shall classify a command by what it would destroy and whether that can be undone, rather than by command name, so that `find -delete`, `shred`, `truncate`, `dd`, and truncating redirects are covered alongside `rm -rf`. Scenario: Destructive verbs other than rm are covered Given a working directory of `/home/u/proj` and a home directory of `/home/u` When `find /home/u -delete` is assessed Then the verdict is Catastrophic And the same holds for `shred`, `truncate`, `dd`, and a truncating redirect to a protected path -
FR-3MustThe system shall deny a catastrophic target outright, and no justification shall ever unlock it.
gherkin @FR-3MustThe system shall deny a catastrophic target outright, and no justification shall ever unlock it. Scenario: A catastrophic verdict is unconditional Given a command whose assessment level is Catastrophic When the gate is evaluated with an elaborate justification naming the user's request Then the outcome is Deny And the reason states that the command cannot be confirmed -
FR-4MustThe system shall treat the filesystem root, protected system paths and their contents, the user's home directory, credential stores and their contents, and raw device nodes as catastrophic targets.
gherkin @FR-4MustThe system shall treat the filesystem root, protected system paths and their contents, the user's home directory, credential stores and their contents, and raw device nodes as catastrophic targets. Scenario: Protected targets are catastrophic and ordinary paths are not Given a home directory of `/home/u` When `/`, `/etc/passwd`, `/home/u`, `~/.ssh/id_ed25519`, and `/dev/sda` are classified Then each one is classified as Catastrophic And `/home/u/proj/src/old.rs` is not -
FR-5MustThe system shall convert a `Confirm` verdict into a reflection prompt that the model must satisfy by re-issuing the call with a substantive `justification` naming the user request the command serves.
gherkin @FR-5MustThe system shall convert a `Confirm` verdict into a reflection prompt that the model must satisfy by re-issuing the call with a substantive `justification` naming the user request the command serves. Scenario: An ambiguous verdict produces a reflection prompt Given the command `rm -rf $TARGET` When the gate is evaluated with no justification Then the outcome is Reflect with a prompt that names the target And the prompt asks which user request requires the deletion -
FR-6MustThe system shall refuse a blind retry of a held command, so that repeating the identical call without a justification produces the same refusal.
gherkin @FR-6MustThe system shall refuse a blind retry of a held command, so that repeating the identical call without a justification produces the same refusal. Scenario: A blind retry is refused again Given a command that the gate held for justification When the identical call is issued again with no justification Then the same refusal is returned And no path is deleted -
FR-7MustThe system shall escalate to `Confirm` whenever the set of affected paths cannot be determined statically, including unresolved variables, command substitution, globs, operands supplied by a pipe, opaque wrappers, and inline shell scripts.
gherkin @FR-7MustThe system shall escalate to `Confirm` whenever the set of affected paths cannot be determined statically, including unresolved variables, command substitution, globs, operands supplied by a pipe, opaque wrappers, and inline shell scripts. Scenario: An unresolvable target escalates Given the command `rm -rf $TARGET` When it is assessed Then the verdict is at least Confirm -
FR-8MustThe system shall apply the same classifier to `apply_patch` deletion targets, and shall refuse to delete a protected path.
gherkin @FR-8MustThe system shall apply the same classifier to `apply_patch` deletion targets, and shall refuse to delete a protected path. Scenario: apply_patch refuses a protected deletion Given a file at `$HOME/.ssh/id_ed25519` When an apply_patch call deletes that file by absolute path Then the tool reports a refusal And the file still exists -
FR-9ShouldThe system shall unwrap command wrappers such as `sudo`, `env`, `nice`, `ionice`, `timeout`, `nohup`, `xargs`, `command`, and `exec`, so that the destructive program underneath is the one that gets classified.
gherkin @FR-9ShouldThe system shall unwrap command wrappers such as `sudo`, `env`, `nice`, `ionice`, `timeout`, `nohup`, `xargs`, `command`, and `exec`, so that the destructive program underneath is the one that gets classified. Scenario: A wrapper does not hide the destructive program Given the command `sudo env nice -n 5 rm -rf ~` When it is assessed Then the verdict is Catastrophic -
FR-10ShouldThe system shall split a command line into segments on shell separators and assess each segment independently, so that chaining cannot launder a catastrophic command.
gherkin @FR-10ShouldThe system shall split a command line into segments on shell separators and assess each segment independently, so that chaining cannot launder a catastrophic command. Scenario: Chaining does not launder a catastrophic command Given the command `echo starting && rm -rf ~` When it is assessed Then the verdict is Catastrophic -
FR-11ShouldThe system shall treat a truncating redirect to a protected path as a destructive write, and shall treat an append (`>>`) and the standard sinks (`/dev/null`, `/dev/stdout`, `/dev/stderr`, `NUL`) as non-destructive.
gherkin @FR-11ShouldThe system shall treat a truncating redirect to a protected path as a destructive write, and shall treat an append (`>>`) and the standard sinks (`/dev/null`, `/dev/stdout`, `/dev/stderr`, `NUL`) as non-destructive. Scenario: Only truncation counts as a destructive write Given the command `echo bad > /etc/passwd` When it is assessed Then the verdict is Catastrophic And the command `echo line >> /home/u/other/log.txt` runs immediately -
FR-12ShouldThe system shall let routine in-project cleanup run without a reflection turn, so that the gate does not train users to bypass it.
gherkin @FR-12ShouldThe system shall let routine in-project cleanup run without a reflection turn, so that the gate does not train users to bypass it. Scenario: Routine in-project cleanup is not interrupted Given the command `rm -rf target` inside the working directory When it is assessed Then the verdict runs immediately without a reflection turn -
FR-13ShouldThe system shall apply the gate at the single `Tool::execute` chokepoint of the `bash` tool, before background dispatch, so that foreground, background, and batch dispatch paths cannot bypass it.
gherkin @FR-13ShouldThe system shall apply the gate at the single `Tool::execute` chokepoint of the `bash` tool, before background dispatch, so that foreground, background, and batch dispatch paths cannot bypass it. Scenario: Background dispatch is gated Given a bash tool call with `run_in_background` set to true and the command `rm -rf $HOME` When the tool call is executed Then the call fails with a refusal And the home directory still exists -
FR-14ShouldThe system shall record each gate decision in the log, distinguishing a denial from a hold for justification.
gherkin @FR-14ShouldThe system shall record each gate decision in the log, distinguishing a denial from a hold for justification. Scenario: Gate decisions are logged Given a bash tool call that the gate denies When the tool call is executed Then a denial is written to the log And a command that is only held for justification is logged as a hold -
FR-15MayThe system shall expose the protected path lists (home subpaths, credential subpaths, system paths, and recursively protected system paths) so that other tools and documentation can reuse the same policy.
gherkin @FR-15MayThe system shall expose the protected path lists (home subpaths, credential subpaths, system paths, and recursively protected system paths) so that other tools and documentation can reuse the same policy. Scenario: The protected path lists are reusable Given the protected path policy When the home subpaths, credential subpaths, system paths, and recursively protected system paths are read Then each list is non-empty and contains the expected entries -
NFR-1MustThe assessment shall run entirely offline, with no model call and no network call, and shall complete in under 5 ms for a typical command line.
gherkin @NFR-1MustThe assessment shall run entirely offline, with no model call and no network call, and shall complete in under 5 ms for a typical command line. Scenario: The assessment is offline and fast Given a typical command line of a few hundred characters When it is assessed Then no model call and no network call is made And the assessment completes in under 5 ms -
NFR-2MustThe system shall reason only from the command text and path strings, and shall not read, log, or transmit the contents of any file that a command names.
gherkin @NFR-2MustThe system shall reason only from the command text and path strings, and shall not read, log, or transmit the contents of any file that a command names. Scenario: File contents never reach the gate Given a command that names an existing file When it is assessed and the refusal is produced Then the file is not read And neither the refusal text nor the log records the file contents -
NFR-3MustThe assessment shall be total: any input, including empty, malformed, or garbage input, shall yield a verdict rather than an error or a panic.
gherkin @NFR-3MustThe assessment shall be total: any input, including empty, malformed, or garbage input, shall yield a verdict rather than an error or a panic. Scenario: Garbage input still yields a verdict Given the command strings ``, ` `, `'`, `\`, `;;;`, `&&`, and `rm -rf "unterminated` When each one is assessed Then each one produces an assessment rather than an error or a panic -
NFR-4MustThe same command string and the same risk context shall always produce the same verdict, independent of wall-clock time, randomness, or network state.
gherkin @NFR-4MustThe same command string and the same risk context shall always produce the same verdict, independent of wall-clock time, randomness, or network state. Scenario: The same input always yields the same verdict Given a command string and a risk context When it is assessed twice Then both verdicts are identical -
NFR-5MustThe classifier crate shall declare no runtime dependency and shall make no network call, so that the safety decision cannot be subverted by an upstream service.
gherkin @NFR-5MustThe classifier crate shall declare no runtime dependency and shall make no network call, so that the safety decision cannot be subverted by an upstream service. Scenario: The classifier has no runtime dependencies Given the `jcode-command-risk` crate When its dependency list is inspected Then it declares no runtime dependency And the gate makes no network call -
NFR-6ShouldA refusal shall name the offending path or target, shall ask the model to check the command against the user's actual request, and shall tell the model to ask the user when it is unsure.
gherkin @NFR-6ShouldA refusal shall name the offending path or target, shall ask the model to check the command against the user's actual request, and shall tell the model to ask the user when it is unsure. Scenario: The refusal is actionable Given a command that the gate held When the refusal text is produced Then it names the offending target And it asks the model to check the command against the user's actual request and to ask the user when unsure -
NFR-7ShouldThe safe path shall add no model round trip and no extra tool call, so an ordinary command costs only the assessment itself.
gherkin @NFR-7ShouldThe safe path shall add no model round trip and no extra tool call, so an ordinary command costs only the assessment itself. Scenario: The safe path adds no round trip Given a command that is classified Safe When it is executed Then the tool runs it directly with no additional model turn -
NFR-8ShouldThe classifier shall be consumable by any tool without pulling in the agent runtime, so the destructive-command policy has one source of truth.
gherkin @NFR-8ShouldThe classifier shall be consumable by any tool without pulling in the agent runtime, so the destructive-command policy has one source of truth. Scenario: The policy has one source of truth Given the `jcode-command-risk` crate When another tool needs a destructive-command policy Then it can depend on the crate without pulling in the agent runtime
Conflicts
None identified.
Open Questions
- Should the classifier learn
cmd.exesyntax so the gate is equally effective on the Windows build of thebashtool? - Should the latency budget in NFR-1MustThe assessment shall run entirely offline, with no model call and no network call, and shall complete in under 5 ms for a typical command line. be pinned by a benchmark so that a future refactor cannot silently make the safe path expensive?
- Should the protected path set be user-configurable, so that a home directory laid out differently from the defaults is still protected?
Specification: Command Safety Gate
Overview
The command safety gate is a two-stage cascade implemented in the dependency-free jcode-command-risk crate and wired into the bash and apply_patch tools.
Stage 1 is assess(command, &RiskContext), a deterministic offline parser that classifies a command by blast radius and returns a RiskAssessment carrying a RiskLevel of Safe, Low, Confirm, or Catastrophic.
Stage 2 is gate(&assessment, &Justification), which turns a Confirm verdict into a Reflect outcome carrying a reflection prompt, and turns a Catastrophic verdict into an unconditional Deny.
The bash tool calls the gate at the single Tool::execute chokepoint before any process is spawned, and the apply_patch tool consults the same path policy for the catastrophic tier when deleting files.
Architecture
model tool call
|
+----------------+----------------+
| |
bash tool apply_patch tool
| |
v v
+------------------+ +------------------+
| bash.rs | | apply_patch.rs |
| Tool::execute | | DeleteFile hunk |
| (chokepoint) | +------------------+
+------------------+ |
| | resolved absolute path
| command + justification v
| +-----------------------------------+
| | jcode_command_risk:: |
| | is_catastrophic_target() |
| | (catastrophic tier only) |
| +-----------------------------------+
v
+--------------------------------+
| bash_destructive_gate.rs |
| destructive_command_refusal()|
| bash_parameters_schema() |
+--------------------------------+
|
v
+---------------------------------------------------------------+
| crates/jcode-command-risk |
| |
| stage 1 assess(command, &RiskContext) -> RiskAssessment |
| tokenize.rs split_segments, embedded_ |
| substitutions, Token flags |
| paths.rs expand, classify_target, |
| is_catastrophic_target |
| |
| stage 2 gate(&assessment, &Justification) -> GateOutcome |
+---------------------------------------------------------------+
| | |
Allow | Reflect {prompt} Deny {reason}
v v v
run the return the return the refusal
command prompt to and log a warning
the model
Data Models
Risk level
| Variant | Order | Constraints | Description |
|---|---|---|---|
Safe |
0 | runs immediately | No destructive potential was detected. |
Low |
1 | runs immediately | Destructive but bounded, typically inside the working directory or a temp directory. |
Confirm |
2 | never runs immediately | The destructive target cannot be determined statically, so a justification is required. |
Catastrophic |
3 | absolute deny | The target is the filesystem root, the home directory, a credential store, or a device node. |
- The variants are totally ordered, and the assessment takes the maximum over its findings.
runs_immediatelyis true forSafeandLow.is_absolute_denyis true only forCatastrophic.
Risk finding
| Field | Type | Constraints | Description |
|---|---|---|---|
level |
RiskLevel |
not null | The severity contributed by this finding. |
reason |
String |
not null, human readable | The explanation shown to the model verbatim. |
target |
Option<String> |
none | The concrete path or argument that triggered the finding. |
Risk assessment
| Field | Type | Constraints | Description |
|---|---|---|---|
level |
RiskLevel |
not null, maximum of the finding levels | The overall verdict for one command. |
findings |
Vec<RiskFinding> |
empty when the level is Safe |
The individual reasons the command was flagged. |
explanation()renders the findings as a bullet list, each line ending with the target when one is present.
Risk context
| Field | Type | Constraints | Description |
|---|---|---|---|
working_dir |
Option<PathBuf> |
none | The working directory of the tool call, used to judge bounded targets. |
home_dir |
Option<PathBuf> |
none | The user's home directory, read from HOME by RiskContext::from_env. |
scratch_dir |
Option<PathBuf> |
none | The dedicated scratch directory, read from JCODE_SCRATCH_DIR. |
RiskContext::from_envfillshome_dirandscratch_dirfrom the environment.- The
bashgate overridesscratch_dirwith the tool's own scratch directory on non-Windows hosts, so the assessed path is the path the child shell receives.
Gate outcome
| Variant | Payload | Description |
|---|---|---|
Allow |
none | Run the command as issued. |
Reflect |
prompt: String |
Refuse this attempt and make the model justify itself first. |
Deny |
reason: String |
Refuse permanently, because no justification can unlock it. |
Justification
| Field | Type | Constraints | Description |
|---|---|---|---|
text |
Option<String> |
none | The model's account of which user request the command serves. |
is_substantiverequires at least 25 trimmed characters and rejects a bare affirmation such asyes,ok,proceed, orgo ahead.- The bar is deliberately low: the goal is to force a reflection turn, not to grade prose.
Bash tool schema surface
| Property | Type | Required | Description |
|---|---|---|---|
command |
string | yes | The bash command to execute. |
intent |
string | no | The intent annotation shared by the tool suite. |
timeout |
integer | no | Timeout in milliseconds. |
run_in_background |
boolean | no | Run in the background with progress reporting. |
notify |
boolean | no | Notify on completion. |
wake |
boolean | no | Wake on completion. |
stall_wake_seconds |
integer | no | Wake delay for a background job that goes quiet. |
justification |
string | no | Only when re-issuing a command the destructive gate refused. Explains which user request it serves. |
- The
justificationfield lives in the same module as the gate so the schema and the policy that reads it stay in sync. - An explicit
nullforjustificationis accepted and treated as absent, matching the other optional arguments.
API Contracts
This feature exposes no HTTP or RPC surface.
The contract is the Rust API below, implemented in crates/jcode-command-risk and consumed from crates/jcode-app-core.
| Function | Module | Purpose |
|---|---|---|
assess(command: &str, ctx: &RiskContext) -> RiskAssessment |
jcode_command_risk |
Stage 1, classify a shell command by blast radius. |
gate(assessment: &RiskAssessment, justification: &Justification) -> GateOutcome |
jcode_command_risk |
Stage 2, decide whether to allow, hold for reflection, or deny. |
is_catastrophic_target(path: &Path, ctx: &RiskContext) -> bool |
jcode_command_risk |
The single most important predicate, exposed so it can be tested and reused in isolation. |
classify_target(expanded: &Path, raw: &str, recursive: bool, ctx: &RiskContext) -> Option<RiskFinding> |
jcode_command_risk |
Classify one resolved target into a risk level. |
expand(raw: &str, ctx: &RiskContext) -> PathBuf |
jcode_command_risk |
Resolve ~, $HOME, and relative paths lexically, without touching the filesystem. |
destructive_command_refusal(command: &str, justification: Option<&str>, working_dir: Option<PathBuf>) -> Option<String> |
jcode_app_core::tool::bash |
The seam that returns refusal text, or None when the command may run. |
Failure modes:
| Condition | Behaviour |
|---|---|
| Malformed or garbage command text | A verdict is still produced, never an error. |
HOME unset on the host |
The system-path tier still applies, and the home tier is skipped. |
| The home directory is reassigned inside the command | The trusted protected paths still apply and the command is held. |
| A catastrophic target | Denied unconditionally, with no justification path. |
Sequences
Allow flow
sequenceDiagram
autonumber
participant M as Model
participant B as bash tool
participant G as jcode_command_risk
participant S as Shell
M->>B: bash(command)
B->>G: assess(command, ctx)
G-->>B: RiskAssessment(level=Safe or Low)
B->>G: gate(assessment, justification)
G-->>B: GateOutcome::Allow
B->>S: spawn the command
S-->>B: output
B-->>M: tool output
Confirm flow
sequenceDiagram
autonumber
participant M as Model
participant B as bash tool
participant G as jcode_command_risk
participant S as Shell
M->>B: bash(command) with no justification
B->>G: assess(command, ctx)
G-->>B: RiskAssessment(level=Confirm)
B->>G: gate(assessment, Justification::default)
G-->>B: GateOutcome::Reflect(prompt)
B-->>M: refusal text naming the target
M->>B: bash(command) with justification
B->>G: gate(assessment, Justification(text))
G-->>B: GateOutcome::Allow
B->>S: spawn the command
S-->>B: output
B-->>M: tool output
Deny flow
sequenceDiagram
autonumber
participant M as Model
participant B as bash tool
participant G as jcode_command_risk
participant S as Shell
M->>B: bash(command)
B->>G: assess(command, ctx)
G-->>B: RiskAssessment(level=Catastrophic)
B->>G: gate(assessment, justification)
G-->>B: GateOutcome::Deny(reason)
B-->>M: refusal stating the command cannot be confirmed
Note over B,S: No process is spawned, and no justification unlocks it
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Classify by blast radius, not by command name | Ask what the command destroys and whether it can be undone | A denylist of rm -rf misses find -delete, shred, truncate, dd, and >file. |
| Stage 1 is deterministic and offline | Pure lexical parsing with no model call and no network call | It costs nothing on the overwhelmingly common safe path, and the verdict cannot be talked around by a remote service. |
| Stage 2 is a reflection prompt, not a second model | The harness refuses once and hands back a structured prompt | An LLM judge is expensive, adds latency to every borderline call, and can be talked around by the same reasoning that produced the command. |
| The refusal is not satisfiable by repetition | The model must supply a justification naming the user request |
This separates the gate from a "run it twice" speed bump that an agent defeats reflexively. |
| The catastrophic tier is absolute and path-based | A small set of protected paths, compared after normalization | The one protection that cannot be argued around must not depend on correctly parsing the command. |
| Credential stores are protected recursively, config roots are matched exactly | ~/.ssh/id_ed25519 is protected, ~/.config/app/settings.toml is not |
Destroying a single private key is as damaging as destroying the directory, while individual config files are edited all day. |
/home and /Users are not recursively protected |
Only the exact roots, plus the user's own home directory | A user's own project lives under those roots, so a recursive rule would block ordinary work. |
| Ambiguity escalates rather than allows | Unknown target, piped operands, opaque wrapper, or inline script all yield Confirm |
A false positive costs one reflection turn, a false negative costs the user's data. |
| Wrappers are unwrapped before classification | sudo, env, nice, timeout, xargs, command, exec, and similar are stripped |
Otherwise any common prefix is a complete bypass of the gate. |
| Path resolution is lexical | expand and normalize never touch the filesystem |
The classifier stays total, cannot be slowed down by a hostile argument, and works on paths that do not exist. |
The gate lives at the single Tool::execute chokepoint |
The check runs before background dispatch | Every other caller, including batch, dispatches through Tool::execute, so there is exactly one place to get right. |
apply_patch consults only the catastrophic tier |
Ordinary file deletes remain the tool's normal job | The bash gate does not cover the patch path, so the absolute deny is duplicated there. |
| The classifier lives in its own crate with no runtime dependencies | jcode-command-risk |
Any tool can adopt the policy without pulling in the agent runtime. |
| The gate records decisions in the log | A warning for a denial, an info line for a hold | Operators need to see what was blocked and what was held. |
Risks and Unknowns
- Static parsing is defeatable by a determined command such as
sh -c "$(printf ...)", so the gate is defense in depth and not a sandbox. - The
bashtool on Windows runscmd.exe, and the classifier models POSIX shell syntax, so Windows-specific destructive verbs are not classified. - Path normalization is not symlink-aware, so a symlink pointing outside the working directory is not resolved before the comparison.
- The protected path set is hardcoded, so a home directory laid out differently from the defaults is not protected.
- No benchmark harness pins the latency budget in NFR-1MustThe assessment shall run entirely offline, with no model call and no network call, and shall complete in under 5 ms for a typical command line., so a future refactor could make the safe path expensive without a test failing.
- A
Confirmcommand with a plausible but wrong justification still runs, because the gate forces a reflection turn rather than proving intent. - The repository document
docs/SAFETY_SYSTEM.mddescribes the ambient-mode permission system, which is a separate subsystem and does not document this gate. - The gate module's own tests are compiled only on non-Windows hosts, so the Windows build has no direct coverage of the policy seam.
Out of Scope
- The rest of the tool suite beyond
bashandapply_patch, which is documented as a separate feature. - The ambient-mode permission system described in
docs/SAFETY_SYSTEM.md. - Sandboxing, containerization, or any OS-level confinement of the agent's processes.
- A second, model-based judge for destructive commands.
- The opt-in external
pre_toolhook thatToolRegistry::executeoffers. - Classification of Windows
cmd.exedestructive syntax. - Making the protected path set user-configurable.
Test Plan: Command Safety Gate
Scope
Tests the two-stage command safety gate: the deterministic blast-radius classifier in crates/jcode-command-risk and the wiring of that classifier into the bash and apply_patch tools.
Out of scope: the rest of the tool suite, the ambient-mode permission system described in docs/SAFETY_SYSTEM.md, and any OS-level confinement of the agent's processes.
Test files referenced below, all verified to exist in the repository:
crates/jcode-command-risk/src/assess_tests.rscrates/jcode-command-risk/src/gate_tests.rscrates/jcode-command-risk/src/paths_tests.rscrates/jcode-command-risk/src/tokenize_tests.rscrates/jcode-app-core/src/tool/bash_destructive_gate.rs(inlinemod tests)crates/jcode-app-core/src/tool/bash_tests.rscrates/jcode-app-core/src/tool/apply_patch_tests.rs
Unit Tests
The classifier crate is exercised through pure functions, so the assessment tests are unit tests at the crate boundary.
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Blast-radius classification rather than command name | crates/jcode-command-risk/src/assess_tests.rs (non_rm_destructive_tools_are_covered, deleting_concrete_paths_outside_the_project_runs_immediately, concrete_truncating_redirect_outside_cwd_runs_immediately) |
find /home/u -delete is Catastrophic, dd if=/dev/zero of=/dev/sda does not run immediately, a concrete out-of-workspace delete is Low |
| TC-2 | The catastrophic target set | crates/jcode-command-risk/src/assess_tests.rs (the_issue_604_command_is_blocked_outright, root_destruction_is_blocked_outright, credential_theft_or_destruction_is_blocked, files_inside_system_directories_are_protected_too) |
Every spelling of the home directory, /, /etc, /usr, ~/.ssh, ~/.gnupg, ~/.aws, and files inside the recursively protected system paths are Catastrophic |
| TC-3 | Chaining and separators | crates/jcode-command-risk/src/assess_tests.rs (chaining_does_not_bypass_the_gate, no_separator_launders_a_catastrophic_command, the_worst_finding_in_a_chain_wins, shell_constructs_do_not_hide_catastrophic_commands) |
No separator form (&&, ||, ;, |, newline) launders a catastrophic command, and the worst finding in a chain wins |
| TC-4 | Routine in-project work is not interrupted | crates/jcode-command-risk/src/assess_tests.rs (routine_cleanup_inside_the_project_is_not_blocked, no_routine_project_command_triggers_a_prompt, issue_725_read_only_and_bounded_commands_run_immediately) |
Cleanup inside the project, bounded globs, and read-only commands all run immediately |
| TC-5 | Unknown targets escalate | crates/jcode-command-risk/src/assess_tests.rs (runtime_computed_targets_require_justification, destructive_command_without_a_visible_target_escalates) |
An unresolved variable, a command substitution, and a destructive verb with no visible target all reach at least Confirm |
| TC-6 | Wrapper unwrapping | crates/jcode-command-risk/src/assess_tests.rs (wrapper_commands_do_not_hide_the_real_program, nested_wrappers_are_unwrapped_all_the_way_down, a_wrapper_hiding_an_unparseable_payload_escalates, ordinary_wrapped_commands_still_run_immediately, wrapper_value_flags_and_unbounded_globs_remain_guarded) |
The destructive program under any wrapper is Catastrophic, an unparseable payload escalates, and ordinary wrapped commands stay quiet |
| TC-7 | Inline shell scripts and command substitution | crates/jcode-command-risk/src/assess_tests.rs (inline_shell_scripts_are_assessed_not_skipped, issue_1753_substitutions_are_assessed_like_top_level_commands, issue_1753_inert_text_stays_safe) |
sh -c "rm -rf ~" and $(rm -rf ~) are Catastrophic, while quoted heredoc bodies and single-quoted text stay Safe |
| TC-8 | Operands supplied by a pipe | crates/jcode-command-risk/src/assess_tests.rs (piped_deletes_cannot_launder_their_targets) |
find ~ -type f \| xargs rm -rf does not run immediately, because the affected set is invisible to the parser |
| TC-9 | find actions |
crates/jcode-command-risk/src/assess_tests.rs (read_only_find_actions_do_not_delete_search_roots, find_mutating_and_unknown_actions_remain_protected, find_output_actions_write_only_their_destinations) |
Read-only -exec payloads are Safe, mutating or unknown payloads are held or denied, and -fprint writes only its destination |
| TC-10 | Redirects and sinks | crates/jcode-command-risk/src/assess_tests.rs (appending_is_not_treated_as_destructive, harmless_command_operands_are_not_redirect_targets, safe_redirect_sink_does_not_make_explicit_deletion_safe, read_only_find_with_stderr_redirect_is_safe, read_only_early_returns_preserve_redirect_checks) |
Only > marks a truncating target, >> and /dev/null do not, and a redirect to a protected path is still caught after a read-only early return |
| TC-11 | Environment printing and command lookup | crates/jcode-command-risk/src/assess_tests.rs (environment_printing_and_command_lookup_are_read_only, reassignment_does_not_override_trusted_protection, env_split_strings_cannot_be_mistaken_for_printing) |
env, env -u, and command -v are Safe, a HOME= reassignment does not weaken the protected paths, and env -S is held |
| TC-12 | Heredoc bodies are data, not shell source | crates/jcode-command-risk/src/assess_tests.rs (issue_922_heredoc_payload_does_not_trip_the_gate, heredoc_inside_double_quoted_command_substitution_is_data) |
A heredoc body that mentions rm does not trip the gate, while a real command after the terminator is still assessed |
| TC-13 | Assessment totality, ordering, and explanations | crates/jcode-command-risk/src/assess_tests.rs (assessment_is_total_over_garbage_input, severity_ordering_is_monotonic, catastrophic_cannot_be_unlocked_but_confirm_can, explanation_names_the_offending_target) |
Garbage input never panics, the level ordering is monotonic, Catastrophic is an absolute deny while Confirm is not, and the explanation names the path |
| TC-14 | Protected path resolution | crates/jcode-command-risk/src/paths_tests.rs (home_directory_is_catastrophic_in_every_spelling, parent_traversal_out_of_home_reaches_root_and_is_caught, root_and_system_paths_are_catastrophic, credential_stores_inside_home_are_catastrophic, ordinary_project_paths_are_not_catastrophic, home_subdirectory_is_not_itself_catastrophic, individual_credential_files_are_protected_not_just_their_directory, ordinary_config_files_remain_editable, missing_home_context_does_not_panic_or_misfire, normalize_never_escapes_above_root) |
Every spelling of the home directory resolves to the same verdict, .. traversal reaches and is caught at root, credential files are protected, and ordinary config files stay editable |
| TC-15 | Target classification tiers | crates/jcode-command-risk/src/paths_tests.rs (inside_working_directory_is_low_risk_not_confirm, non_recursive_delete_inside_cwd_is_unremarkable, concrete_outside_working_directory_target_is_low_risk, temp_paths_are_exempt, glob_over_a_protected_directory_is_catastrophic, unresolvable_targets_escalate_rather_than_pass, known_variable_logs_are_bounded_but_unknown_expansions_still_confirm, known_variables_do_not_bypass_protected_paths) |
A recursive delete inside the working directory is Low, a temp path produces no finding, a glob over a protected directory is Catastrophic, and an unknown expansion is Confirm |
| TC-16 | Tokenizer quoting, chaining, and flag detection | crates/jcode-command-risk/src/tokenize_tests.rs (all thirteen tests) |
Quoting and escaping resolve to one target word, chained and piped commands split into separate segments, > is marked while >> is not, recursive flags are detected in bundles, and malformed input never panics |
| TC-17 | Gate outcomes and justification substance | crates/jcode-command-risk/src/gate_tests.rs (all nine tests) |
Safe and Low allow, Catastrophic denies even with a perfect justification, Confirm reflects with a prompt that names the target, a blind retry is held again, and bare affirmations do not unlock the gate |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-18 | The gate policy at the tool seam | crates/jcode-app-core/src/tool/bash_destructive_gate.rs inline mod tests (scratch_log_and_backup_commands_do_not_require_justification, protected_writes_and_unknown_variables_remain_blocked) |
Scratch log and backup commands are not held, while rm -rf /etc, echo bad > /etc/passwd, find /etc -type f -exec rm {} \;, and echo test > "$UNKNOWN/tests.log" are all refused |
| TC-19 | The bash schema exposes the justification field |
crates/jcode-app-core/src/tool/bash_tests.rs (bash_optional_nulls_use_omitted_defaults, bash_executes_with_null_optional_arguments) |
An explicit null justification is treated as absent, and a call carrying a null justification still runs |
End-to-End Tests
These drive the real tool entry points and observe filesystem effects.
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-20 | The bash tool refuses to delete the home directory | crates/jcode-app-core/src/tool/bash_tests.rs (bash_refuses_to_delete_the_home_directory): set HOME to a temp directory, place a canary file in it, call bash with rm -rf $HOME |
The call fails with a refusal that says the command is blocked, and the canary file still exists |
| TC-21 | The bash tool holds a risky delete until it is justified | crates/jcode-app-core/src/tool/bash_tests.rs (bash_holds_a_risky_delete_until_justified_then_runs_it): call bash with a glob delete outside the workspace, then repeat it, then repeat it with a justification |
The first attempt and the blind retry are both held with a prompt naming the justification, and the justified attempt runs and deletes the target |
| TC-22 | The bash tool does not interfere with ordinary commands | crates/jcode-app-core/src/tool/bash_tests.rs (bash_does_not_interfere_with_ordinary_commands): run echo hello, rm -rf build, and ls -la in a temp working directory |
All three run untouched |
| TC-23 | Background dispatch cannot bypass the gate | crates/jcode-app-core/src/tool/bash_tests.rs (indirect_dispatch_paths_cannot_bypass_the_gate): call bash with run_in_background set and the command rm -rf $HOME |
The call fails with a refusal, and the canary file still exists |
| TC-24 | apply_patch refuses a protected path |
crates/jcode-app-core/src/tool/apply_patch_tests.rs (apply_patch_refuses_to_delete_a_protected_path): set HOME to a temp directory, create .ssh/id_ed25519, delete it by absolute path through a patch |
The tool reports a refusal, and the credential file still exists |
| TC-25 | apply_patch still deletes ordinary files |
crates/jcode-app-core/src/tool/apply_patch_tests.rs (apply_patch_still_deletes_ordinary_files): delete an ordinary file by absolute path through a patch |
The delete succeeds and the file is gone |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-26 | Empty, whitespace-only, or unbalanced-quote command input | The assessment returns a verdict and never panics, because assess is total over its input (crates/jcode-command-risk/src/assess_tests.rs::assessment_is_total_over_garbage_input, crates/jcode-command-risk/src/tokenize_tests.rs::tokenizing_is_total_and_never_panics) |
| TC-27 | HOME is unset on the host |
The system-path tier still applies and the classifier does not panic or misfire on ordinary paths (crates/jcode-command-risk/src/paths_tests.rs::missing_home_context_does_not_panic_or_misfire) |
| TC-28 | Pathological .. input such as /../../../../.. |
Normalization stops at /, and the result stays catastrophic (crates/jcode-command-risk/src/paths_tests.rs::normalize_never_escapes_above_root) |
| TC-29 | The command reassigns HOME= or JCODE_SCRATCH_DIR= |
The trusted protected paths still apply and the command is held (crates/jcode-command-risk/src/assess_tests.rs::reassignment_does_not_override_trusted_protection) |
| TC-30 | The model retries the identical held command | The same refusal is returned and nothing is deleted (crates/jcode-app-core/src/tool/bash_tests.rs::bash_holds_a_risky_delete_until_justified_then_runs_it, crates/jcode-command-risk/src/gate_tests.rs::a_blind_retry_does_not_satisfy_the_gate) |
| TC-31 | The justification is a bare affirmation such as yes, ok, or proceed. |
The command stays held, because the justification carries no information about intent (crates/jcode-command-risk/src/gate_tests.rs::empty_affirmations_are_rejected, crates/jcode-command-risk/src/gate_tests.rs::justification_substance_check_is_a_low_but_real_bar) |
| TC-32 | The command is dispatched in the background | The background path is gated as well, because the check sits at the single Tool::execute chokepoint (crates/jcode-app-core/src/tool/bash_tests.rs::indirect_dispatch_paths_cannot_bypass_the_gate) |
| TC-33 | The host runs Windows, where the bash tool drives cmd.exe |
The gate still runs and denies a syntactically recognised destructive command, but cmd.exe-specific destructive verbs are not classified. The gate module's own tests are compiled only on non-Windows hosts, so this scenario has no automated coverage today |
Test Infrastructure
- A synthetic
RiskContextwithworking_dir=/home/u/proj,home_dir=/home/u, andscratch_dir=/home/u/.jcode/scratchdrives the crate-level tests. - The tool-level tests use a real
tempfile::tempdir()as the home directory, with a canary file as the observable effect. - The tool-level tests set and restore the
HOMEenvironment variable, so they mutate process-global state and must not run concurrently with other tests that readHOME. jcode-command-riskdeclarestempfileas its only dev-dependency and no runtime dependencies, so the classifier is exercised without the agent runtime.- Test environment:
cargo test -p jcode-command-riskandcargo test -p jcode-app-core. - The gate module's own tests and the destructive-gate bash tests are compiled only on non-Windows hosts, so the Windows build has no direct coverage of the policy seam.
- No benchmark harness pins the latency budget in NFR-1MustThe assessment shall run entirely offline, with no model call and no network call, and shall complete in under 5 ms for a typical command line., and no test asserts the absence of file reads in NFR-2MustThe system shall reason only from the command text and path strings, and shall not read, log, or transmit the contents of any file that a command names., because both properties are enforced by construction rather than by an assertion.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall assess every shell command submitted to the `bash` tool with a deterministic, offline blast-radius assessment before the command is executed. | TC-1, TC-13, TC-20 |
| FR-2MustThe system shall classify a command by what it would destroy and whether that can be undone, rather than by command name, so that `find -delete`, `shred`, `truncate`, `dd`, and truncating redirects are covered alongside `rm -rf`. | TC-1, TC-9, TC-10 |
| FR-3MustThe system shall deny a catastrophic target outright, and no justification shall ever unlock it. | TC-2, TC-3, TC-17 |
| FR-4MustThe system shall treat the filesystem root, protected system paths and their contents, the user's home directory, credential stores and their contents, and raw device nodes as catastrophic targets. | TC-2, TC-14 |
| FR-5MustThe system shall convert a `Confirm` verdict into a reflection prompt that the model must satisfy by re-issuing the call with a substantive `justification` naming the user request the command serves. | TC-5, TC-17, TC-21 |
| FR-6MustThe system shall refuse a blind retry of a held command, so that repeating the identical call without a justification produces the same refusal. | TC-17, TC-21, TC-30 |
| FR-7MustThe system shall escalate to `Confirm` whenever the set of affected paths cannot be determined statically, including unresolved variables, command substitution, globs, operands supplied by a pipe, opaque wrappers, and inline shell scripts. | TC-5, TC-6, TC-8, TC-9, TC-15 |
| FR-8MustThe system shall apply the same classifier to `apply_patch` deletion targets, and shall refuse to delete a protected path. | TC-24, TC-25 |
| FR-9ShouldThe system shall unwrap command wrappers such as `sudo`, `env`, `nice`, `ionice`, `timeout`, `nohup`, `xargs`, `command`, and `exec`, so that the destructive program underneath is the one that gets classified. | TC-6 |
| FR-10ShouldThe system shall split a command line into segments on shell separators and assess each segment independently, so that chaining cannot launder a catastrophic command. | TC-3, TC-16 |
| FR-11ShouldThe system shall treat a truncating redirect to a protected path as a destructive write, and shall treat an append (`>>`) and the standard sinks (`/dev/null`, `/dev/stdout`, `/dev/stderr`, `NUL`) as non-destructive. | TC-10, TC-15 |
| FR-12ShouldThe system shall let routine in-project cleanup run without a reflection turn, so that the gate does not train users to bypass it. | TC-4, TC-22 |
| FR-13ShouldThe system shall apply the gate at the single `Tool::execute` chokepoint of the `bash` tool, before background dispatch, so that foreground, background, and batch dispatch paths cannot bypass it. | TC-20, TC-23 |
| FR-14ShouldThe system shall record each gate decision in the log, distinguishing a denial from a hold for justification. | TC-18 |
| FR-15MayThe system shall expose the protected path lists (home subpaths, credential subpaths, system paths, and recursively protected system paths) so that other tools and documentation can reuse the same policy. | TC-14 |
| NFR-1MustThe assessment shall run entirely offline, with no model call and no network call, and shall complete in under 5 ms for a typical command line. | TC-13 |
| NFR-2MustThe system shall reason only from the command text and path strings, and shall not read, log, or transmit the contents of any file that a command names. | TC-13, TC-14 |
| NFR-3MustThe assessment shall be total: any input, including empty, malformed, or garbage input, shall yield a verdict rather than an error or a panic. | TC-13, TC-16, TC-26 |
| NFR-4MustThe same command string and the same risk context shall always produce the same verdict, independent of wall-clock time, randomness, or network state. | TC-13 |
| NFR-5MustThe classifier crate shall declare no runtime dependency and shall make no network call, so that the safety decision cannot be subverted by an upstream service. | TC-1 |
| NFR-6ShouldA refusal shall name the offending path or target, shall ask the model to check the command against the user's actual request, and shall tell the model to ask the user when it is unsure. | TC-17, TC-20 |
| NFR-7ShouldThe safe path shall add no model round trip and no extra tool call, so an ordinary command costs only the assessment itself. | TC-4, TC-22 |
| NFR-8ShouldThe classifier shall be consumable by any tool without pulling in the agent runtime, so the destructive-command policy has one source of truth. | TC-18 |
requirements
- Should the classifier learn
cmd.exesyntax so the gate is equally effective on the Windows build of thebashtool? - Should the latency budget in NFR-1 be pinned by a benchmark so that a future refactor cannot silently make the safe path expensive?
- Should the protected path set be user-configurable, so that a home directory laid out differently from the defaults is still protected?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Todo and Goal Tracking
Overview
The agent keeps a session-scoped working memory that the user can watch live.
A plan records the intent the user actually expressed, broken into goals, each with steps, a quality gate, and a completion-confidence score.
The goal-level gate distinguishes a closed feedback loop from a taste judgment, so the model cannot fake progress on work that has no measurable signal.
The todo tool writes items, groups, and plan-level assessments, and the initiative tool drives long-running goals and refreshes the goal side panel without stealing focus.
A shared policy layer generates the synthetic continuation messages (auto-poke, gate digest, ownership, final response) and the same policy ships to the SDKSoftware Development Kit and any embedding client.
This feature was reverse-engineered from the existing codebase during an SDLC sync, so it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | A live, honest view of what the agent is doing, why it thinks the work is progressing, and what is still blocked. |
| Agent authors | A tool contract that records intent, per-goal quality gates, and evidence state without letting the model grade its own homework. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. clients (SDKSoftware Development Kit, Desktop) | One shared follow-up policy so every client pokes, gates, and hands off identically. |
| Maintainers | A single pure policy crate that can be unit-tested without a runtime, a terminal, or a provider. |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall persist a session-scoped todo list whose items carry content, status, priority, id, an optional group label, and evidence-state confidence fields, and shall reload it across turns and across session resume. | Must | The system shall persist a session-scoped todo list whose items carry content, status, priority, id, an optional group label, and evidence-state confidence fields, and shall reload it across turns and across session resume. |
| FR-2MustThe system shall accept only the todo statuses pending, in_progress, completed, and cancelled, shall canonicalize natural completion synonyms and case variants into them, and shall reject any other status with an error naming the valid vocabulary. | Must | The system shall accept only the todo statuses pending, in_progress, completed, and cancelled, shall canonicalize natural completion synonyms and case variants into them, and shall reject any other status with an error naming the valid vocabulary. |
| FR-3MustThe system shall group todos under an optional group label, one group per coherent goal, and shall render a grouped list with per-group headers and a flat list without them. | Must | The system shall group todos under an optional group label, one group per coherent goal, and shall render a grouped list with per-group headers and a flat list without them. |
| FR-4MustThe system shall record a plan-level intent assessment exactly once per plan, holding the user's stated intention and how well the agent understands it, independently of any individual group. | Must | The system shall record a plan-level intent assessment exactly once per plan, holding the user's stated intention and how well the agent understands it, independently of any individual group. |
| FR-5MustThe system shall record a goal-level quality assessment per group, covering the closed feedback loop state, the concrete feedback loop, its relevance, coverage, traceability, the delivery state, difficulty, autonomy, iteration maturity, and any stopping evidence. | Must | The system shall record a goal-level quality assessment per group, covering the closed feedback loop state, the concrete feedback loop, its relevance, coverage, traceability, the delivery state, difficulty, autonomy, iteration maturity, and any stopping evidence. |
| FR-6MustThe system shall distinguish a goal with a closed feedback loop from a goal whose success is a taste judgment, and shall require acceptance-aligned relevance and edge-and-integration coverage for goals at or above the involved difficulty level. | Must | The system shall distinguish a goal with a closed feedback loop from a goal whose success is a taste judgment, and shall require acceptance-aligned relevance and edge-and-integration coverage for goals at or above the involved difficulty level. |
| FR-7MustThe system shall record a forward-looking evidence state per todo, an evidence state at completion, and a tool-owned history of every distinct state a todo has carried, so that an evidence-driven rise is distinguishable from a bulk end-of-task stamp. | Must | The system shall record a forward-looking evidence state per todo, an evidence state at completion, and a tool-owned history of every distinct state a todo has carried, so that an evidence-driven rise is distinguishable from a bulk end-of-task stamp. |
| FR-8MustThe system shall defer the quality-gate checks to turn end, recording an observation for every failing check during the turn and replaying them once as a digest, with the single exception of a first plan write whose intent assessment is severely low. | Must | The system shall defer the quality-gate checks to turn end, recording an observation for every failing check during the turn and replaying them once as a digest, with the single exception of a first plan write whose intent assessment is severely low. |
| FR-9MustThe system shall never reject a todo write because a gate would fail, and shall save the write first and enforce the gate after the turn ends. | Must | The system shall never reject a todo write because a gate would fail, and shall save the write first and enforce the gate after the turn ends. |
| FR-10MustThe system shall merge each write with the stored state so that an omitted plan field, an omitted goal field, and a goal the write does not mention are all retained, and shall drop a goal whose todo group no longer exists. | Must | The system shall merge each write with the stored state so that an omitted plan field, an omitted goal field, and a goal the write does not mention are all retained, and shall drop a goal whose todo group no longer exists. |
| FR-11MustThe system shall generate every synthetic continuation message (the incomplete-todo poke, the intent check, the feedback-loop check, the ownership check, the completion-confidence check, the confidence-spike check, the gate digest, and the final-response handoff) from one shared policy layer, and shall keep the private thresholds, scores, and elapsed-time trigger out of the model-facing text. | Must | The system shall generate every synthetic continuation message (the incomplete-todo poke, the intent check, the feedback-loop check, the ownership check, the completion-confidence check, the confidence-spike check, the gate digest, and the final-response handoff) from one shared policy layer, and shall keep the private thresholds, scores, and elapsed-time trigger out of the model-facing text. |
| FR-12MustThe system shall classify those synthetic messages so the transcript never re-renders them as user prompts, and shall show a short user-facing notice in their place. | Must | The system shall classify those synthetic messages so the transcript never re-renders them as user prompts, and shall show a short user-facing notice in their place. |
| FR-13MustThe system shall decide the next follow-up after a turn ends in a fixed order: the long-session review, the incomplete-todo poke, the gate digest, the ownership gate, the completion-confidence check, the confidence-spike check, and finally the final-response handoff. | Must | The system shall decide the next follow-up after a turn ends in a fixed order: the long-session review, the incomplete-todo poke, the gate digest, the ownership gate, the completion-confidence check, the confidence-spike check, and finally the final-response handoff. |
| FR-14MustThe system shall bound the number of gate turns per completion cycle, surface a stall notice when the bound is reached, and re-arm for new work afterwards. | Must | The system shall bound the number of gate turns per completion cycle, surface a stall notice when the bound is reached, and re-arm for new work afterwards. |
| FR-15MustThe system shall expose a `todo` tool that reads and writes the todo list, the plan, and the goal assessments, that publishes the update on the bus, and that records lifecycle telemetry. | Must | The system shall expose a todo tool that reads and writes the todo list, the plan, and the goal assessments, that publishes the update on the bus, and that records lifecycle telemetry. |
| FR-16MustThe system shall expose an `initiative` tool that creates, lists, shows, resumes, updates, checkpoints, and focuses durable goals scoped to the project or to the user, and that refreshes an already-open goal side panel without stealing focus. | Must | The system shall expose an initiative tool that creates, lists, shows, resumes, updates, checkpoints, and focuses durable goals scoped to the project or to the user, and that refreshes an already-open goal side panel without stealing focus. |
| FR-17MustThe system shall never open the side panel from the initiative tool, and shall leave the opening of the goals overview to an explicit user command. | Must | The system shall never open the side panel from the initiative tool, and shall leave the opening of the goals overview to an explicit user command. |
| FR-18MustThe system shall surface the todo state in the terminal user interface as an inline chat card, an optional side-panel screen, an optional pinned band, and the persistent info widget, and shall keep the overall completed-of-total progress display visible in each of them. | Must | The system shall surface the todo state in the terminal user interface as an inline chat card, an optional side-panel screen, an optional pinned band, and the persistent info widget, and shall keep the overall completed-of-total progress display visible in each of them. |
| FR-19ShouldThe system shall derive a session title from the todo plan, preferring the group of the current or latest incomplete item, then the plan intention, then the item text. | Should | The system shall derive a session title from the todo plan, preferring the group of the current or latest incomplete item, then the plan intention, then the item text. |
| FR-20ShouldThe system shall ship the same policy to the SDKSoftware Development Kit and to any embedding client, exposing the session todo state and a follow-up acknowledgement so those clients run the identical follow-up policy. | Should | The system shall ship the same policy to the SDKSoftware Development Kit and to any embedding client, exposing the session todo state and a follow-up acknowledgement so those clients run the identical follow-up policy. |
| FR-21ShouldThe system shall load sessions recorded before the semantic-state migration, mapping legacy 0-100 numeric scores and the legacy field names onto the current semantic states. | Should | The system shall load sessions recorded before the semantic-state migration, mapping legacy 0-100 numeric scores and the legacy field names onto the current semantic states. |
| FR-22MayThe system shall let the user turn the auto-poke on and off, and shall make an explicit turn-off stick for the rest of the session. | May | The system shall let the user turn the auto-poke on and off, and shall make an explicit turn-off stick for the rest of the session. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustThe model-visible tool schema and every synthetic continuation message shall not disclose the private thresholds, the numeric scores, or the evaluator vocabulary, so the model cannot target the evaluator instead of reporting an honest assessment. | Must | Security | The model-visible tool schema and every synthetic continuation message shall not disclose the private thresholds, the numeric scores, or the evaluator vocabulary, so the model cannot target the evaluator instead of reporting an honest assessment. |
| NFR-2MustThe model-visible tool schema shall not be biased toward one domain's validation vocabulary, so the feedback-loop guidance stays equally applicable to every kind of work. | Must | Neutrality | The model-visible tool schema shall not be biased toward one domain's validation vocabulary, so the feedback-loop guidance stays equally applicable to every kind of work. |
| NFR-3MustEach static quality-gate continuation message shall stay within an approximate budget of 64 tokens, so it reads as a nudge rather than as a replacement system prompt. | Must | Performance | Each static quality-gate continuation message shall stay within an approximate budget of 64 tokens, so it reads as a nudge rather than as a replacement system prompt. |
| NFR-4MustA gate continuation shall name at most 6 todos explicitly and shall summarize the remainder, so a large plan cannot turn one nudge into a wall of text. | Must | Performance | A gate continuation shall name at most 6 todos explicitly and shall summarize the remainder, so a large plan cannot turn one nudge into a wall of text. |
| NFR-5MustThe deferred gate-observation log shall be capped per session, so a very long iterative turn cannot grow it without bound. | Must | Availability | The deferred gate-observation log shall be capped per session, so a very long iterative turn cannot grow it without bound. |
| NFR-6MustA failure to persist the gate-observation log shall be logged and swallowed rather than failing the todo write itself. | Must | Reliability | A failure to persist the gate-observation log shall be logged and swallowed rather than failing the todo write itself. |
| NFR-7MustA persisted session written under an earlier release shall still load, including the pre-rename field names and the earlier synthetic message wordings. | Must | Compatibility | A persisted session written under an earlier release shall still load, including the pre-rename field names and the earlier synthetic message wordings. |
| NFR-8ShouldA session id used to build a todo state path shall be restricted to a safe character set, so a session id can never escape the todo state directory. | Should | Security | A session id used to build a todo state path shall be restricted to a safe character set, so a session id can never escape the todo state directory. |
| NFR-9ShouldThe todo widget shall keep one logical row per visual row at narrow terminal widths, and shall truncate rather than wrap. | Should | Performance | The todo widget shall keep one logical row per visual row at narrow terminal widths, and shall truncate rather than wrap. |
| NFR-10ShouldThe pinned todo band shall render below the sticky prompt, without a horizontal separator, and shall show the overall progress rather than a collapsed summary. | Should | Usability | The pinned todo band shall render below the sticky prompt, without a horizontal separator, and shall show the overall progress rather than a collapsed summary. |
| NFR-11ShouldThe todo tool shall accept provider quirks that send tool arguments as JSON strings rather than native types, and shall reject only genuinely malformed input. | Should | Availability | The todo tool shall accept provider quirks that send tool arguments as JSON strings rather than native types, and shall reject only genuinely malformed input. |
Constraints
- The policy layer must stay free of storage, terminal, and provider dependencies, so the SDKSoftware Development Kit and any embedding client can run the same code as the TUITerminal User Interface.
- The private elapsed-time trigger for the long-session review must never appear in model-facing text.
- The todo list format on disk must stay a bare array of items, so every existing consumer keeps reading it.
- The goal assessments must stay in their own file beside the todo list, so each format stays independently readable.
- The swarm plan DAG is a separate feature, and session-local todo and goal state must stay distinct from swarm plan data.
Acceptance Criteria
Every FR and NFR shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
Acceptance criteria verify how a requirement is proven done, they do not restate it.
Write concrete, scenario-based criteria (happy path, edge cases and error states where applicable).
Write each criterion as a fenced gherkin block with a tag matching its requirement ID, so the criteria are parseable and later executable via BDD tooling (pytest-bdd, cucumber).
Multiple scenarios per requirement are allowed; tag each with the requirement ID.
-
FR-1MustThe system shall persist a session-scoped todo list whose items carry content, status, priority, id, an optional group label, and evidence-state confidence fields, and shall reload it across turns and across session resume.
gherkin @FR-1MustThe system shall persist a session-scoped todo list whose items carry content, status, priority, id, an optional group label, and evidence-state confidence fields, and shall reload it across turns and across session resume. Scenario: Todo items survive a write and a reload Given a session with a todo item "write the parser" in status pending When the agent writes the todo list and the session is reloaded Then the item is present with its content, status, priority, id, and group preserved -
FR-2MustThe system shall accept only the todo statuses pending, in_progress, completed, and cancelled, shall canonicalize natural completion synonyms and case variants into them, and shall reject any other status with an error naming the valid vocabulary.
```gherkin @FR-2MustThe system shall accept only the todo statuses pending, in_progress, completed, and cancelled, shall canonicalize natural completion synonyms and case variants into them, and shall reject any other status with an error naming the valid vocabulary. Scenario: Unknown todo status is rejected Given the agent calls the todo tool with status "blocked" When the tool parses the call Then the call fails with an error naming the valid vocabulary pending, in_progress, completed, cancelled
@FR-2MustThe system shall accept only the todo statuses pending, in_progress, completed, and cancelled, shall canonicalize natural completion synonyms and case variants into them, and shall reject any other status with an error naming the valid vocabulary. Scenario: Completion synonyms are canonicalized Given the agent calls the todo tool with statuses "done", "Finished", and "Canceled" When the tool parses the call Then the statuses become completed, completed, and cancelled ```
-
FR-3MustThe system shall group todos under an optional group label, one group per coherent goal, and shall render a grouped list with per-group headers and a flat list without them.
gherkin @FR-3MustThe system shall group todos under an optional group label, one group per coherent goal, and shall render a grouped list with per-group headers and a flat list without them. Scenario: Grouped todos render under a group header Given todos in the groups "build" and "verify" When the todo widget renders the list Then one header row per group is shown with the group's completed-of-total count -
FR-4MustThe system shall record a plan-level intent assessment exactly once per plan, holding the user's stated intention and how well the agent understands it, independently of any individual group.
gherkin @FR-4MustThe system shall record a plan-level intent assessment exactly once per plan, holding the user's stated intention and how well the agent understands it, independently of any individual group. Scenario: The plan intent assessment survives a goals-only write Given a plan whose user_intention is "make search feel instant" and whose understands_user_intent is partial When the agent writes only the goal assessments Then the stored plan still carries the same intention and understanding state -
FR-5MustThe system shall record a goal-level quality assessment per group, covering the closed feedback loop state, the concrete feedback loop, its relevance, coverage, traceability, the delivery state, difficulty, autonomy, iteration maturity, and any stopping evidence.
gherkin @FR-5MustThe system shall record a goal-level quality assessment per group, covering the closed feedback loop state, the concrete feedback loop, its relevance, coverage, traceability, the delivery state, difficulty, autonomy, iteration maturity, and any stopping evidence. Scenario: A goal assessment records the full field set Given the agent writes a goal for the group "optimize grep" When the assessment is stored Then the stored goal carries the feedback loop state, the feedback loop text, the relevance, coverage, traceability, delivery state, difficulty, autonomy, iteration maturity, and stopping evidence -
FR-6MustThe system shall distinguish a goal with a closed feedback loop from a goal whose success is a taste judgment, and shall require acceptance-aligned relevance and edge-and-integration coverage for goals at or above the involved difficulty level.
gherkin @FR-6MustThe system shall distinguish a goal with a closed feedback loop from a goal whose success is a taste judgment, and shall require acceptance-aligned relevance and edge-and-integration coverage for goals at or above the involved difficulty level. Scenario: A substitute check does not clear the acceptance bar Given a goal of involved difficulty whose feedback loop relevance is synthetic When the completion bar is evaluated Then the goal does not pass, and the same holds for a representative or acceptance-blocked relevance -
FR-7MustThe system shall record a forward-looking evidence state per todo, an evidence state at completion, and a tool-owned history of every distinct state a todo has carried, so that an evidence-driven rise is distinguishable from a bulk end-of-task stamp.
gherkin @FR-7MustThe system shall record a forward-looking evidence state per todo, an evidence state at completion, and a tool-owned history of every distinct state a todo has carried, so that an evidence-driven rise is distinguishable from a bulk end-of-task stamp. Scenario: A bulk end-of-task stamp stays distinguishable from a stepped rise Given a completed todo whose confidence history is speculative then verified When the spike classifier runs Then the todo is reported as a confidence spike -
FR-8MustThe system shall defer the quality-gate checks to turn end, recording an observation for every failing check during the turn and replaying them once as a digest, with the single exception of a first plan write whose intent assessment is severely low.
gherkin @FR-8MustThe system shall defer the quality-gate checks to turn end, recording an observation for every failing check during the turn and replaying them once as a digest, with the single exception of a first plan write whose intent assessment is severely low. Scenario: A moderate first write records instead of interrupting Given a first plan write whose understanding is partial and whose goal has narrow coverage When the todo tool executes the write Then the tool output carries no gate continuation, and the failing checks are recorded as observations for the turn-end digest -
FR-9MustThe system shall never reject a todo write because a gate would fail, and shall save the write first and enforce the gate after the turn ends.
gherkin @FR-9MustThe system shall never reject a todo write because a gate would fail, and shall save the write first and enforce the gate after the turn ends. Scenario: A low-scoring completion is still saved Given a write that completes a group whose delivery state is below the bar When the todo tool executes the write Then the completed todo and the low delivery state are persisted, and no ownership continuation is returned in the tool output -
FR-10MustThe system shall merge each write with the stored state so that an omitted plan field, an omitted goal field, and a goal the write does not mention are all retained, and shall drop a goal whose todo group no longer exists.
gherkin @FR-10MustThe system shall merge each write with the stored state so that an omitted plan field, an omitted goal field, and a goal the write does not mention are all retained, and shall drop a goal whose todo group no longer exists. Scenario: A goal for a finished task is dropped Given stored goals for the groups "first task" and "second task" When the agent replaces the todo list with items only in the group "second task" Then only the "second task" goal remains -
FR-11MustThe system shall generate every synthetic continuation message (the incomplete-todo poke, the intent check, the feedback-loop check, the ownership check, the completion-confidence check, the confidence-spike check, the gate digest, and the final-response handoff) from one shared policy layer, and shall keep the private thresholds, scores, and elapsed-time trigger out of the model-facing text.
gherkin @FR-11MustThe system shall generate every synthetic continuation message (the incomplete-todo poke, the intent check, the feedback-loop check, the ownership check, the completion-confidence check, the confidence-spike check, the gate digest, and the final-response handoff) from one shared policy layer, and shall keep the private thresholds, scores, and elapsed-time trigger out of the model-facing text. Scenario: The continuations name a category but not the calibration Given each of the quality-gate continuation messages When the messages are inspected Then none of them contains a threshold, a percent, a score, or the word gate -
FR-12MustThe system shall classify those synthetic messages so the transcript never re-renders them as user prompts, and shall show a short user-facing notice in their place.
gherkin @FR-12MustThe system shall classify those synthetic messages so the transcript never re-renders them as user prompts, and shall show a short user-facing notice in their place. Scenario: A synthetic continuation is not replayed as a user prompt Given a persisted transcript containing a gate digest continuation When the session is reloaded and rendered Then the continuation is not rendered as a user prompt, and a short notice is shown instead -
FR-13MustThe system shall decide the next follow-up after a turn ends in a fixed order: the long-session review, the incomplete-todo poke, the gate digest, the ownership gate, the completion-confidence check, the confidence-spike check, and finally the final-response handoff.
gherkin @FR-13MustThe system shall decide the next follow-up after a turn ends in a fixed order: the long-session review, the incomplete-todo poke, the gate digest, the ownership gate, the completion-confidence check, the confidence-spike check, and finally the final-response handoff. Scenario: The follow-up order is respected Given a completed todo list with one recorded gate observation and a weak completion confidence When the follow-up policy decides the next continuation Then the gate digest is sent first, the completion-validation continuation second, and the final-response handoff last -
FR-14MustThe system shall bound the number of gate turns per completion cycle, surface a stall notice when the bound is reached, and re-arm for new work afterwards.
gherkin @FR-14MustThe system shall bound the number of gate turns per completion cycle, surface a stall notice when the bound is reached, and re-arm for new work afterwards. Scenario: The gate budget trips and then re-arms Given a completion cycle in which the validation gate never passes When more turns are requested than the gate budget allows Then the policy stops sending continuations, surfaces a stall notice, and pokes again once new open work appears -
FR-15MustThe system shall expose a `todo` tool that reads and writes the todo list, the plan, and the goal assessments, that publishes the update on the bus, and that records lifecycle telemetry.
gherkin @FR-15MustThe system shall expose a `todo` tool that reads and writes the todo list, the plan, and the goal assessments, that publishes the update on the bus, and that records lifecycle telemetry. Scenario: A todo write publishes the update and records telemetry Given the agent writes a todo list When the write completes Then a todo-updated event is published on the bus and the lifecycle counters are recorded -
FR-16MustThe system shall expose an `initiative` tool that creates, lists, shows, resumes, updates, checkpoints, and focuses durable goals scoped to the project or to the user, and that refreshes an already-open goal side panel without stealing focus.
gherkin @FR-16MustThe system shall expose an `initiative` tool that creates, lists, shows, resumes, updates, checkpoints, and focuses durable goals scoped to the project or to the user, and that refreshes an already-open goal side panel without stealing focus. Scenario: An initiative update refreshes an open overview without stealing focus Given the user has opened the goals overview in the side panel When the agent updates an initiative through the initiative tool Then the overview page shows the new content and the focused page is still the goals overview -
FR-17MustThe system shall never open the side panel from the initiative tool, and shall leave the opening of the goals overview to an explicit user command.
gherkin @FR-17MustThe system shall never open the side panel from the initiative tool, and shall leave the opening of the goals overview to an explicit user command. Scenario: Creating an initiative does not open the side panel Given no side panel page is open for the session When the agent creates an initiative through the initiative tool Then no side panel update is published and no goal page is written -
FR-18MustThe system shall surface the todo state in the terminal user interface as an inline chat card, an optional side-panel screen, an optional pinned band, and the persistent info widget, and shall keep the overall completed-of-total progress display visible in each of them.
gherkin @FR-18MustThe system shall surface the todo state in the terminal user interface as an inline chat card, an optional side-panel screen, an optional pinned band, and the persistent info widget, and shall keep the overall completed-of-total progress display visible in each of them. Scenario: The todo card shows the plan and the goal assessments Given a session with todos, a plan, and one goal assessment When the user runs the todos command Then an inline card is shown carrying the todos, the plan, and the goal assessments -
FR-19ShouldThe system shall derive a session title from the todo plan, preferring the group of the current or latest incomplete item, then the plan intention, then the item text.
gherkin @FR-19ShouldThe system shall derive a session title from the todo plan, preferring the group of the current or latest incomplete item, then the plan intention, then the item text. Scenario: The session title comes from the active group Given todos where the in-progress item belongs to the group "Fix resume names" When the session title is derived Then the title is "Fix resume names" -
FR-20ShouldThe system shall ship the same policy to the SDKSoftware Development Kit and to any embedding client, exposing the session todo state and a follow-up acknowledgement so those clients run the identical follow-up policy.
gherkin @FR-20ShouldThe system shall ship the same policy to the SDKSoftware Development Kit and to any embedding client, exposing the session todo state and a follow-up acknowledgement so those clients run the identical follow-up policy. Scenario: An SDKSoftware Development Kit client can read the todo state and acknowledge a follow-up Given an SDKSoftware Development Kit client with the todo-state capability When it requests the session todo state and then acknowledges the follow-up effects Then it receives the snapshot and the gate-observation log is cleared -
FR-21ShouldThe system shall load sessions recorded before the semantic-state migration, mapping legacy 0-100 numeric scores and the legacy field names onto the current semantic states.
gherkin @FR-21ShouldThe system shall load sessions recorded before the semantic-state migration, mapping legacy 0-100 numeric scores and the legacy field names onto the current semantic states. Scenario: A legacy numeric payload still loads Given a stored goal carrying the legacy hill-climbability and end-to-end-ownership keys with numeric values When the session state is loaded Then the goal carries the current feedback-loop and delivery states, and the legacy key names are not written back -
FR-22MayThe system shall let the user turn the auto-poke on and off, and shall make an explicit turn-off stick for the rest of the session.
gherkin @FR-22MayThe system shall let the user turn the auto-poke on and off, and shall make an explicit turn-off stick for the rest of the session. Scenario: Turning the auto-poke off sticks for the session Given the user turns the auto-poke off When a later turn ends with incomplete todos Then no poke is sent, and the default-on re-arm does not undo the explicit turn-off -
NFR-1MustThe model-visible tool schema and every synthetic continuation message shall not disclose the private thresholds, the numeric scores, or the evaluator vocabulary, so the model cannot target the evaluator instead of reporting an honest assessment.
gherkin @NFR-1MustThe model-visible tool schema and every synthetic continuation message shall not disclose the private thresholds, the numeric scores, or the evaluator vocabulary, so the model cannot target the evaluator instead of reporting an honest assessment. Scenario: The model-visible schema hides the calibration Given the serialized todo tool schema When it is inspected Then it contains no threshold, quality gate, internal quality check, or score wording -
NFR-2MustThe model-visible tool schema shall not be biased toward one domain's validation vocabulary, so the feedback-loop guidance stays equally applicable to every kind of work.
gherkin @NFR-2MustThe model-visible tool schema shall not be biased toward one domain's validation vocabulary, so the feedback-loop guidance stays equally applicable to every kind of work. Scenario: The schema does not bias one kind of work Given the serialized todo tool schema When it is inspected Then it contains no browser, screenshot, viewport, or console-error hint -
NFR-3MustEach static quality-gate continuation message shall stay within an approximate budget of 64 tokens, so it reads as a nudge rather than as a replacement system prompt.
gherkin @NFR-3MustEach static quality-gate continuation message shall stay within an approximate budget of 64 tokens, so it reads as a nudge rather than as a replacement system prompt. Scenario: Every static continuation fits the token budget Given the long-session review, intent, feedback-loop, ownership, completion, confidence-spike, final-response, and digest messages When each is estimated in tokens Then each stays at or below the approximate budget of 64 tokens and starts with the compact automation prefix -
NFR-4MustA gate continuation shall name at most 6 todos explicitly and shall summarize the remainder, so a large plan cannot turn one nudge into a wall of text.
gherkin @NFR-4MustA gate continuation shall name at most 6 todos explicitly and shall summarize the remainder, so a large plan cannot turn one nudge into a wall of text. Scenario: A long list is summarized instead of enumerated Given 40 completed todos with no completion confidence When the completion continuation is built Then the first 6 todos are named, and the remainder is reported as a count -
NFR-5MustThe deferred gate-observation log shall be capped per session, so a very long iterative turn cannot grow it without bound.
gherkin @NFR-5MustThe deferred gate-observation log shall be capped per session, so a very long iterative turn cannot grow it without bound. Scenario: The observation log stays bounded Given a turn that records more observations than the cap allows When the observations are appended Then only the capped number of most recent observations is retained -
NFR-6MustA failure to persist the gate-observation log shall be logged and swallowed rather than failing the todo write itself.
gherkin @NFR-6MustA failure to persist the gate-observation log shall be logged and swallowed rather than failing the todo write itself. Scenario: An unwritable observation log does not fail the write Given the observation log cannot be written When the agent writes the todo list Then the write still succeeds and the failure is logged -
NFR-7MustA persisted session written under an earlier release shall still load, including the pre-rename field names and the earlier synthetic message wordings.
gherkin @NFR-7MustA persisted session written under an earlier release shall still load, including the pre-rename field names and the earlier synthetic message wordings. Scenario: An earlier synthetic wording is still classified Given a persisted transcript containing an earlier version of the ownership continuation When the transcript is classified Then the message is recognised as a synthetic continuation and not as a user prompt -
NFR-8ShouldA session id used to build a todo state path shall be restricted to a safe character set, so a session id can never escape the todo state directory.
gherkin @NFR-8ShouldA session id used to build a todo state path shall be restricted to a safe character set, so a session id can never escape the todo state directory. Scenario: An unsafe session id is rejected Given the session id "../x" When a todo state path is built Then the session id is reported as unsafe -
NFR-9ShouldThe todo widget shall keep one logical row per visual row at narrow terminal widths, and shall truncate rather than wrap.
gherkin @NFR-9ShouldThe todo widget shall keep one logical row per visual row at narrow terminal widths, and shall truncate rather than wrap. Scenario: The todo widget keeps one row per item at a narrow width Given a todo list rendered in a narrow info widget When the widget renders Then each item occupies exactly one visual row and long content is truncated -
NFR-10ShouldThe pinned todo band shall render below the sticky prompt, without a horizontal separator, and shall show the overall progress rather than a collapsed summary.
gherkin @NFR-10ShouldThe pinned todo band shall render below the sticky prompt, without a horizontal separator, and shall show the overall progress rather than a collapsed summary. Scenario: The pinned band sits under the sticky prompt Given the pinned todo band is enabled and a user prompt is visible When the transcript renders Then the pinned todo row appears below the prompt row and no horizontal separator is drawn -
NFR-11ShouldThe todo tool shall accept provider quirks that send tool arguments as JSON strings rather than native types, and shall reject only genuinely malformed input.
gherkin @NFR-11ShouldThe todo tool shall accept provider quirks that send tool arguments as JSON strings rather than native types, and shall reject only genuinely malformed input. Scenario: Stringified tool arguments are accepted Given the agent sends the whole todos array as a JSON string and a numeric confidence as a string When the tool parses the call Then the call succeeds and the confidence maps onto the closest semantic state
Conflicts
None identified yet.
Open Questions
- None, the feature is implemented and the artifacts were derived from the code rather than from an open design question.
Specification: Todo and Goal Tracking
Overview
The feature is split across three layers.
jcode-task-types holds the pure domain model (todos, goals, plan-level intent assessment, initiatives, and the semantic states used for every assessment).
jcode-todo-policy holds the pure policy (the quality-gate bars, the synthetic continuation messages, the transcript classifiers, the turn-end follow-up state machine, and the on-disk layout), with no storage, terminal, or provider dependency.
jcode-app-core and jcode-tui hold the runtime surfaces (the todo and initiative tools, the persistence helpers in jcode-base, the auto-poke loop in the TUITerminal User Interface and in jcode run, and the todo widgets).
The same policy crate is re-exported by jcode-base (crate::todo::*), served to SDKSoftware Development Kit clients through the harness API, and re-exported by jcode-sdk as jcode_sdk::todo, so the TUITerminal User Interface, the CLI, the SDKSoftware Development Kit, and Desktop all run the same rules.
This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
jcode-task-types (pure domain model)
TodoItem, TodoGoal, TodoPlan, Goal, GoalMilestone
semantic states: IntentUnderstanding, FeedbackLoopState,
FeedbackLoopRelevance, FeedbackLoopCoverage,
FeedbackLoopTraceability, ConfidenceState, Difficulty,
Autonomy, DeliveryState, IterationMaturity
│
▼
jcode-todo-policy (pure policy, no I/O)
├── lib.rs quality-gate bars, continuation messages,
│ transcript classifiers, session title
├── followup.rs FollowUpPolicy: turn-end decision state machine
└── store.rs on-disk layout under <jcode home>/todos/
│
┌─────────────────┼──────────────────────────┐
▼ ▼ ▼
jcode-base jcode-app-core jcode-sdk
crate::todo::* tool/todo.rs jcode_sdk::todo
load/save todos, tool/goal.rs (initiative) todo_state()
goals, plan, gate BusEvent::TodoUpdated ack_todo_follow_up()
observations, review BusEvent::SidePanelUpdated
state, side panel telemetry
│ │
▼ ▼
jcode-tui harness API server
├── app/todos_view.rs get_todo_state
├── app/input.rs ack_todo_follow_up
├── info_widget_todos.rs
└── app/commands.rs /initiatives, /goals
│
▼
root crate: jcode run (src/cli/commands.rs)
Data Models
Todo item
| Field | Type | Constraints | Description |
|---|---|---|---|
| content | string | not null | What the item is. |
| status | string | not null, one of pending, in_progress, completed, cancelled | Canonical status. Natural synonyms are canonicalized on parse. |
| priority | string | not null | Priority label, used to weight the aggregate confidence. |
| id | string | not null | Stable identifier of the item within the plan. |
| group | string, optional | trimmed, empty collapses to absent | Group label. One group per coherent goal. |
| confidence | ConfidenceState, optional | absent means not assessed | Forward-looking evidence state that the item can be completed correctly. |
| completion_confidence | ConfidenceState, optional | absent means not assessed | Evidence state recorded when the item was completed. |
| confidence_history | list of ConfidenceState | tool-owned, oldest first | Every distinct state the item has carried. Model-supplied values are discarded. |
| blocked_by | list of string | default empty | Identifiers of the items that block this one. |
| assigned_to | string, optional | default absent | Owner of the item. |
Todo group
A group is not a stored entity.
It is the normalized (trimmed, non-empty) group label carried by a set of todo items, and it is the key that binds a TodoGoal assessment to the items it describes.
The ungrouped flat list is the implicit group with the key None, so a flat plan still has exactly one goal assessment.
Groups appear in the order they are first seen, and the ungrouped bucket is always rendered last.
Goal (todo-level assessment)
| Field | Type | Constraints | Description |
|---|---|---|---|
| group | string, optional | normalized | The group this assessment describes. None is the ungrouped list. |
| closed_feedback_loop | FeedbackLoopState, optional | alias hill_climbability |
How much of the goal's correctness the feedback loop can report on its own. |
| feedback_loop | string, optional | none | The concrete requirement-to-check process used to judge each iteration. |
| feedback_loop_relevance | FeedbackLoopRelevance, optional | none | How directly the checks represent the acceptance behavior. |
| feedback_loop_coverage | FeedbackLoopCoverage, optional | none | How broadly the checks exercise main paths, integration boundaries, and edge cases. |
| feedback_loop_traceability | FeedbackLoopTraceability, optional | none | Whether every requirement and changed public output maps to a concrete check. |
| delivery_state | DeliveryState, optional | alias end_to_end_ownership |
How far the result traveled toward the user's outcome. |
| difficulty | Difficulty, optional | descriptive, never gated | Intrinsic difficulty of the goal. |
| autonomy | Autonomy, optional | gated at necessary_followthrough | How far beyond the literal request the work went. |
| iteration_maturity | IterationMaturity, optional | gated | How far the loop was exercised, and the basis for stopping. |
| stopping_evidence | string, optional | required for a confirmed plateau, exhausted constraints, or an exhausted budget | Evidence behind the reported iteration maturity. |
*_history fields |
list of state, optional | tool-owned, oldest first | The distinct states each assessment has carried. Model-supplied values are discarded. |
The difficulty only calibrates the feedback-loop bars. A goal at or above the involved difficulty needs acceptance-aligned relevance, edge-and-integration coverage, and complete traceability. The delivery bar is never raised by difficulty, because operational delivery comes from the request rather than from implementation difficulty.
Plan-level intent assessment
| Field | Type | Constraints | Description |
|---|---|---|---|
| user_intention | string, optional | inherited from the stored plan when omitted | The user's underlying reason and desired end state, kept distinct from the agent's steps. |
| understands_user_intent | IntentUnderstanding, optional | alias alignment_score, user_intention_alignment |
How well the agent understands what the user actually wants. |
| understands_user_intent_history | list of IntentUnderstanding | tool-owned, oldest first | The distinct understanding states the plan has carried. |
The plan is stored in its own file so the todo list file stays a bare array of items.
Confidence scores
Confidence is expressed as semantic states, not as numbers.
ConfidenceState runs speculative, plausible, validated, verified.
IntentUnderstanding runs uncertain, partial, clear, complete.
FeedbackLoopState runs absent, weak, usable, strong, closed.
FeedbackLoopRelevance runs indirect, synthetic, representative, acceptance_blocked, acceptance_aligned.
FeedbackLoopCoverage runs narrow, main_paths, edge_and_integration_paths.
FeedbackLoopTraceability runs unmapped, partial, complete.
DeliveryState runs change_made, integrated, workflow_validated, outcome_delivered.
Difficulty runs trivial, routine, involved, complex, hard, expert, research, open_ended.
Autonomy runs requested_only, necessary_followthrough, proactive, stewardship.
IterationMaturity runs not_started, exploring, improving, plateau_unproven, outcome_reached, constraints_exhausted, plateau_confirmed, budget_exhausted.
Each state keeps a legacy 0-100 band and a representative score, so a payload recorded before the semantic-state migration still loads on the closest state and telemetry can still aggregate numerically. The states serialize as snake_case strings and parse case-insensitively.
Initiative (durable goal)
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | string | slugified, unique within the scope | Identifier of the initiative. |
| title | string | not empty | Title. |
| scope | GoalScope | global or project, default project | Where the initiative is stored. |
| status | GoalStatus | draft, active, paused, blocked, completed, archived, abandoned | Lifecycle state. |
| description | string, optional | none | Free-form description. |
| why | string, optional | none | The reason the initiative exists. |
| success_criteria | list of string | none | What "done" means. |
| milestones | list of GoalMilestone | none | Ordered steps, each with its own steps. |
| next_steps | list of string | none | The immediate next actions. |
| blockers | list of string | none | What is currently blocked. |
| current_milestone_id | string, optional | none | The active milestone. |
| progress_percent | integer 0-100, optional | clamped to 100 | Reported progress. |
| created_at / updated_at | timestamp | not null | Bookkeeping. |
| updates | list of GoalUpdate | not null | Checkpoint history. |
Initiatives live outside the session todo state, under <jcode home>/goals/global and <jcode home>/goals/projects/<project hash>, and are mirrored into the memory store.
Follow-up decision
| Field | Type | Constraints | Description |
|---|---|---|---|
| follow_up | FollowUp, optional | none | The synthetic continuation to send, with its kind, model-facing message, and user-facing notice. |
| notice | string, optional | none | A user-facing notice with no follow-up, used by the circuit breaker. |
| effects | TodoEffects | none | Persistent side effects to apply, namely clearing the gate-observation log and marking the long-session review delivered. |
FollowUpKind runs incomplete_todos, long_session_review, gate_digest, ownership, completion_validation, confidence_spike, final_response.
API Contracts
This feature defines no HTTP endpoint, so no api.yaml accompanies this document.
The contract surface is the model-facing tool schema, the TUITerminal User Interface commands, and the SDKSoftware Development Kit capability pair.
Model-facing tools
| Tool | Action | Purpose |
|---|---|---|
todo |
read | Return the stored todo list, plan, and goal assessments. |
todo |
write | Write the todo list, the plan, and the goal assessments. A write with no todos, goals, or plan is a read. |
initiative |
create, list, show, resume, update, checkpoint, focus | Manage durable initiatives. The update and checkpoint actions refresh an already-open goal page in update-only mode, which never steals focus. |
SDKSoftware Development Kit capabilities
| Capability | Purpose |
|---|---|
todo_state |
Read the session todo snapshot (todos, plan, goals, gate observations, long-session review flag). |
ack_todo_follow_up |
Apply the follow-up effects (clear the observation log, mark the review delivered). |
TUITerminal User Interface commands
| Command | Purpose |
|---|---|
/todos, /todo |
Toggle the inline todo card in the chat. |
/todos panel, /todos on, /todos off |
Toggle the transient todo page in the side panel. |
/todos pin, /todos pin on, /todos pin off |
Toggle the pinned todo band. |
/initiatives, /goals |
Open the initiatives overview in the side panel. |
/initiatives resume |
Resume the attached or first resumable initiative. |
/initiatives show <id> |
Open one initiative in the side panel. |
Sequences
Write a todo list
sequenceDiagram
autonumber
participant M as Model
participant T as todo tool
participant S as Todo state files
participant B as Bus
participant P as Policy layer
M->>T: todo(todos, plan, goals)
T->>T: normalize provider quirks, validate status vocabulary
T->>S: load stored todos, goals, plan
T->>T: merge confidence history, merge goals, merge plan
T->>T: record gate observations for the failing checks
T->>S: save todos, goals, plan
T->>B: publish TodoUpdated
T->>T: record telemetry
T-->>M: todos, plan, goals, plan update, goal updates
Note over M,P: The digest is not built here
Evaluate the quality gate at turn end
sequenceDiagram
autonumber
participant A as Agent
participant O as Observation log
participant P as Policy layer
participant F as Follow-up policy
participant M as Model
A->>O: append observations for the failing checks
A->>P: read todos, plan, goals
P-->>A: observations, plan, goals
F->>F: decide, given the snapshot
alt incomplete todos remain
F->>M: send the incomplete-todo poke
else the turn ended with all work closed
F->>O: clear the observation log
F->>M: send the gate digest
F->>M: send the ownership or completion continuation
F->>M: send the final-response handoff
end
Auto-poke continuation
sequenceDiagram
autonumber
participant U as User
participant T as TUITerminal User Interface or jcode run
participant S as Todo state
participant M as Model
participant R as Transcript renderer
U->>T: submits a turn
T->>M: runs the turn
M->>S: writes the todo list
T->>S: loads todos, goals, plan
alt incomplete todos remain
T->>T: builds the poke message
T->>M: sends the poke as a synthetic user-role turn
R-->>U: shows a short notice instead of the poke text
end
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| One pure policy crate | jcode-todo-policy has no storage, terminal, or provider dependency |
The SDKSoftware Development Kit and any embedding client run the same rules as the TUITerminal User Interface, and the policy is unit-testable without a runtime. |
| Semantic states instead of 0-100 scores | Every assessment is an ordered enum with a legacy numeric band | The bands describe evidence, not a number to maximize, and legacy payloads still load on the closest state. |
| Deferred gates with a turn-end digest | Checks record observations during the turn and replay them once at turn end | Understanding of a request starts low and rises, so interrupting on every low reading punished agents that were resolving the ambiguity. |
| A late climb is still raised | The score decides the wording, not whether the point is raised | Work done while the score was low never benefited from the better loop that arrived afterwards. |
| Tool-owned score histories | Model-supplied histories are discarded in favor of the stored trail plus this write's observation | A model must not be able to fabricate a gradual climb that clears a gate. |
| Writes are never rejected by a gate | The write is saved, and the gate runs after the turn | A rejected write loses the agent's work, and the turn-end check still catches the problem. |
| One file per format | Todos, goals, plan, gate observations, and review state each live in their own file | The todo list stays a bare array that every existing consumer can read. |
| The todo tool never opens the side panel | The initiative tool refreshes an already-open page in update-only mode | An agent must not steal the user's focus or open panels the user did not ask for. |
| The private elapsed-time trigger stays private | The 30-minute review threshold never appears in model-facing text | A visible timer would let the model target the evaluator instead of doing the work. |
| Legacy continuations are kept for classification only | The old wordings are matched by the classifier but never sent | Persisted transcripts must not re-render an old gate message as a user prompt. |
| A shared transcript classifier | is_auto_poke_message and auto_poke_display_summary classify every synthetic message |
The live UI, the transcript renderer, and the SDKSoftware Development Kit agree on what is synthetic. |
Risks and Unknowns
- The gate thresholds are private constants, so a change to them can silently change model behaviour without any visible test failure beyond the policy unit tests.
- The follow-up state machine is duplicated in the TUITerminal User Interface (
schedule_auto_poke_followup_if_needed) and in the pure policy (FollowUpPolicy::decide), so the two can drift. - The semantic-state migration depends on the legacy bands staying stable, because a session's stored score is mapped through them on every load.
- The long-session review clock is durable per session, so a session that is resumed after a long gap can receive the review immediately.
- The todo widget and the pinned band are dense render paths, so layout regressions at narrow widths are the most likely source of visible defects.
- The
todotool's model-visible schema is hand-written, so a careless edit could reintroduce calibration wording that the policy tests would not catch.
Out of Scope
- The swarm plan DAG in
crates/jcode-planandcrates/jcode-swarm-core, which is a separate feature. - The swarm plan projection that the info widget can render in place of the session todo list.
- Multi-agent or sub-agent todo coordination, which is handled by the swarm feature.
Test Plan: Todo and Goal Tracking
Scope
Covers the pure todo policy crate (quality-gate bars, continuation messages, transcript classifiers, the turn-end follow-up state machine, and the on-disk layout), the domain model in jcode-task-types, the todo and initiative tools, the todo persistence helpers in jcode-base, the goal and side-panel storage, and the terminal surfaces (the todo card, the pinned band, the info widget, and the auto-poke loop in the TUITerminal User Interface and in jcode run).
Out of scope: the swarm plan DAG and its projections, live terminal interaction, and provider network behaviour.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Semantic states serialize as snake_case strings, parse case-insensitively, and map legacy 0-100 numbers onto the closest state | crates/jcode-task-types/src/lib.rs (inline semantic_state_tests) |
Every state round-trips, a legacy number maps onto the closest band, and an out-of-range value is rejected. |
| TC-2 | Legacy todo, plan, and goal payloads still load, and the current field names are the only ones written back | crates/jcode-task-types/src/lib.rs (inline semantic_state_tests) |
A payload with hill_climbability, end_to_end_ownership, and alignment_score loads onto the current fields, and the legacy names are absent from the serialized output. |
| TC-3 | The quality-gate bars, including the difficulty-calibrated relevance, coverage, and traceability requirements, the delivery bar, autonomy, iteration maturity, and stopping evidence | crates/jcode-todo-policy/src/tests.rs |
An involved-difficulty goal with a synthetic or representative relevance fails, the delivery bar is never raised by difficulty alone, and a confirmed plateau needs stopping evidence. |
| TC-4 | The turn-end gate digest: a late climb is still raised, repeats collapse with a count, goals are separated by group, and the ungrouped goal renders cleanly | crates/jcode-todo-policy/src/tests.rs |
One digest line per point, with the "started this work without understanding" wording for a late climb, a "flagged N times" count for repeats, and no empty quoted label for the ungrouped goal. |
| TC-5 | The synthetic continuation messages, their classification as non-user prompts, and the short user-facing display summaries | crates/jcode-todo-policy/src/tests.rs |
Every built continuation is recognised by is_auto_poke_message, the spike and completion continuations name the target todos, and a real user prompt is never classified as synthetic. |
| TC-6 | Continuation privacy, the static token budget, and the cap on the number of named todos | crates/jcode-todo-policy/src/tests.rs |
No continuation contains a threshold, percent, score, or gate wording, every static message stays within the approximate 64-token budget, and a 40-item list names 6 todos and summarizes the rest. |
| TC-7 | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. title derivation from the todo plan | crates/jcode-todo-policy/src/tests.rs |
The title prefers the in-progress item's group, then the latest incomplete item's group, then the plan intention, then the item content. |
| TC-8 | The turn-end follow-up state machine: the decision order, the arm and disarm rules, the digest and gate budget, and the snapshot round trip | crates/jcode-todo-policy/src/followup_tests.rs |
The digest is sent before validation and the final handoff, the final handoff is sent once, the gate budget trips with a notice, and new work re-arms the policy. |
| TC-9 | The on-disk layout, the tolerant snapshot load, and the effect application | crates/jcode-todo-policy/src/store.rs (inline mod tests) |
The file names match the runtime layout, a missing session yields an empty snapshot, and clearing the observations and marking the review delivered are idempotent. |
| TC-10 | The todo tool schema and input parsing |
crates/jcode-app-core/src/tool/todo.rs (inline mod tests) |
The schema advertises the intent, todos, plan, and goals properties with the constrained enums, hides the legacy keys, discloses no calibration wording, and parses native, stringified, and synonym inputs. |
| TC-11 | The todo tool merge, prune, and change-reporting logic | crates/jcode-app-core/src/tool/todo.rs (inline mod tests) |
Unmentioned goals and omitted fields are retained, a goal whose group is gone is dropped, the plan and goal changes list only the changed fields, and a forged score history is discarded in favor of the stored trail. |
| TC-12 | The todo telemetry derivation | crates/jcode-app-core/src/tool/todo.rs (inline mod tests) |
Created, completed, abandoned, group, and score summaries are derived, regrouping is not counted as creation or abandonment, and the empty state is all zeros. |
| TC-13 | The todo widget rendering in the info widget | crates/jcode-tui/src/tui/info_widget_tests.rs |
The item and aggregate confidence, the group headers, the exact pips for a small list, the feedback-loop suffix on the flat and grouped layouts, and the empty-goal case all render as expected. |
| TC-14 | Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. layout contention between the todo widget and the background task widget | crates/jcode-tui/src/tui/info_widget_layout_tests.rs |
The todo widget wins a short pocket without overlapping the background widget, and both place disjointly when there is room for two. |
| TC-15 | Auto-poke re-arm after the completion-gate circuit breaker | crates/jcode-tui/src/tui/app/tests/state_model_poke_03.rs |
Open work re-arms auto-poke and still produces a poke, so one breaker trip cannot silence the feature for the session. |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-16 | The todo tool writes the list, the plan, and the goals against an isolated home, and publishes the update |
crates/jcode-app-core/src/tool/todo.rs (inline async tests) |
The stored state matches the write, the bus event is published, and the panel shows only the current task. |
| TC-17 | The gate deferral end to end through the real tool | crates/jcode-app-core/src/tool/todo.rs (inline async tests) |
A moderate first write returns no continuation and records the observations instead, the histories accumulate, and a later climb changes the digest wording rather than erasing the point. |
| TC-18 | Goal creation, persistence, the memory mirror, session attachment, and resume | crates/jcode-base/src/goal_tests.rs |
The goal is stored under the project scope, mirrored into the memory graph, attached to the session, and returned by resume. |
| TC-19 | The goal page focus behaviour | crates/jcode-base/src/goal_tests.rs |
The first goal page takes the focus, and a page written later does not steal the focus from an unrelated page. |
| TC-20 | The initiative tool create, resume, list, and update actions |
crates/jcode-app-core/src/tool/goal_tests.rs |
Create and list publish no side panel update, resume returns the initiative with its next step, and update refreshes an open overview while keeping the focus on the goals page. |
| TC-21 | The todo state files, the gate observation log, and the long-session review clock | crates/jcode-base/src/todo.rs (inline mod tests) |
The observations round-trip and clear, the plan round-trips without the legacy key names, and the timed review is durable and fires only once. |
| TC-22 | The side panel page persistence, focus, and PDF budget | crates/jcode-base/src/side_panel_tests.rs |
Pages persist and focus the latest, deletion falls back to the most recent page, the focus revision tracks explicit intent, and the aggregate budget is enforced before mutation. |
| TC-23 | The TUITerminal User Interface todo card, the panel toggle, and the pinned payload | crates/jcode-tui/src/tui/app/tests/todo_card.rs |
The card toggles and never stacks, the panel subcommand toggles the screen, the card refreshes when the todos or the goal scores change, and the pinned payload is empty when the config is off. |
| TC-24 | The TUITerminal User Interface auto-poke cycles, the reload survival of the final handoff, and the peer poke handling | crates/jcode-tui/src/tui/app/tests/auto_poke_cycles.rs |
A todo-free turn keeps the feature armed, an unchanged list does not consume another turn, the final handoff survives a reload, a late observation does not resurrect the gates, and a peer poke is shown without a duplicate local poke. |
| TC-25 | The jcode run auto-poke loop |
src/cli/commands_tests.rs |
Incomplete todos are poked first, the deferred gate digest is delivered before the confidence check, the digest log survives a poke iteration that still has open work, and the loop stays silent once the confidence is earned. |
| TC-26 | The SDKSoftware Development Kit capability parity for the todo state surface | crates/jcode-sdk/src/sdk_tests/parity.rs |
The Rust and TypeScript SDKs both implement todo_state and ack_todo_follow_up, and neither exposes a public capability that is missing from the shared list. |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-27 | The pinned todo band render regressions on a fresh session | crates/jcode-tui/src/tui/ui_tests/pinned_todo_regressions.rs |
The band appears without consuming the prompt, the content height grows when the band appears, and a hidden todo tool message contributes zero transcript rows while the surrounding messages keep their positions. |
| TC-28 | The pinned band placement, the collapse control, and the hiding of the duplicate todo card | crates/jcode-tui/src/tui/app/tests/todo_card.rs |
The band renders below the sticky prompt with no separator, the more row expands and collapses the band, the todo tool card is hidden from the transcript while the band shows the item, and the pinned todos are omitted from the info widgets. |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-29 | An unknown todo status such as "blocked" is sent | The call is rejected with an error naming the valid vocabulary, and the error lists pending, in_progress, completed, and cancelled. |
| TC-30 | The provider sends the whole todos array as a JSON string, an item as a stringified object, and a numeric confidence as a string | The call succeeds, the array and the item are parsed, and the numeric confidence maps onto the closest semantic state. |
| TC-31 | The agent replaces the todo list with a new task while a goal for the finished task is still stored | The orphan goal is dropped so the panel does not show a stale goal, and the ungrouped goal of a flat list is kept while it still has items. |
| TC-32 | The model supplies its own confidence history, plan history, or goal history | The supplied trail is discarded in favor of the stored trail plus the current write's observation, so a climb cannot be fabricated. |
| TC-33 | A group is created and completed in a single write | The group is still observed, because a one-step completion is where a weak feedback loop would otherwise hide. |
| TC-34 | A session id such as "../x" is used to build a todo state path | The session id is reported as unsafe, and the path cannot escape the todo state directory. |
| TC-35 | A very long iterative turn records more observations than the cap | The log keeps only the most recent capped number of observations, and the digest loses no information it would have reported. |
| TC-36 | The completion gate never passes across more turns than the gate budget allows | The policy stops sending continuations, surfaces a stall notice, stays quiet until new work appears, and pokes again once new open work exists. |
| TC-37 | The user turns the auto-poke off and open work appears later | The poke stays off for the rest of the session, and the default-on re-arm does not undo the explicit turn-off. |
| TC-38 | Another window pokes the same open work | The peer poke is shown as a system notice, is not rendered as a user prompt, and this window does not send a duplicate poke. |
Test Infrastructure
- The pure policy crate needs no fixtures beyond in-memory structs, and it is the only place where the gate bars and the continuation text are pinned.
- The runtime tests isolate the state on disk with a temporary
JCODE_HOMEand thestorage::lock_test_envguard, so parallel tests do not share a todo directory. - The tool tests build a
ToolContextwith a synthetic session id and a temporary project directory. - The TUITerminal User Interface tests drive the app through
create_test_appand render it with the ratatuiTestBackend, and they serialize on the render and viewport snapshot locks. - The pinned band tests write an isolated
config.tomlwithdisplay.pin_todosand restore the previous home and config cache afterwards. - The SDKSoftware Development Kit parity test compares the Rust and TypeScript client sources against a shared capability list.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall persist a session-scoped todo list whose items carry content, status, priority, id, an optional group label, and evidence-state confidence fields, and shall reload it across turns and across session resume. | TC-1, TC-2, TC-9, TC-16, TC-21 |
| FR-2MustThe system shall accept only the todo statuses pending, in_progress, completed, and cancelled, shall canonicalize natural completion synonyms and case variants into them, and shall reject any other status with an error naming the valid vocabulary. | TC-10, TC-29, TC-30 |
| FR-3MustThe system shall group todos under an optional group label, one group per coherent goal, and shall render a grouped list with per-group headers and a flat list without them. | TC-13, TC-23 |
| FR-4MustThe system shall record a plan-level intent assessment exactly once per plan, holding the user's stated intention and how well the agent understands it, independently of any individual group. | TC-2, TC-11, TC-17 |
| FR-5MustThe system shall record a goal-level quality assessment per group, covering the closed feedback loop state, the concrete feedback loop, its relevance, coverage, traceability, the delivery state, difficulty, autonomy, iteration maturity, and any stopping evidence. | TC-1, TC-2, TC-11 |
| FR-6MustThe system shall distinguish a goal with a closed feedback loop from a goal whose success is a taste judgment, and shall require acceptance-aligned relevance and edge-and-integration coverage for goals at or above the involved difficulty level. | TC-3 |
| FR-7MustThe system shall record a forward-looking evidence state per todo, an evidence state at completion, and a tool-owned history of every distinct state a todo has carried, so that an evidence-driven rise is distinguishable from a bulk end-of-task stamp. | TC-5, TC-11, TC-32 |
| FR-8MustThe system shall defer the quality-gate checks to turn end, recording an observation for every failing check during the turn and replaying them once as a digest, with the single exception of a first plan write whose intent assessment is severely low. | TC-4, TC-17, TC-33 |
| FR-9MustThe system shall never reject a todo write because a gate would fail, and shall save the write first and enforce the gate after the turn ends. | TC-16, TC-17 |
| FR-10MustThe system shall merge each write with the stored state so that an omitted plan field, an omitted goal field, and a goal the write does not mention are all retained, and shall drop a goal whose todo group no longer exists. | TC-11, TC-31 |
| FR-11MustThe system shall generate every synthetic continuation message (the incomplete-todo poke, the intent check, the feedback-loop check, the ownership check, the completion-confidence check, the confidence-spike check, the gate digest, and the final-response handoff) from one shared policy layer, and shall keep the private thresholds, scores, and elapsed-time trigger out of the model-facing text. | TC-5, TC-6 |
| FR-12MustThe system shall classify those synthetic messages so the transcript never re-renders them as user prompts, and shall show a short user-facing notice in their place. | TC-5, TC-6 |
| FR-13MustThe system shall decide the next follow-up after a turn ends in a fixed order: the long-session review, the incomplete-todo poke, the gate digest, the ownership gate, the completion-confidence check, the confidence-spike check, and finally the final-response handoff. | TC-8, TC-25 |
| FR-14MustThe system shall bound the number of gate turns per completion cycle, surface a stall notice when the bound is reached, and re-arm for new work afterwards. | TC-8, TC-36 |
| FR-15MustThe system shall expose a `todo` tool that reads and writes the todo list, the plan, and the goal assessments, that publishes the update on the bus, and that records lifecycle telemetry. | TC-12, TC-16 |
| FR-16MustThe system shall expose an `initiative` tool that creates, lists, shows, resumes, updates, checkpoints, and focuses durable goals scoped to the project or to the user, and that refreshes an already-open goal side panel without stealing focus. | TC-18, TC-19, TC-20, TC-22 |
| FR-17MustThe system shall never open the side panel from the initiative tool, and shall leave the opening of the goals overview to an explicit user command. | TC-20, TC-22 |
| FR-18MustThe system shall surface the todo state in the terminal user interface as an inline chat card, an optional side-panel screen, an optional pinned band, and the persistent info widget, and shall keep the overall completed-of-total progress display visible in each of them. | TC-13, TC-23, TC-27, TC-28 |
| FR-19ShouldThe system shall derive a session title from the todo plan, preferring the group of the current or latest incomplete item, then the plan intention, then the item text. | TC-7 |
| FR-20ShouldThe system shall ship the same policy to the SDKSoftware Development Kit and to any embedding client, exposing the session todo state and a follow-up acknowledgement so those clients run the identical follow-up policy. | TC-8, TC-21, TC-26 |
| FR-21ShouldThe system shall load sessions recorded before the semantic-state migration, mapping legacy 0-100 numeric scores and the legacy field names onto the current semantic states. | TC-1, TC-2, TC-9, TC-21 |
| FR-22MayThe system shall let the user turn the auto-poke on and off, and shall make an explicit turn-off stick for the rest of the session. | TC-15, TC-24, TC-37, TC-38 |
| NFR-1MustThe model-visible tool schema and every synthetic continuation message shall not disclose the private thresholds, the numeric scores, or the evaluator vocabulary, so the model cannot target the evaluator instead of reporting an honest assessment. | TC-6, TC-10 |
| NFR-2MustThe model-visible tool schema shall not be biased toward one domain's validation vocabulary, so the feedback-loop guidance stays equally applicable to every kind of work. | TC-10 |
| NFR-3MustEach static quality-gate continuation message shall stay within an approximate budget of 64 tokens, so it reads as a nudge rather than as a replacement system prompt. | TC-6 |
| NFR-4MustA gate continuation shall name at most 6 todos explicitly and shall summarize the remainder, so a large plan cannot turn one nudge into a wall of text. | TC-6 |
| NFR-5MustThe deferred gate-observation log shall be capped per session, so a very long iterative turn cannot grow it without bound. | TC-35 |
| NFR-6MustA failure to persist the gate-observation log shall be logged and swallowed rather than failing the todo write itself. | TC-16, TC-17 |
| NFR-7MustA persisted session written under an earlier release shall still load, including the pre-rename field names and the earlier synthetic message wordings. | TC-1, TC-2, TC-5, TC-21 |
| NFR-8ShouldA session id used to build a todo state path shall be restricted to a safe character set, so a session id can never escape the todo state directory. | TC-9, TC-34 |
| NFR-9ShouldThe todo widget shall keep one logical row per visual row at narrow terminal widths, and shall truncate rather than wrap. | TC-13, TC-14 |
| NFR-10ShouldThe pinned todo band shall render below the sticky prompt, without a horizontal separator, and shall show the overall progress rather than a collapsed summary. | TC-27, TC-28 |
| NFR-11ShouldThe todo tool shall accept provider quirks that send tool arguments as JSON strings rather than native types, and shall reject only genuinely malformed input. | TC-10, TC-30 |
requirements
- None, the feature is implemented and the artifacts were derived from the code rather than from an open design question.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Productivity Reporting
Overview
jcode already stores every session transcript on the local disk, but that history is not visible to the user in any form. This feature turns the local history into a report the user can read and share, without sending anything to a server. A scan pass reads the local transcript store and produces one compact summary per session, an aggregation pass folds those summaries into a single report of sessions, prompts, tool calls, tokens, projects, and activity patterns, and two renderers turn the report into Markdown for the chat transcript and into a PNG dashboard saved with the other generated images. The report is reachable from the /productivity slash command, from the /wrapped and /stats aliases, and from the runtime productivity command used by non-terminal clients. This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | A readable summary of their own usage history that they can copy, paste, and share outside the terminal. |
| Maintainer | A deterministic report pipeline that reads only local data and can be exercised from unit tests. |
| Non-terminal clients | A machine-readable report and dashboard image over the runtime command surface. |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall scan the local session transcript store under the jcode home directory and produce one compact summary per transcript file. | Must | The system shall scan the local session transcript store under the jcode home directory and produce one compact summary per transcript file. |
| FR-2MustThe system shall reuse an incremental scan cache keyed by transcript file length and modification time so unchanged transcripts are not re-parsed on later runs. | Must | The system shall reuse an incremental scan cache keyed by transcript file length and modification time so unchanged transcripts are not re-parsed on later runs. |
| FR-3MustThe system shall aggregate the per-session summaries into a single report covering sessions, prompts, assistant messages, tool calls, images, token usage, typed characters, and active days. | Must | The system shall aggregate the per-session summaries into a single report covering sessions, prompts, assistant messages, tool calls, images, token usage, typed characters, and active days. |
| FR-4MustThe system shall tally tool calls per canonical tool name, expanding batched invocations so each inner tool call is counted, and normalizing legacy tool aliases to their canonical names. | Must | The system shall tally tool calls per canonical tool name, expanding batched invocations so each inner tool call is counted, and normalizing legacy tool aliases to their canonical names. |
| FR-5MustThe system shall render the report as Markdown suitable for display in the chat transcript. | Must | The system shall render the report as Markdown suitable for display in the chat transcript. |
| FR-6MustThe system shall render the report as a PNG dashboard image and save it to `generated-images/productivity-<timestamp>.png` under the jcode home directory. | Must | The system shall render the report as a PNG dashboard image and save it to generated-images/productivity-<timestamp>.png under the jcode home directory. |
| FR-7MustThe system shall expose the report through the `/productivity` slash command, with `/wrapped` and `/stats` accepted as aliases. | Must | The system shall expose the report through the /productivity slash command, with /wrapped and /stats accepted as aliases. |
| FR-8ShouldThe system shall generate the report off the user-interface thread and deliver the result to the session that requested it. | Should | The system shall generate the report off the user-interface thread and deliver the result to the session that requested it. |
| FR-9ShouldThe system shall copy the dashboard image to the system clipboard and open it in the default image viewer, and report which of those actions succeeded. | Should | The system shall copy the dashboard image to the system clipboard and open it in the default image viewer, and report which of those actions succeeded. |
| FR-10ShouldThe system shall derive activity buckets (code edits, commands run, searches, web actions) and shareable flavor (archetype, power score, badges) from the aggregated tallies. | Should | The system shall derive activity buckets (code edits, commands run, searches, web actions) and shareable flavor (archetype, power score, badges) from the aggregated tallies. |
| FR-11ShouldThe system shall expose the same report to non-terminal clients through the runtime `productivity` command, returning the structured report, the PNG path, and the PNG as base64. | Should | The system shall expose the same report to non-terminal clients through the runtime productivity command, returning the structured report, the PNG path, and the PNG as base64. |
| FR-12MayThe system shall record the activity calendar (hour of day, weekday, active dates) and the current and longest consecutive-day streaks. | May | The system shall record the activity calendar (hour of day, weekday, active dates) and the current and longest consecutive-day streaks. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustThe system shall perform every step locally, with no network request, no account, and no upload of transcript content. | Must | Privacy | The system shall perform every step locally, with no network request, no account, and no upload of transcript content. |
| NFR-2MustThe system shall complete a repeated run over an unchanged transcript store without re-parsing any file. | Must | Performance | The system shall complete a repeated run over an unchanged transcript store without re-parsing any file. |
| NFR-3MustThe system shall hold only a compact per-session summary in memory while scanning, not the full transcript content. | Must | Performance | The system shall hold only a compact per-session summary in memory while scanning, not the full transcript content. |
| NFR-4ShouldThe system shall count an unreadable or malformed transcript as a parse error and continue the scan. | Should | Reliability | The system shall count an unreadable or malformed transcript as a parse error and continue the scan. |
| NFR-5ShouldThe system shall keep the user interface responsive while the report is generated. | Should | Availability | The system shall keep the user interface responsive while the report is generated. |
| NFR-6ShouldThe system shall rasterize the dashboard locally, without a headless browser and without downloading fonts over the network. | Should | Portability | The system shall rasterize the dashboard locally, without a headless browser and without downloading fonts over the network. |
Constraints
- The report is derived only from transcripts that already exist on the local disk.
- Transcripts are read with a tolerant partial deserializer rather than the canonical session types, so the crate stays independent of the transcript schema.
- The dashboard is built as an SVG string in process and rasterized with a local SVG renderer.
- The scan cache lives beside the other jcode cache files and is keyed by a per-file fingerprint.
Acceptance Criteria
Every FR and NFR shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
Acceptance criteria verify how a requirement is proven done, they do not restate it. Write concrete, scenario-based criteria (happy path, edge cases and error states where applicable).
-
FR-1MustThe system shall scan the local session transcript store under the jcode home directory and produce one compact summary per transcript file.
gherkin @FR-1MustThe system shall scan the local session transcript store under the jcode home directory and produce one compact summary per transcript file. Scenario: Scan produces one summary per transcript Given a jcode home directory containing three transcript files under sessions When the scan runs Then three session summaries are produced and the report records three scanned files -
FR-2MustThe system shall reuse an incremental scan cache keyed by transcript file length and modification time so unchanged transcripts are not re-parsed on later runs.
gherkin @FR-2MustThe system shall reuse an incremental scan cache keyed by transcript file length and modification time so unchanged transcripts are not re-parsed on later runs. Scenario: Unchanged transcripts are not re-parsed Given a scan cache holding a fingerprint for every transcript When a second scan runs over the same unchanged transcripts Then every file is served from the cache and the cache hit count equals the number of transcripts -
FR-3MustThe system shall aggregate the per-session summaries into a single report covering sessions, prompts, assistant messages, tool calls, images, token usage, typed characters, and active days.
gherkin @FR-3MustThe system shall aggregate the per-session summaries into a single report covering sessions, prompts, assistant messages, tool calls, images, token usage, typed characters, and active days. Scenario: Totals are folded across sessions Given three sessions with ten user prompts, ten assistant messages, and twenty-three tool calls in total When the report is built Then the report records three sessions, ten prompts, ten assistant messages, and twenty-three tool calls -
FR-4MustThe system shall tally tool calls per canonical tool name, expanding batched invocations so each inner tool call is counted, and normalizing legacy tool aliases to their canonical names.
gherkin @FR-4MustThe system shall tally tool calls per canonical tool name, expanding batched invocations so each inner tool call is counted, and normalizing legacy tool aliases to their canonical names. Scenario: Batched calls are credited to the inner tools Given a session whose transcript contains one batch call wrapping two inner tool calls When the session is summarized Then the batch tool and each inner tool are each counted once -
FR-5MustThe system shall render the report as Markdown suitable for display in the chat transcript.
gherkin @FR-5MustThe system shall render the report as Markdown suitable for display in the chat transcript. Scenario: Markdown report contains the headline numbers Given a report built from one populated session When the Markdown is rendered Then the output contains the report title and the power score line -
FR-6MustThe system shall render the report as a PNG dashboard image and save it to `generated-images/productivity-<timestamp>.png` under the jcode home directory.
gherkin @FR-6MustThe system shall render the report as a PNG dashboard image and save it to `generated-images/productivity-<timestamp>.png` under the jcode home directory. Scenario: Dashboard is rasterized and saved Given a report built from one populated session When the report is generated Then the PNG bytes carry the PNG signature and a file named productivity-<timestamp>.png exists under generated-images in the jcode home directory -
FR-7MustThe system shall expose the report through the `/productivity` slash command, with `/wrapped` and `/stats` accepted as aliases.
gherkin @FR-7MustThe system shall expose the report through the `/productivity` slash command, with `/wrapped` and `/stats` accepted as aliases. Scenario: Command and its aliases start a report Given the local slash-command dispatcher When each of /productivity, /wrapped, and /stats is dispatched Then each is claimed by the dispatcher and starts a report generation without starting an agent turn -
FR-8ShouldThe system shall generate the report off the user-interface thread and deliver the result to the session that requested it.
gherkin @FR-8ShouldThe system shall generate the report off the user-interface thread and deliver the result to the session that requested it. Scenario: Result is delivered to the requesting session Given a report result addressed to session A When a session with a different id receives the result event Then the event is ignored and the report is not displayed -
FR-9ShouldThe system shall copy the dashboard image to the system clipboard and open it in the default image viewer, and report which of those actions succeeded.
gherkin @FR-9ShouldThe system shall copy the dashboard image to the system clipboard and open it in the default image viewer, and report which of those actions succeeded. Scenario: Clipboard failure is reported without losing the report Given the system clipboard is unavailable When the report result is handled Then the Markdown report is still displayed and the footer states that the image could not be copied -
FR-10ShouldThe system shall derive activity buckets (code edits, commands run, searches, web actions) and shareable flavor (archetype, power score, badges) from the aggregated tallies.
gherkin @FR-10ShouldThe system shall derive activity buckets (code edits, commands run, searches, web actions) and shareable flavor (archetype, power score, badges) from the aggregated tallies. Scenario: Activity buckets and flavor are derived Given a report with two edits, one apply patch, four bash calls, seven agentgrep calls, and one browser call When the report is built Then the code edit count is three, the command count is four, the search count is seven, the web action count is one, and the archetype and power score are populated -
FR-11ShouldThe system shall expose the same report to non-terminal clients through the runtime `productivity` command, returning the structured report, the PNG path, and the PNG as base64.
gherkin @FR-11ShouldThe system shall expose the same report to non-terminal clients through the runtime `productivity` command, returning the structured report, the PNG path, and the PNG as base64. Scenario: Runtime command returns the report and the image Given a runtime host with local transcripts When the productivity runtime command runs Then the response carries the serialized report, the saved PNG path, and the PNG as base64 with media type image/png -
FR-12MayThe system shall record the activity calendar (hour of day, weekday, active dates) and the current and longest consecutive-day streaks.
gherkin @FR-12MayThe system shall record the activity calendar (hour of day, weekday, active dates) and the current and longest consecutive-day streaks. Scenario: Activity calendar and streaks are recorded Given one session active on four distinct calendar dates including a run of three consecutive days When the report is built Then the report records four active days, the first and last active dates, and a longest streak of three days -
NFR-1MustThe system shall perform every step locally, with no network request, no account, and no upload of transcript content.
gherkin @NFR-1MustThe system shall perform every step locally, with no network request, no account, and no upload of transcript content. Scenario: Report generation makes no network call Given a machine with no network connectivity When the report is generated Then the report is produced and the dashboard is written to disk -
NFR-2MustThe system shall complete a repeated run over an unchanged transcript store without re-parsing any file.
gherkin @NFR-2MustThe system shall complete a repeated run over an unchanged transcript store without re-parsing any file. Scenario: Repeat run is served from the cache Given a transcript store that has already been scanned once When the report is generated a second time Then no transcript is re-parsed and the run completes faster than the first run -
NFR-3MustThe system shall hold only a compact per-session summary in memory while scanning, not the full transcript content.
gherkin @NFR-3MustThe system shall hold only a compact per-session summary in memory while scanning, not the full transcript content. Scenario: Only compact summaries are held in memory Given a large transcript store When the scan runs Then each transcript is reduced to a compact summary before it is retained and the full transcript is not kept -
NFR-4ShouldThe system shall count an unreadable or malformed transcript as a parse error and continue the scan.
gherkin @NFR-4ShouldThe system shall count an unreadable or malformed transcript as a parse error and continue the scan. Scenario: Malformed transcript does not abort the scan Given one transcript file that is not valid JSON When the scan runs Then the parse error count is one and the report is still produced from the remaining transcripts -
NFR-5ShouldThe system shall keep the user interface responsive while the report is generated.
gherkin @NFR-5ShouldThe system shall keep the user interface responsive while the report is generated. Scenario: Interface stays responsive during generation Given a report generation in flight When the user keeps typing Then the input is accepted while the generation continues in the background -
NFR-6ShouldThe system shall rasterize the dashboard locally, without a headless browser and without downloading fonts over the network.
gherkin @NFR-6ShouldThe system shall rasterize the dashboard locally, without a headless browser and without downloading fonts over the network. Scenario: Dashboard renders without a browser Given a host with a system font database and no network access When the dashboard is rasterized Then a PNG is produced from the locally built SVG
Conflicts
None identified yet.
Open Questions
- Should the report support a selectable time window (today, last 7 days, all time) instead of always covering all time?
Specification: Productivity Reporting
Overview
The feature is implemented in the workspace crate jcode-productivity-core (crates/jcode-productivity-core/) and is driven from the TUITerminal User Interface by the /productivity slash command (crates/jcode-tui/src/tui/app/productivity.rs) and from non-terminal clients by the runtime productivity command (crates/jcode-app-core/src/server/runtime_special_commands.rs). The crate is split into five modules: scan reads the local transcript store and maintains an incremental cache, aggregate folds the per-session summaries into a ProductivityReport, markdown renders the report for the chat transcript, dashboard builds an SVG and rasterizes it to PNG, and model holds the data types. The crate depends only on jcode-storage for path resolution, so the report is produced entirely from local data. This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
/productivity /wrapped /stats runtime command "productivity"
│ (jcode-app-core)
▼ │
crates/jcode-tui/src/tui/app/productivity.rs │
(spawns a worker thread, publishes a bus event) │
│ │
└──────────────► jcode_productivity_core::generate() ◄──┘
│
┌─────────────────────────────────┴──────────────────────────────┐
▼ ▼
scan::scan_all() aggregate::build_report()
reads ~/.jcode/sessions/*.json folds Vec<SessionSummary>
cache ~/.jcode/cache/productivity/summaries.json │
key (file_len, mtime_ns) ▼
│ ProductivityReport
▼ │
Vec<SessionSummary> ┌──────────────┴──────────────┐
▼ ▼
markdown::render_markdown dashboard::render_svg
(chat transcript) │
dashboard::render_png (usvg/resvg)
│
▼
~/.jcode/generated-images/productivity-<ts>.png
Data flow in one line: transcripts on disk, summaries in the scan cache, one aggregated report, two renderers, one PNG on disk and one Markdown block in the chat.
The TUITerminal User Interface never calls the crate on the UI thread. The command handler sets an in-flight flag, spawns a thread that runs generate(), and publishes the outcome as a BusEvent::ProductivityReportReady event carrying the originating session id.
Data Models
SessionSummary
The compact per-session aggregate that is cached between runs. One instance is produced per transcript file.
| Field | Type | Constraints | Description |
|---|---|---|---|
| first_ts | string | nullable | RFC3339 timestamp of the first timestamped message. |
| last_ts | string | nullable | RFC3339 timestamp of the last timestamped message. |
| created_at | string | nullable | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. creation timestamp from the transcript header. |
| updated_at | string | nullable | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. update timestamp from the transcript header. |
| project | string | nullable | Basename of the session working directory. |
| working_dir | string | nullable | Full working directory path. |
| provider_key | string | nullable | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). identifier recorded in the transcript. |
| model | string | nullable | Model identifier recorded in the transcript. |
| user_msgs | u32 | not null | Count of messages with role user. |
| assistant_msgs | u32 | not null | Count of messages with role assistant. |
| user_chars | u64 | not null | Characters typed by the human, excluding <system-reminder> blobs. |
| assistant_chars | u64 | not null | Characters produced by the assistant in text blocks. |
| tools | map | not null | Tool invocation histogram keyed by canonical tool name. |
| images | u32 | not null | Images attached or produced in the transcript. |
| input_tokens | u64 | not null | Sum of reported input tokens. |
| output_tokens | u64 | not null | Sum of reported output tokens. |
| cache_read_tokens | u64 | not null | Sum of reported cache-read tokens. |
| cache_creation_tokens | u64 | not null | Sum of reported cache-creation tokens. |
| hour_hist | array[24] | not null | Local-time activity histogram, one slot per hour of day. |
| weekday_hist | array[7] | not null | Local-time activity histogram, one slot per weekday with Monday at index 0. |
| active_dates | list[string] | not null | Sorted distinct local calendar dates on which the session was active. |
SessionSummary::total_tool_calls() sums the tool histogram into a u64.
Tally
A single named, sortable metric used for the top-N lists in the report.
| Field | Type | Constraints | Description |
|---|---|---|---|
| name | string | not null | Label of the counted item, such as a project name or a tool name. |
| count | u64 | not null | Number of occurrences. |
ProductivityReport
The fully computed report. It is serializable so the same structure backs the Markdown, the PNG, and the runtime command payload.
| Field | Type | Constraints | Description |
|---|---|---|---|
| generated_at | string | not null | Local timestamp of the report generation, formatted as YYYY-MM-DD HH:MM. |
| total_sessions | u64 | not null | Number of sessions folded into the report. |
| total_messages | u64 | not null | Sum of user and assistant messages. |
| user_prompts | u64 | not null | Sum of user messages. |
| assistant_messages | u64 | not null | Sum of assistant messages. |
| total_tool_calls | u64 | not null | Sum of all tool histogram entries. |
| total_images | u64 | not null | Sum of images across sessions. |
| input_tokens | u64 | not null | Sum of input tokens. |
| output_tokens | u64 | not null | Sum of output tokens. |
| cache_read_tokens | u64 | not null | Sum of cache-read tokens. |
| cache_creation_tokens | u64 | not null | Sum of cache-creation tokens. |
| user_chars | u64 | not null | Sum of characters typed by the human. |
| user_words | u64 | not null | Approximate prompt word count, derived as user_chars / 5. |
| assistant_chars | u64 | not null | Sum of characters produced by the assistant. |
| first_day | string | nullable | Earliest active calendar date. |
| last_day | string | nullable | Latest active calendar date. |
| active_days | u64 | not null | Number of distinct active calendar dates. |
| span_days | u64 | not null | Inclusive day span between the first and last active dates. |
| current_streak | u64 | not null | Consecutive active days ending today or yesterday. |
| longest_streak | u64 | not null | Longest run of consecutive active days. |
| busiest_day | Tally | nullable | Active date with the highest message count. |
| hour_hist | array[24] | not null | Folded hour-of-day histogram. |
| weekday_hist | array[7] | not null | Folded weekday histogram. |
| peak_hour | u8 | not null | Hour slot with the highest activity. |
| chronotype | string | not null | Label derived from the peak hour. |
| top_projects | list[Tally] | not null | Up to 8 projects ranked by session count. |
| distinct_projects | u64 | not null | Number of distinct project names. |
| top_tools | list[Tally] | not null | Up to 10 tools ranked by call count. |
| top_models | list[Tally] | not null | Up to 6 models ranked by message count, excluding <synthetic>. |
| top_providers | list[Tally] | not null | Up to 6 providers ranked by message count. |
| code_edits | u64 | not null | Calls to edit, write, multiedit, apply_patch, patch, and replace. |
| commands_run | u64 | not null | Calls to bash. |
| searches | u64 | not null | Calls to grep, agentgrep, and glob. |
| web_actions | u64 | not null | Calls to browser, websearch, and webfetch. |
| longest_session_msgs | u64 | not null | Largest message count in a single session. |
| avg_session_msgs | f64 | not null | Mean message count per session. |
| archetype | string | not null | Shareable activity archetype label. |
| archetype_blurb | string | not null | One-line explanation of the archetype. |
| power_score | u64 | not null | Weighted headline score. |
| badges | list[string] | not null | Shareable badge labels earned by the activity profile. |
| scanned_files | u64 | not null | Number of transcripts read or served from cache. |
| parse_errors | u64 | not null | Number of transcripts that failed to parse. |
| scan_secs | f64 | not null | Wall-clock seconds spent in the scan. |
| cache_hits | u64 | not null | Number of transcripts served from the scan cache. |
ProductivityOutput
The bundle returned by jcode_productivity_core::generate().
| Field | Type | Constraints | Description |
|---|---|---|---|
| report | ProductivityReport | not null | The aggregated report. |
| markdown | string | not null | Rendered Markdown for the chat transcript. |
| png | Vec\<u8> | not null | PNG dashboard bytes, identical to the saved file. |
| png_path | PathBuf | not null | Absolute path of the saved PNG. |
API Contracts
This feature defines no HTTP surface, so there is no api.yaml alongside this document.
The feature is reached through two command contracts.
| Command | Surface | Purpose |
|---|---|---|
/productivity, /wrapped, /stats |
TUITerminal User Interface slash command | Generate the report, print the Markdown, and copy and open the dashboard PNG. |
productivity |
Runtime command (RuntimeCommand::Productivity) |
Return the structured report, the saved PNG path, and the PNG as base64 to non-terminal clients. |
The runtime command accepts no arguments, or the single argument status or show; any other argument is rejected with This command accepts only status or show.
The runtime response is a JSON object with these fields.
| Field | Type | Description |
|---|---|---|
| report | object | The serialized ProductivityReport. |
| png_path | string | Path of the saved dashboard PNG. |
| image.media_type | string | Always image/png. |
| image.base64 | string | Standard base64 encoding of the PNG bytes. |
| scope | string | Always runtime host. |
The runtime command also returns the rendered Markdown as its human-readable message.
The slash command writes a footer under the Markdown report that names the saved PNG path and states whether the image was copied to the clipboard and whether it was opened in an image viewer.
Sequences
Slash command report generation
sequenceDiagram
autonumber
participant U as User
participant T as TUITerminal User Interface command handler
participant W as Worker thread
participant C as jcode-productivity-core
participant D as Local disk
participant B as Event bus
U->>T: /productivity
T->>T: set in-flight flag, show scanning notice
T->>W: spawn worker
W->>C: generate()
C->>D: read transcripts and scan cache
D-->>C: transcripts and cached summaries
C->>C: aggregate summaries into report
C->>C: render Markdown and SVG, rasterize PNG
C->>D: write generated-images/productivity-<ts>.png
C-->>W: report, Markdown, PNG bytes, PNG path
W->>B: publish ProductivityReportReady(session_id, result)
B->>T: deliver event to the session
T->>T: copy PNG to clipboard, open image viewer
T->>U: display Markdown report and footer
Runtime command report generation
sequenceDiagram
autonumber
participant C as Non-terminal client
participant R as Runtime command handler
participant P as jcode-productivity-core
participant D as Local disk
C->>R: productivity
R->>R: reject unexpected arguments
R->>P: generate() on a blocking task
P->>D: read transcripts and scan cache
P->>D: write dashboard PNG
P-->>R: report, Markdown, PNG bytes, PNG path
R-->>C: JSON payload with report, png_path, base64 PNG, plus the Markdown message
Incremental scan
sequenceDiagram
autonumber
participant S as scan::scan_all
participant C as Cache file
participant F as Transcript file
S->>C: read summaries.json
C-->>S: cached entries keyed by file name
S->>S: enumerate sessions/*.json and fingerprint each file
loop for each transcript, in parallel
alt length and mtime match the cache
S->>S: reuse the cached summary, count a cache hit
else the file changed or is new
S->>F: read and parse the transcript
F-->>S: summary, or a parse error
end
end
S->>C: rewrite the cache with the surviving entries
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| The feature lives in its own workspace crate | jcode-productivity-core |
Keeps the reporting code out of the TUITerminal User Interface and the app core, and lets the app core call it without a TUITerminal User Interface dependency. |
| Transcripts are parsed with a tolerant partial deserializer | Local RawSession and RawMessage types with serde defaults |
The crate stays dependency-light and keeps working when the canonical transcript schema drifts. |
| The scan keeps an on-disk cache keyed by file fingerprint | (file_len, mtime_ns) per file name, stored at cache/productivity/summaries.json |
Transcripts can number in the tens of thousands; re-parsing all of them on every run is not viable. |
| The cache is rewritten from the current scan | Entries for deleted transcripts are dropped | The cache never grows without bound and stays consistent with the store. |
| A cache format version invalidates stale entries | CACHE_VERSION bumped when summary semantics change |
A semantic change in the summary must not reuse summaries computed under the old rules. |
| The cache is best-effort | Read and parse failures fall back to an empty cache | A corrupted cache must never block the report. |
| Parsing is parallelized | rayon over the file list |
The scan is the expensive part and the per-file work is independent. |
| Only compact summaries are retained | Vec<SessionSummary> instead of raw transcripts |
Memory stays bounded over multi-gigabyte histories. |
| Batch tool calls are expanded | The inner calls of a batch invocation are counted individually |
Otherwise a single batched turn hides most of the tool usage from the report. |
| Legacy tool names are normalized | file_read, file_write, file_edit, file_grep, and todowrite map to read, write, edit, grep, and todo |
Old transcripts and new transcripts must contribute to the same tally. |
| Activity buckets are derived from the tool tally | Fixed tool groups map to code edits, commands, searches, and web actions | The buckets make the report comparable without a second pass over the transcripts. |
| The dashboard is hand-built SVG rasterized to PNG | usvg plus resvg with the system font database |
No headless browser and no network font download; the output is deterministic per machine. |
| Emoji are stripped from dashboard text | ascii_only keeps ASCII plus a small set of punctuation |
The system sans font cannot render emoji, and the PNG must not show tofu boxes. |
| Generation runs off the UI thread | A worker thread publishes BusEvent::ProductivityReportReady |
A cold scan over a large history takes seconds, and the interface must stay responsive. |
| The result event carries the session id | ProductivityReportReady { session_id, result } |
A report requested in one session must not be rendered in another. |
| Clipboard access is best-effort | Wayland wl-copy, then xclip, then arboard |
Clipboard tooling varies per desktop, and a missing clipboard tool must not lose the report. |
| The report is exposed over the runtime command surface | RuntimeCommand::Productivity |
Non-terminal clients need the same report and image that the TUITerminal User Interface shows. |
Risks and Unknowns
- The transcript schema is read with a partial deserializer, so a change to the on-disk format can silently drop a metric rather than fail loudly.
- The scan cache is keyed by length and modification time, so a transcript edited in place with the same length and the same timestamp granularity is served stale.
- The
user_wordsfigure is a proxy derived from characters, not a real word count. - The dashboard depends on the system font database, so a machine without the expected fonts renders a different poster than a machine with them.
- The power score, archetype, and badges are tuned constants, so the thresholds are a matter of taste rather than a measured model.
- Clipboard and image-viewer integration is only exercised on the desktop platforms that ship the expected tools.
Out of Scope
- Any hosted service, account, upload, or network call in the reporting path.
- A selectable report time window; the report always covers all recorded history.
- Editing, pruning, or summarizing the underlying transcripts.
- A historical series of past reports; each run produces a fresh report from the current store.
Test Plan: Productivity Reporting
Scope
Covers the aggregation, rendering, and failure-handling behavior of the productivity report.
The unit tests build reports from in-memory SessionSummary values, so they exercise the aggregation and both renderers without touching the transcript store.
The integration test covers the TUITerminal User Interface side of the report lifecycle, the delivery of the result event, and the failure path.
Out of scope: the disk scan and the incremental cache, which have no automated test and are exercised through the crate example harness.
Coverage gaps: no automated test covers the scan, the cache, the command aliases, the clipboard integration, or the runtime productivity command.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Aggregate per-session summaries into report totals, activity buckets, project count, power score, and archetype | crates/jcode-productivity-core/src/tests.rs, test aggregates_basic_totals, three sessions with ten prompts, ten assistant messages, twenty-three tool calls, and five code edits |
Report records three sessions, ten prompts, ten assistant messages, twenty-three tool calls, five code edits, four commands, seven searches, one web action, two distinct projects, a power score above zero, and a non-empty archetype |
| TC-2 | Rank the top-N lists by count in descending order | crates/jcode-productivity-core/src/tests.rs, test top_lists_sorted_desc, two alpha sessions and one gamma session |
The first project is alpha with count two, and the first tool is read with count fifteen |
| TC-3 | Deduplicate active dates and compute the longest consecutive-day streak | crates/jcode-productivity-core/src/tests.rs, test streaks_and_active_days_dedup, one session active on 2026-05-10, 2026-05-11, 2026-05-12, and 2026-05-20 |
Report records four active days, a longest streak of three days, a first day of 2026-05-10, and a last day of 2026-05-20 |
| TC-4 | Render the Markdown, the SVG, and the PNG for a populated report | crates/jcode-productivity-core/src/tests.rs, test renders_markdown_and_png, one session with four prompts and ten tool calls |
The Markdown contains the report title and the power score, the SVG starts with <svg and contains a text element, and the PNG is larger than 1000 bytes and carries the PNG signature |
| TC-5 | Render an empty report without failing | crates/jcode-productivity-core/src/tests.rs, test empty_report_is_safe, an empty summary list |
The report records zero sessions, the Markdown still contains the report title, and the PNG is produced and carries the PNG signature |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-6 | Handle a failed report result delivered over the remote bus event path | crates/jcode-tui/src/tui/app/tests/remote_events_reload_01/part_01.rs, test test_remote_bus_productivity_failure_clears_refresh_state, a test app with the in-flight flag set and a result event carrying the error generation failed |
The event is handled, the in-flight flag is cleared, the status notice reads Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. failed, and the last display message contains the error text |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-7 | Manual end-to-end run of the full pipeline against the real transcript store, through the crate example harness | Run cargo run -p jcode-productivity-core --example run (crates/jcode-productivity-core/examples/run.rs) on a machine with transcripts under the jcode home directory |
The harness prints the scan counters (scanned, parse_errors, cache_hits, scan_secs) and the Markdown report, and a dashboard PNG is written under generated-images in the jcode home directory. A second run reports a cache hit for every transcript and a shorter scan time |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-8 | One transcript file is not valid JSON | The file is counted as a parse error, the scan continues over the remaining transcripts, and the report is still produced |
| TC-9 | The scan cache file is missing or corrupted | The cache read and parse failure is ignored, the scan starts from an empty cache, and the report is still produced |
| TC-10 | The scan cache was written by an older cache format | The version mismatch discards the cached entries and the transcripts are re-parsed |
| TC-11 | There are no transcripts at all | The report records zero sessions, the Markdown still renders, and the PNG is still produced |
| TC-12 | The system clipboard is unavailable | The Markdown report is still displayed and the footer states that the image could not be copied |
| TC-13 | A second report is requested while one is already generating | The second request is refused with a status notice and no second generation is started |
| TC-14 | A report result arrives for a different session | The event is ignored and nothing is displayed |
| TC-15 | A report result carries an error instead of a payload | The in-flight flag is cleared, an error message is displayed, and the status notice reports the failure (covered by TC-6) |
| TC-16 | A dashboard label contains emoji the system font cannot render | The emoji are stripped before the SVG is built so the PNG shows no tofu boxes |
Test Infrastructure
crates/jcode-productivity-core/src/tests.rsis the crate's#[cfg(test)]module and runs withcargo test -p jcode-productivity-core.- All unit tests build their inputs as in-memory
SessionSummaryvalues, so they need no fixtures, no transcript files, and no network access. - The PNG assertions check the PNG signature and a minimum byte size, because the exact bytes depend on the system font database of the test machine.
- The TUITerminal User Interface integration test uses the shared
create_test_app()helper and a dummy remote connection fromcrates/jcode-tui/src/tui/backend/. crates/jcode-productivity-core/examples/run.rsis a manual harness rather than an automated test; it exercises the real scan, the real cache, and the real PNG write.- No productivity test file exists under the repository-level
tests/directory.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall scan the local session transcript store under the jcode home directory and produce one compact summary per transcript file. | TC-7, TC-8 |
| FR-2MustThe system shall reuse an incremental scan cache keyed by transcript file length and modification time so unchanged transcripts are not re-parsed on later runs. | TC-7, TC-9, TC-10 |
| FR-3MustThe system shall aggregate the per-session summaries into a single report covering sessions, prompts, assistant messages, tool calls, images, token usage, typed characters, and active days. | TC-1, TC-3 |
| FR-4MustThe system shall tally tool calls per canonical tool name, expanding batched invocations so each inner tool call is counted, and normalizing legacy tool aliases to their canonical names. | TC-1, TC-2 |
| FR-5MustThe system shall render the report as Markdown suitable for display in the chat transcript. | TC-4, TC-5 |
| FR-6MustThe system shall render the report as a PNG dashboard image and save it to `generated-images/productivity-<timestamp>.png` under the jcode home directory. | TC-4, TC-5, TC-7 |
| FR-7MustThe system shall expose the report through the `/productivity` slash command, with `/wrapped` and `/stats` accepted as aliases. | TC-7 |
| FR-8ShouldThe system shall generate the report off the user-interface thread and deliver the result to the session that requested it. | TC-6, TC-14 |
| FR-9ShouldThe system shall copy the dashboard image to the system clipboard and open it in the default image viewer, and report which of those actions succeeded. | TC-6, TC-12, TC-13 |
| FR-10ShouldThe system shall derive activity buckets (code edits, commands run, searches, web actions) and shareable flavor (archetype, power score, badges) from the aggregated tallies. | TC-1, TC-2 |
| FR-11ShouldThe system shall expose the same report to non-terminal clients through the runtime `productivity` command, returning the structured report, the PNG path, and the PNG as base64. | TC-7 |
| FR-12MayThe system shall record the activity calendar (hour of day, weekday, active dates) and the current and longest consecutive-day streaks. | TC-3 |
| NFR-1MustThe system shall perform every step locally, with no network request, no account, and no upload of transcript content. | TC-4, TC-7 |
| NFR-2MustThe system shall complete a repeated run over an unchanged transcript store without re-parsing any file. | TC-7, TC-9, TC-10 |
| NFR-3MustThe system shall hold only a compact per-session summary in memory while scanning, not the full transcript content. | TC-1, TC-3 |
| NFR-4ShouldThe system shall count an unreadable or malformed transcript as a parse error and continue the scan. | TC-8 |
| NFR-5ShouldThe system shall keep the user interface responsive while the report is generated. | TC-6, TC-13 |
| NFR-6ShouldThe system shall rasterize the dashboard locally, without a headless browser and without downloading fonts over the network. | TC-4, TC-16 |
requirements
- Should the report support a selectable time window (today, last 7 days, all time) instead of always covering all time?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time.
Overview
CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. is an opt-in execution mode where the model writes a short JavaScript program that orchestrates harness tool calls instead of issuing one tool call per model turn.
The program runs inside an embedded QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. sandbox hosted by jcode, and only what the script returns, plus its captured console output, reaches the transcript, so intermediate results never enter the conversation.
The mode is enabled with [tools] codemode = true or the JCODE_CODEMODE=1 environment variable, and it is off by default.
This feature documents already-implemented code that was reverse-engineered from the repository during an SDLC sync.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | Fewer and larger tool rounds, so long task chains cost fewer tokens and finish faster |
| Model and agent authors | A programmable way to chain, filter, and parallelize tool calls inside a single turn |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. owners | A per-session scratch store so a script can reuse data without refetching it |
| Maintainers | A sandbox that exposes no host capability beyond the tools the session already allows |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall expose the `codemode` tool only when codemode is enabled in config through `[tools] codemode = true` or through the `JCODE_CODEMODE` environment variable, and shall leave the tool unexposed when it is disabled. | Must | The system shall expose the codemode tool only when codemode is enabled in config through [tools] codemode = true or through the JCODE_CODEMODE environment variable, and shall leave the tool unexposed when it is disabled. |
| FR-2MustThe system shall execute the model-written program as the body of an async function inside an embedded QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. runtime, so the script can use `await` and `return`. | Must | The system shall execute the model-written program as the body of an async function inside an embedded QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. runtime, so the script can use await and return. |
| FR-3MustThe system shall let a script invoke any other tool available to the session through `await tools.<name>(args)` and `await callTool(name, args)`, and shall raise a JavaScript `Error` inside the script when a tool call fails. | Must | The system shall let a script invoke any other tool available to the session through await tools.<name>(args) and await callTool(name, args), and shall raise a JavaScript Error inside the script when a tool call fails. |
| FR-4MustThe system shall route every tool call made from a script through the harness tool registry, so session allow and deny policy, tool hooks, and MCP routing apply to script calls. | Must | The system shall route every tool call made from a script through the harness tool registry, so session allow and deny policy, tool hooks, and MCP routing apply to script calls. |
| FR-5MustThe system shall keep intermediate results inside the sandbox, so only the script's return value and its captured console output reach the transcript. | Must | The system shall keep intermediate results inside the sandbox, so only the script's return value and its captured console output reach the transcript. |
| FR-6MustThe system shall report a failed script to the model, and shall raise the run as a tool error when the script produced no tool calls and no console output. | Must | The system shall report a failed script to the model, and shall raise the run as a tool error when the script produced no tool calls and no console output. |
| FR-7MustThe system shall expose a per-session JSON store to the script through `store(key, value)`, `load(key)`, and `storedKeys()`, and shall persist it between codemode calls in the same session. | Must | The system shall expose a per-session JSON store to the script through store(key, value), load(key), and storedKeys(), and shall persist it between codemode calls in the same session. |
| FR-8ShouldThe system shall let a script discover the tools it may call through `listTools(filter?)` and `describeTool(name)`. | Should | The system shall let a script discover the tools it may call through listTools(filter?) and describeTool(name). |
| FR-9ShouldThe system shall decode a tool's text output into a parsed JSON value when the output is a JSON object or array, and into a string otherwise. | Should | The system shall decode a tool's text output into a parsed JSON value when the output is a JSON object or array, and into a string otherwise. |
| FR-10ShouldThe system shall exclude the `codemode` and `batch` tools from the set of tools a script may reach. | Should | The system shall exclude the codemode and batch tools from the set of tools a script may reach. |
| FR-11ShouldThe system shall report the number of tool calls, the elapsed time, and the names of the stored keys alongside the script result. | Should | The system shall report the number of tool calls, the elapsed time, and the names of the stored keys alongside the script result. |
| FR-12ShouldThe system shall cap the report returned to the model at a fixed character budget and mark the report as truncated when the cap is reached. | Should | The system shall cap the report returned to the model at a fixed character budget and mark the report as truncated when the cap is reached. |
| FR-13ShouldThe system shall report an unknown tool name together with the names of similar available tools and a pointer to `listTools()`. | Should | The system shall report an unknown tool name together with the names of similar available tools and a pointer to listTools(). |
| FR-14MayThe system shall capture `console.log`, `console.info`, `console.warn`, `console.error`, and `console.debug` output, prefixing every level above `info` with its level name. | May | The system shall capture console.log, console.info, console.warn, console.error, and console.debug output, prefixing every level above info with its level name. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustThe sandbox shall expose no filesystem, network, timer, or process API, and shall reach the outside world only through host-routed tool calls. | Must | Security | The sandbox shall expose no filesystem, network, timer, or process API, and shall reach the outside world only through host-routed tool calls. |
| NFR-2MustEvery run shall be bounded by a QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. heap limit, a wall-clock timeout, a maximum tool call count, and a maximum captured console size. | Must | Resource control | Every run shall be bounded by a QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. heap limit, a wall-clock timeout, a maximum tool call count, and a maximum captured console size. |
| NFR-3MustThe system shall report codemode as unavailable on FreeBSD, where the QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. bindings have no prebuilt artifact, without failing the build. | Must | Availability | The system shall report codemode as unavailable on FreeBSD, where the QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. bindings have no prebuilt artifact, without failing the build. |
| NFR-4ShouldEach run shall execute on a dedicated thread with a current-thread runtime, so the non-`Send` QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. engine stays thread-confined while host calls run on the caller's runtime. | Should | Isolation | Each run shall execute on a dedicated thread with a current-thread runtime, so the non-Send QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. engine stays thread-confined while host calls run on the caller's runtime. |
| NFR-5ShouldDropping the run future shall cancel the script, and tearing a run down shall abort the tool calls still in flight. | Should | Reliability | Dropping the run future shall cancel the script, and tearing a run down shall abort the tool calls still in flight. |
| NFR-6ShouldIndependent tool calls made by one script shall run concurrently rather than one after another. | Should | Performance | Independent tool calls made by one script shall run concurrently rather than one after another. |
| NFR-7ShouldEvery run shall be logged with the session id, the tool call count, the elapsed time, and the error, if any. | Should | Observability | Every run shall be logged with the session id, the tool call count, the elapsed time, and the error, if any. |
| NFR-8MayThe QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. dependency shall be optional per target, so a target without prebuilt bindings still builds. | May | Portability | The QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. dependency shall be optional per target, so a target without prebuilt bindings still builds. |
Constraints
- The feature is experimental and opt-in, and it is off in the default config.
- The sandbox runs where the harness runs, not where
bashruns. - The embedded QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. engine is not
Send, so each run is confined to a single thread. - The
codemodetool description is exempt from the shared tool-description token cap because it documents the sandbox API. - The QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. C build lives in its own workspace crate so it is compiled once and cached.
Acceptance Criteria
Every FR and NFR shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
-
FR-1MustThe system shall expose the `codemode` tool only when codemode is enabled in config through `[tools] codemode = true` or through the `JCODE_CODEMODE` environment variable, and shall leave the tool unexposed when it is disabled.
```gherkin @FR-1MustThe system shall expose the `codemode` tool only when codemode is enabled in config through `[tools] codemode = true` or through the `JCODE_CODEMODE` environment variable, and shall leave the tool unexposed when it is disabled. Scenario: Tool is exposed when codemode is enabled in config Given the config section "[tools] codemode = true" When the session tool registry is built Then the registry contains a tool named "codemode"
@FR-1MustThe system shall expose the `codemode` tool only when codemode is enabled in config through `[tools] codemode = true` or through the `JCODE_CODEMODE` environment variable, and shall leave the tool unexposed when it is disabled. Scenario: Tool is absent when codemode is disabled Given the default config where "tools.codemode" is false When the session tool registry is built Then the registry contains no tool named "codemode"
@FR-1MustThe system shall expose the `codemode` tool only when codemode is enabled in config through `[tools] codemode = true` or through the `JCODE_CODEMODE` environment variable, and shall leave the tool unexposed when it is disabled. Scenario: Environment variable enables codemode Given the environment variable "JCODE_CODEMODE" set to "1" And the config leaves "tools.codemode" false When the session tool registry is built Then the registry contains a tool named "codemode" ```
-
FR-2MustThe system shall execute the model-written program as the body of an async function inside an embedded QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. runtime, so the script can use `await` and `return`.
gherkin @FR-2MustThe system shall execute the model-written program as the body of an async function inside an embedded QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. runtime, so the script can use `await` and `return`. Scenario: Script body runs as an async function Given a script "const a = await tools.echo({}); return a;" When the script runs Then the result is the value the script returned -
FR-3MustThe system shall let a script invoke any other tool available to the session through `await tools.<name>(args)` and `await callTool(name, args)`, and shall raise a JavaScript `Error` inside the script when a tool call fails.
```gherkin @FR-3MustThe system shall let a script invoke any other tool available to the session through `await tools.<name>(args)` and `await callTool(name, args)`, and shall raise a JavaScript `Error` inside the script when a tool call fails. Scenario: Script calls a session tool Given a script that awaits "tools.echo({ x: 1 })" When the script runs Then the tool is invoked with the arguments the script passed And the tool result reaches the script as a value
@FR-3MustThe system shall let a script invoke any other tool available to the session through `await tools.<name>(args)` and `await callTool(name, args)`, and shall raise a JavaScript `Error` inside the script when a tool call fails. Scenario: A failing tool throws inside the script Given a tool that always fails And a script that awaits the failing tool inside a try block When the script runs Then the script catches an Error whose message names the failing tool ```
-
FR-4MustThe system shall route every tool call made from a script through the harness tool registry, so session allow and deny policy, tool hooks, and MCP routing apply to script calls.
gherkin @FR-4MustThe system shall route every tool call made from a script through the harness tool registry, so session allow and deny policy, tool hooks, and MCP routing apply to script calls. Scenario: SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. policy applies to script calls Given a session policy that denies the tool "shout" And a script that lists the available tools When the script runs Then the denied tool is absent from the listed tools -
FR-5MustThe system shall keep intermediate results inside the sandbox, so only the script's return value and its captured console output reach the transcript.
gherkin @FR-5MustThe system shall keep intermediate results inside the sandbox, so only the script's return value and its captured console output reach the transcript. Scenario: Intermediate results stay in the sandbox Given a script that calls a tool three times and returns a summary When the script runs Then the transcript receives the summary, the console output, and a tool call count And the transcript receives no intermediate tool output -
FR-6MustThe system shall report a failed script to the model, and shall raise the run as a tool error when the script produced no tool calls and no console output.
```gherkin @FR-6MustThe system shall report a failed script to the model, and shall raise the run as a tool error when the script produced no tool calls and no console output. Scenario: A script error is reported to the model Given a script that throws an Error When the script runs Then the report contains the error message
@FR-6MustThe system shall report a failed script to the model, and shall raise the run as a tool error when the script produced no tool calls and no console output. Scenario: A failure with no side effects is a tool error Given a script that throws before calling any tool When the script runs Then the tool call fails with the script error ```
-
FR-7MustThe system shall expose a per-session JSON store to the script through `store(key, value)`, `load(key)`, and `storedKeys()`, and shall persist it between codemode calls in the same session.
gherkin @FR-7MustThe system shall expose a per-session JSON store to the script through `store(key, value)`, `load(key)`, and `storedKeys()`, and shall persist it between codemode calls in the same session. Scenario: A stored value is visible to a later run in the same session Given a first script that stores a value under the key "n" When a second script in the same session loads that key Then the second script receives the stored value -
FR-8ShouldThe system shall let a script discover the tools it may call through `listTools(filter?)` and `describeTool(name)`.
gherkin @FR-8ShouldThe system shall let a script discover the tools it may call through `listTools(filter?)` and `describeTool(name)`. Scenario: Tool discovery from inside a script Given a script that calls "listTools()" and "describeTool(\"echo\")" When the script runs Then the script receives the tool names, the tool descriptions, and the tool input schema -
FR-9ShouldThe system shall decode a tool's text output into a parsed JSON value when the output is a JSON object or array, and into a string otherwise.
```gherkin @FR-9ShouldThe system shall decode a tool's text output into a parsed JSON value when the output is a JSON object or array, and into a string otherwise. Scenario: JSON tool output is decoded Given a tool that returns a JSON object as text When a script calls the tool Then the script receives a parsed object
@FR-9ShouldThe system shall decode a tool's text output into a parsed JSON value when the output is a JSON object or array, and into a string otherwise. Scenario: Plain text tool output stays a string Given a tool that returns plain text When a script calls the tool Then the script receives the text as a string ```
-
FR-10ShouldThe system shall exclude the `codemode` and `batch` tools from the set of tools a script may reach.
gherkin @FR-10ShouldThe system shall exclude the `codemode` and `batch` tools from the set of tools a script may reach. Scenario: Recursion and batch are not reachable Given a script that calls "tools.codemode" When the script runs Then the call fails with an unknown tool error for "codemode" -
FR-11ShouldThe system shall report the number of tool calls, the elapsed time, and the names of the stored keys alongside the script result.
gherkin @FR-11ShouldThe system shall report the number of tool calls, the elapsed time, and the names of the stored keys alongside the script result. Scenario: The run footer reports calls, time, and stored keys Given a script that calls one tool and stores one key When the run report is rendered Then the report shows "1 tool call", the elapsed seconds, and the stored key name -
FR-12ShouldThe system shall cap the report returned to the model at a fixed character budget and mark the report as truncated when the cap is reached.
gherkin @FR-12ShouldThe system shall cap the report returned to the model at a fixed character budget and mark the report as truncated when the cap is reached. Scenario: An oversized report is truncated Given a run whose report exceeds the report budget When the report is rendered Then the report is capped and states that it was truncated -
FR-13ShouldThe system shall report an unknown tool name together with the names of similar available tools and a pointer to `listTools()`.
gherkin @FR-13ShouldThe system shall report an unknown tool name together with the names of similar available tools and a pointer to `listTools()`. Scenario: An unknown tool name suggests alternatives Given a script that calls the tool "ech" When the script runs Then the error names the unknown tool and suggests the tool "echo" -
FR-14MayThe system shall capture `console.log`, `console.info`, `console.warn`, `console.error`, and `console.debug` output, prefixing every level above `info` with its level name.
gherkin @FR-14MayThe system shall capture `console.log`, `console.info`, `console.warn`, `console.error`, and `console.debug` output, prefixing every level above `info` with its level name. Scenario: Console output is captured with level prefixes Given a script that logs "hi" and an object at level "log" and "careful" at level "warn" When the script runs Then the captured lines are "hi {\"a\":1}" and "[warn] careful" -
NFR-1MustThe sandbox shall expose no filesystem, network, timer, or process API, and shall reach the outside world only through host-routed tool calls.
gherkin @NFR-1MustThe sandbox shall expose no filesystem, network, timer, or process API, and shall reach the outside world only through host-routed tool calls. Scenario: No host API is reachable from the script Given a script that checks "require", "process", "fetch", "setTimeout", "std", and "os" When the script runs Then every one of them is undefined -
NFR-2MustEvery run shall be bounded by a QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. heap limit, a wall-clock timeout, a maximum tool call count, and a maximum captured console size.
```gherkin @NFR-2MustEvery run shall be bounded by a QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. heap limit, a wall-clock timeout, a maximum tool call count, and a maximum captured console size. Scenario: A busy loop hits the wall clock limit Given a script that loops forever And a run timeout of 300 ms When the script runs Then the run fails with a timeout error
@NFR-2MustEvery run shall be bounded by a QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. heap limit, a wall-clock timeout, a maximum tool call count, and a maximum captured console size. Scenario: A run stops at the tool call limit Given a run limit of 3 tool calls And a script that calls a tool five times When the script runs Then the run fails with a tool call limit error
@NFR-2MustEvery run shall be bounded by a QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. heap limit, a wall-clock timeout, a maximum tool call count, and a maximum captured console size. Scenario: A run stops at the heap limit Given a run heap limit of 8 MB And a script that allocates without bound When the script runs Then the run fails with an error ```
-
NFR-3MustThe system shall report codemode as unavailable on FreeBSD, where the QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. bindings have no prebuilt artifact, without failing the build.
gherkin @NFR-3MustThe system shall report codemode as unavailable on FreeBSD, where the QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. bindings have no prebuilt artifact, without failing the build. Scenario: A FreeBSD build reports codemode as unavailable Given a build targeting FreeBSD When the codemode availability flag is read Then the flag is false And a run returns the "not available on FreeBSD" error -
NFR-4ShouldEach run shall execute on a dedicated thread with a current-thread runtime, so the non-`Send` QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. engine stays thread-confined while host calls run on the caller's runtime.
gherkin @NFR-4ShouldEach run shall execute on a dedicated thread with a current-thread runtime, so the non-`Send` QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. engine stays thread-confined while host calls run on the caller's runtime. Scenario: A run is confined to one thread Given a script that calls a tool When the script runs Then the script executes on a dedicated codemode thread And the tool call runs on the runtime that started the run -
NFR-5ShouldDropping the run future shall cancel the script, and tearing a run down shall abort the tool calls still in flight.
gherkin @NFR-5ShouldDropping the run future shall cancel the script, and tearing a run down shall abort the tool calls still in flight. Scenario: Dropping the run future cancels the script Given a run that is waiting on a tool that never returns When the run future is dropped Then the script stops without blocking the caller -
NFR-6ShouldIndependent tool calls made by one script shall run concurrently rather than one after another.
gherkin @NFR-6ShouldIndependent tool calls made by one script shall run concurrently rather than one after another. Scenario: Independent calls run concurrently Given a script that starts 20 independent tool calls with "Promise.all" And a tool that takes 50 ms When the script runs Then the run finishes in under 800 ms -
NFR-7ShouldEvery run shall be logged with the session id, the tool call count, the elapsed time, and the error, if any.
gherkin @NFR-7ShouldEvery run shall be logged with the session id, the tool call count, the elapsed time, and the error, if any. Scenario: Every run is logged Given a completed run When the run is inspected in the log Then the log line names the session, the tool call count, the elapsed time, and the error -
NFR-8MayThe QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. dependency shall be optional per target, so a target without prebuilt bindings still builds.
gherkin @NFR-8MayThe QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. dependency shall be optional per target, so a target without prebuilt bindings still builds. Scenario: A target without prebuilt bindings still builds Given a target where the QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. bindings are not prebuilt When the workspace is built Then the build succeeds and codemode reports itself unavailable
Conflicts
None identified yet.
Open Questions
- The per-run limits and the report budget are hard-coded rather than configurable, so it is undecided whether they should become config settings.
- It is undecided whether the session store should be scoped per tool call, per turn, or per session beyond its current session-wide lifetime.
- It is undecided whether a script that makes no tool calls and returns a value should be reported as a success or as a no-op.
Specification: CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time.
Overview
CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. is implemented in two places.
crates/jcode-codemode is the sandbox crate, and it holds the embedded QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. runtime, the Host trait that bridges the sandbox to the harness, the Limits type, and the run entry point.
crates/jcode-app-core/src/tool/codemode.rs is the harness side, and it holds the codemode tool, the RegistryHost implementation that routes script calls through Registry::execute, the per-session store on disk, and the report renderer.
The script is evaluated as the body of an async function, a prelude installs the tools proxy and the discovery helpers, and every tool call is marshalled back to the caller's Tokio runtime through the Host trait.
This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
model turn
│ tool call: codemode { code }
▼
crates/jcode-app-core/src/tool/codemode.rs (CodemodeTool)
│ ├─ loads the session tool definitions (Registry::definitions_for_session)
│ │ └─ drops "codemode" and "batch"
│ ├─ loads the session store (~/.jcode/codemode/<session>.json)
│ └─ calls jcode_codemode::run(code, host, tools, store, limits)
▼
crates/jcode-codemode/src/engine.rs (QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. engine)
│ ├─ dedicated thread "jcode-codemode" plus a current-thread Tokio runtime
│ ├─ QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. runtime: heap limit, 1 MB stack, interrupt handler (deadline and cancel flag)
│ ├─ prelude: console, tools proxy, callTool, listTools, describeTool, store/load/storedKeys
│ └─ __callTool → Host::call_tool → spawn on the caller's runtime
▼
Host::call_tool (RegistryHost)
│ └─ Registry::execute(name, args, sub_ctx)
▼
built-in tools, MCP tools, tool hooks, session allow and deny policy
The script runs inside the harness process, not inside the process that bash runs in.
It has no filesystem, network, timer, or process API.
The only way out of the sandbox is a tool call, and the harness routes that call through its normal registry and session policy.
Data Models
Host trait (crates/jcode-codemode/src/lib.rs)
| Field | Type | Constraints | Description |
|---|---|---|---|
| call_tool | fn(&self, name: String, args: Value) -> BoxFuture<'static, Result<Value, String>> |
required | Executes a tool on behalf of the script. Ok carries the decoded result and Err becomes a thrown Error inside the script. |
The trait is Send + Sync + 'static, so the harness can hold it across threads even though the JavaScript engine is not Send.
ToolInfo
| Field | Type | Constraints | Description |
|---|---|---|---|
| name | string | not null | The name the script uses to call the tool. |
| description | string | not null | The full tool description, returned by describeTool. |
| input_schema | JSON value | not null | The JSON Schema of the tool arguments, returned by describeTool. |
listTools returns only the name and the first non-empty line of the description, capped at 200 characters.
Limits
| Field | Type | Constraints | Description |
|---|---|---|---|
| memory_bytes | usize | not null | The QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. heap limit in bytes. The default is 64 MB. |
| timeout | Duration | not null | The wall-clock limit for the whole script, including awaited tool calls. The default is 300 s. |
| max_tool_calls | usize | not null | The maximum number of tool calls per run. The default is 2000. |
| max_log_bytes | usize | not null | The maximum number of bytes of captured console output. The default is 64 KB. |
RunOutput
| Field | Type | Constraints | Description |
|---|---|---|---|
| result | optional JSON value | not null | The JSON value the script returned, and None for undefined. |
| error | optional string | not null | The error message when the script threw, timed out, or was cancelled. |
| logs | list of strings | not null | The captured console lines. |
| logs_truncated | bool | not null | Whether log capture hit max_log_bytes. |
| tool_calls | usize | not null | The number of tool calls the script made. |
| store | map of string to JSON value | not null | The session store after the run, persisted by the caller between runs. |
| elapsed | Duration | not null | The wall-clock duration of the run. |
CodemodeInput (crates/jcode-app-core/src/tool/codemode.rs)
| Field | Type | Constraints | Description |
|---|---|---|---|
| code | string | required, aliases script, source, and js |
The body of the async JavaScript function to run. |
API Contracts
This feature defines no HTTP API, so there is no api.yaml alongside this document.
The contract is the tool schema the model sees and the script API that the prelude installs.
codemode tool schema
| Field | Type | Required | Description |
|---|---|---|---|
| code | string | yes | The body of an async JavaScript function. Use await and return. |
| intent | string | no | The shared per-call intent string that every jcode tool accepts. |
Script API
| Global | Kind | Description |
|---|---|---|
tools |
Proxy | tools.<name>(args) calls a tool. The in operator reports whether a tool exists, and Object.keys(tools) lists the tool names. |
callTool(name, args) |
async function | Calls a tool whose name is not a valid identifier. |
listTools(filter?) |
function | Returns [{name, description}], optionally filtered by a case-insensitive substring of the name or the description. |
describeTool(name) |
function | Returns {name, description, input_schema} for one tool, or undefined when the tool is unknown. |
store(key, value) |
function | Writes a JSON value into the session store and returns it. |
load(key) |
function | Reads a JSON value from the session store, or undefined when the key is absent. |
storedKeys() |
function | Returns the keys currently in the session store. |
console.log, console.info, console.warn, console.error, console.debug |
functions | Appends to the captured console buffer. |
Failure modes
| Condition | Code | Description |
|---|---|---|
| Empty script | code is empty |
The code argument was blank. |
| Unknown tool | unknown tool '<name>' |
The script called a tool that is not exposed to the session. The message lists similar names and points at listTools(). |
| Tool call limit | tool call limit reached (N per run) |
The run made more tool calls than max_tool_calls. |
| Invalid arguments | arguments are not JSON or arguments must be an object, got <value> |
The script passed arguments the harness could not dispatch. |
| Tool failure | <tool>: <error> |
The host tool returned an error, and the script sees a thrown Error. |
| Timeout | timed out after <N>s |
The wall-clock limit was reached. |
| Cancelled | cancelled |
The run future was dropped. |
| Out of memory | <message> (memory limit reached) |
The QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. heap limit was reached. |
| Unsupported platform | codemode is not available on FreeBSD builds |
The build has no QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. engine. |
Sequences
The model writes a script and the harness runs it
Model → codemode { code }
→ CodemodeTool::execute
→ load the session tool definitions, minus "codemode" and "batch"
→ load the session store
→ jcode_codemode::run
→ spawn the thread "jcode-codemode"
→ build a current-thread Tokio runtime
→ create the QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. runtime and apply the heap and stack limits
→ install the globals and evaluate the prelude
→ evaluate "(async () => { <code> })()"
→ await the thread's result
→ save the session store
→ render the report
→ ToolOutput { report, title "codemode: N calls" }
A script calls a tool
Script → tools.<name>(args)
→ __callTool(name, JSON.stringify(args))
→ check that the tool is exposed to the session
→ check the tool call limit
→ Host::call_tool(name, args)
→ RegistryHost → Registry::execute(name, args, sub_ctx)
→ the built-in or MCP tool, under session policy and hooks
→ spawn the host future on the caller's runtime
→ { ok: true, value } or { ok: false, error }
→ the prelude throws an Error when ok is false
The script returns a value
Script → return value
→ the async function promise resolves
→ JSON.stringify(value)
→ serde_json parse
→ RunOutput.result
→ render_report
→ the console lines
→ the result, pretty printed, with strings kept raw
→ the footer: tool call count, elapsed seconds, stored keys
→ the report is truncated to the report budget
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Own workspace crate for the sandbox | crates/jcode-codemode |
The QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. C build compiles once and is cached, and app-core edits do not recompile it. |
Embedded QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. through rquickjs |
rquickjs 0.14 with the futures feature |
A small embeddable engine with no external runtime to install. |
| Thread-confined engine with a spawned host bridge | A dedicated thread plus a current-thread runtime, and host calls spawned on the caller's runtime | QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. runtimes are not Send, but host futures only need to be Send. |
| Only the harness registry is reachable | RegistryHost calls Registry::execute |
SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. policy, hooks, and MCP routing keep working inside a script. |
codemode and batch are not reachable from a script |
The EXCLUDED list |
It avoids recursion, and Promise.all already covers what batch does. |
| Per-session store on disk | ~/.jcode/codemode/<session>.json, written to a temp file and then renamed |
The store survives a restart, and the rename keeps the file from being left half written. |
| A report budget with an explicit truncation marker | 60 000 characters, plus a message telling the model to return a smaller value | A single tool result has to stay inside the model context. |
| The engine is an optional dependency per target | cfg(not(target_os = "freebsd")) |
rquickjs-sys ships no prebuilt FreeBSD bindings, and building them needs libclang. |
| Opt-in by default | [tools] codemode = false in the default config |
The mode is experimental and it changes how the model spends its turns. |
Risks and Unknowns
- The per-run limits and the report budget are hard-coded, so there is no way to tune them without a rebuild.
- A script can still call any tool the session allows, including destructive ones, so the tool-level permission model is the only guard.
- The store file is named after a sanitized session id, so two sessions whose ids sanitize to the same string would share one store file.
- QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. interruption is polled, so a script stuck in a single long-running operation may only be stopped at the next interrupt point.
- The QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. C build lengthens the build for every new contributor, and it is the reason the engine cannot be enabled on FreeBSD today.
- The sandbox runs in the harness process, so a script that drives many expensive tools can consume the same resources as the harness itself.
Out of Scope
- A remote or networked sandbox.
- Adding filesystem, network, timer, or process APIs to the script environment.
- Streaming partial results from a running script back into the transcript.
- Configuring the per-run limits or the report budget through the config file.
- Making the
codemodetool available by default. - Replacing the
batchtool, which keeps its own behavior.
Test Plan: CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time.
Scope
Two test files cover this feature.
crates/jcode-codemode/src/tests.rs drives the sandbox crate through its public run API with a mock Host, and the file is compiled only on non-FreeBSD targets through #[cfg(all(test, not(target_os = "freebsd")))].
crates/jcode-app-core/src/tool/codemode_tests.rs drives the codemode tool through Registry::execute with a registry that holds two stub tools.
Out of scope: the internals of the QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. engine, the harness tools that a script calls, the persistence of the store file on disk, and provider behavior.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Tool output decoding, decode_tool_output_parses_json_only_when_structured in crates/jcode-codemode/src/tests.rs |
decode_tool_output called with {"a":1}, [1,2], plain, and {not json} |
A parsed object, a parsed array, the string plain, and the raw string {not json} |
| TC-2 | Report rendering, report_renders_strings_raw_and_lists_store_keys in crates/jcode-app-core/src/tool/codemode_tests.rs |
render_report called with a string result, one tool call, and one stored key |
The report starts with result:\nplain text, contains [1 tool call,, and contains stored: k] |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-3 | Return value is captured, returns_json_value in crates/jcode-codemode/src/tests.rs |
A script that returns an object and a mapped array | The result is {"a":1,"b":[2,4,6]} and no error is reported |
| TC-4 | An undefined return is reported, undefined_return_is_none in crates/jcode-codemode/src/tests.rs |
A script that only assigns a variable | The result is None and no error is reported |
| TC-5 | Tool calls through the proxy and through callTool, calls_tools_via_proxy_and_call_tool in crates/jcode-codemode/src/tests.rs |
A script that awaits tools.echo({x:1}) and callTool("echo",{y:2}) |
Both results reach the script and the tool call count is 2 |
| TC-6 | Independent tool calls run concurrently, parallel_tool_calls_run_concurrently in crates/jcode-codemode/src/tests.rs |
A script that starts 20 slow calls with Promise.all |
20 results are returned and the run finishes in under 800 ms |
| TC-7 | A tool failure is catchable inside the script, tool_errors_throw_and_can_be_caught in crates/jcode-codemode/src/tests.rs |
A script that catches the failing tool and returns the error message | The result is fail: boom and no run error is reported |
| TC-8 | An uncaught error is reported, uncaught_errors_are_reported in crates/jcode-codemode/src/tests.rs |
A script that throws new Error('nope') |
The run error contains nope |
| TC-9 | A syntax error is reported, syntax_errors_are_reported in crates/jcode-codemode/src/tests.rs |
A script with invalid syntax | The run reports an error |
| TC-10 | An unknown tool name suggests alternatives, unknown_tools_suggest_alternatives in crates/jcode-codemode/src/tests.rs |
A script that calls tools.ech({}) |
The error names ech, suggests echo, and the tool call count is 0 |
| TC-11 | Console output is captured with level prefixes, console_output_is_captured in crates/jcode-codemode/src/tests.rs |
A script that logs one line at level log and one at level warn |
The captured lines are hi {"a":1} and [warn] careful |
| TC-12 | Console capture is bounded, log_capture_is_bounded in crates/jcode-codemode/src/tests.rs |
100 console lines and a 100 byte log limit | The output is marked as truncated and fewer than 100 lines are kept |
| TC-13 | The store persists across runs, store_persists_across_runs in crates/jcode-codemode/src/tests.rs |
A first script that stores a value, and a second script that loads it | The first run lists the key, the second run returns the incremented value, and a missing key loads as undefined |
| TC-14 | The discovery helpers work, discovery_helpers_work in crates/jcode-codemode/src/tests.rs |
A script that calls listTools(), listTools("slo"), describeTool("echo"), and checks 'echo' in tools |
The script receives the tool names, the filtered names, the first description line, the input schema, and true |
| TC-15 | A busy loop hits the wall-clock limit, busy_loops_time_out in crates/jcode-codemode/src/tests.rs |
An infinite loop and a 300 ms timeout | The run error contains timed out |
| TC-16 | A hung tool call hits the wall-clock limit, hung_tool_calls_time_out in crates/jcode-codemode/src/tests.rs |
A tool that never returns and a 300 ms timeout | The run error contains timed out and the test finishes in under 5 s |
| TC-17 | The heap limit is enforced, memory_limit_is_enforced in crates/jcode-codemode/src/tests.rs |
An unbounded allocation loop and an 8 MB limit | The run reports an error |
| TC-18 | The tool call limit is enforced, tool_call_limit_is_enforced in crates/jcode-codemode/src/tests.rs |
5 tool calls and a limit of 3 | The run error contains limit |
| TC-19 | No host API is exposed, no_host_apis_are_exposed in crates/jcode-codemode/src/tests.rs |
A script that checks require, process, fetch, setTimeout, std, and os |
Every one of them is undefined |
| TC-20 | Dropping the run future cancels the script, dropping_the_future_cancels in crates/jcode-codemode/src/tests.rs |
A run future waiting on a tool that never returns | The surrounding timeout fires, and the test runtime is not blocked |
| TC-21 | A script composes registry tools, script_composes_registry_tools in crates/jcode-app-core/src/tool/codemode_tests.rs |
A registry holding a lookup tool and a shout tool, and a script that calls both in parallel |
The report contains the computed total, the uppercased text, the console line, and a 4 tool call count |
| TC-22 | A script cannot call codemode or batch, script_cannot_call_itself_or_batch in crates/jcode-app-core/src/tool/codemode_tests.rs |
A script that lists the tools and a script that calls tools.codemode |
codemode is absent from the listed tools, and the recursive call fails with unknown tool 'codemode' |
| TC-23 | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. policy applies inside scripts, session_policy_applies_inside_scripts in crates/jcode-app-core/src/tool/codemode_tests.rs |
A session policy that denies shout |
shout is absent from the listed tools, and 'shout' in tools is false |
| TC-24 | A pure failure is surfaced as a tool error, uncaught_errors_without_side_effects_are_tool_errors in crates/jcode-app-core/src/tool/codemode_tests.rs |
A script that throws before calling any tool | The tool call fails and the error contains broken script |
End-to-End Tests
None exist today.
- The sandbox tests call jcode_codemode::run directly with a mock host, so they never touch the harness registry.
- The harness tests call Registry::execute("codemode", ...) with stub tools, so they never reach a real provider or a real model turn.
- The gap is the join between the two, which is a model turn that emits a codemode tool call and receives the rendered report.
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-4 | The script returns undefined |
The result is None and the run reports no error |
| TC-7 | The script calls a tool that fails | The failure becomes a thrown Error that the script can catch |
| TC-9 | The script has a syntax error | The run reports an error and the script never starts |
| TC-10 | The script calls a tool that does not exist | The error names the tool, suggests similar names, and counts no tool call |
| TC-12 | The script logs more than the log budget allows | The console output is truncated and the truncation is reported |
| TC-13 | The script loads a key that was never stored | load returns undefined |
| TC-15 | The script loops forever | The wall-clock limit stops the run and the error names the timeout |
| TC-16 | A tool call never returns | The wall-clock limit stops the run while the tool call is still in flight |
| TC-17 | The script allocates without bound | The heap limit stops the run and the run reports an error |
| TC-18 | The script calls tools past the call limit | The call is refused with a limit error |
| TC-19 | The script reaches for a host API | Every host API is undefined, so the script can only act through a tool |
| TC-20 | The caller drops the run future | The script is cancelled and the test runtime is not blocked |
| TC-22 | The script tries to call codemode |
The recursive call is refused as an unknown tool |
| TC-23 | The session policy denies a tool | The denied tool is absent from the tools a script can reach |
| TC-24 | The script fails before any side effect | The tool call fails, so the model can retry |
Test Infrastructure
- The mock host in
crates/jcode-codemode/src/tests.rsimplements theHosttrait with the toolsecho,fail,slow(50 ms), andhang(1 hour), and it counts the calls it receives. - The stub registry in
crates/jcode-app-core/src/tool/codemode_tests.rsbuilds aRegistry::empty()that holds a JSON tool namedlookupand a text tool namedshout, plus thecodemodetool itself. - The sandbox test module only builds on non-FreeBSD targets, so the FreeBSD availability path is asserted by reading the
AVAILABLEconstant rather than by running a script. crates/jcode-app-core/src/tool/tests.rsexemptscodemodefrom the shared 20 token tool-description cap, because the description documents the sandbox API.- Run the suites with
cargo test -p jcode-codemodeandcargo test -p jcode-app-core codemode.
Coverage Matrix
Requirements with no automated test are listed with the reason, so the gaps stay visible.
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall expose the `codemode` tool only when codemode is enabled in config through `[tools] codemode = true` or through the `JCODE_CODEMODE` environment variable, and shall leave the tool unexposed when it is disabled. | Not covered, because no test asserts the config or environment enablement gate |
| FR-2MustThe system shall execute the model-written program as the body of an async function inside an embedded QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. runtime, so the script can use `await` and `return`. | TC-3, TC-4, TC-5 |
| FR-3MustThe system shall let a script invoke any other tool available to the session through `await tools.<name>(args)` and `await callTool(name, args)`, and shall raise a JavaScript `Error` inside the script when a tool call fails. | TC-5, TC-7, TC-21 |
| FR-4MustThe system shall route every tool call made from a script through the harness tool registry, so session allow and deny policy, tool hooks, and MCP routing apply to script calls. | TC-21, TC-23 |
| FR-5MustThe system shall keep intermediate results inside the sandbox, so only the script's return value and its captured console output reach the transcript. | TC-21 |
| FR-6MustThe system shall report a failed script to the model, and shall raise the run as a tool error when the script produced no tool calls and no console output. | TC-8, TC-9, TC-24 |
| FR-7MustThe system shall expose a per-session JSON store to the script through `store(key, value)`, `load(key)`, and `storedKeys()`, and shall persist it between codemode calls in the same session. | TC-13, TC-2 |
| FR-8ShouldThe system shall let a script discover the tools it may call through `listTools(filter?)` and `describeTool(name)`. | TC-14, TC-22 |
| FR-9ShouldThe system shall decode a tool's text output into a parsed JSON value when the output is a JSON object or array, and into a string otherwise. | TC-1, TC-21 |
| FR-10ShouldThe system shall exclude the `codemode` and `batch` tools from the set of tools a script may reach. | TC-22 |
| FR-11ShouldThe system shall report the number of tool calls, the elapsed time, and the names of the stored keys alongside the script result. | TC-2, TC-21 |
| FR-12ShouldThe system shall cap the report returned to the model at a fixed character budget and mark the report as truncated when the cap is reached. | Not covered, because the report truncation helper has no test |
| FR-13ShouldThe system shall report an unknown tool name together with the names of similar available tools and a pointer to `listTools()`. | TC-10 |
| FR-14MayThe system shall capture `console.log`, `console.info`, `console.warn`, `console.error`, and `console.debug` output, prefixing every level above `info` with its level name. | TC-11, TC-12 |
| NFR-1MustThe sandbox shall expose no filesystem, network, timer, or process API, and shall reach the outside world only through host-routed tool calls. | TC-19 |
| NFR-2MustEvery run shall be bounded by a QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. heap limit, a wall-clock timeout, a maximum tool call count, and a maximum captured console size. | TC-15, TC-16, TC-17, TC-18 |
| NFR-3MustThe system shall report codemode as unavailable on FreeBSD, where the QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. bindings have no prebuilt artifact, without failing the build. | Not covered, because the sandbox test module is compiled out on FreeBSD |
| NFR-4ShouldEach run shall execute on a dedicated thread with a current-thread runtime, so the non-`Send` QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. engine stays thread-confined while host calls run on the caller's runtime. | Not asserted directly, because TC-5 and TC-20 exercise the bridge between the script thread and the caller's runtime without checking the thread itself |
| NFR-5ShouldDropping the run future shall cancel the script, and tearing a run down shall abort the tool calls still in flight. | TC-16, TC-20 |
| NFR-6ShouldIndependent tool calls made by one script shall run concurrently rather than one after another. | TC-6 |
| NFR-7ShouldEvery run shall be logged with the session id, the tool call count, the elapsed time, and the error, if any. | Not covered, because the run is logged to the log file rather than to the test output |
| NFR-8MayThe QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. dependency shall be optional per target, so a target without prebuilt bindings still builds. | Not covered, because the optional dependency is a build configuration property |
requirements
- The per-run limits and the report budget are hard-coded rather than configurable, so it is undecided whether they should become config settings.
- It is undecided whether the session store should be scoped per tool call, per turn, or per session beyond its current session-wide lifetime.
- It is undecided whether a script that makes no tool calls and returns a value should be reported as a success or as a no-op.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Agent Applets
Overview
Today the agent can only return text to the user, so any interactive interface it produces is described in prose and the user has to translate it into action. Agent applets let a provider describe native UI declaratively instead. A provider (the agent itself, an MCP server, a local process, or native desktop code) emits a validated tree of closed-set native components, the host renders that tree and owns layout, theme and input, and the host sends user intents back to the provider as actions. No provider code runs in the host process, so an applet cannot compromise the app. This feature documents already-implemented functionality that was reverse-engineered from the existing codebase during an SDLC sync.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Agent authors | A way to show interactive native UI instead of printing instructions |
| Desktop users | Rich, themed, interactive surfaces that live in the workspace rather than in the transcript |
| Desktop app team | A rendering surface that keeps providers outside the host process |
| MCP server authors | A way to ship UI alongside a tool result, without a custom client |
| Maintainer | A versioned schema that stays compatible as node types are added |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall define a versioned applet wire schema (`jcode.applet/1`) whose view is a tree drawn from a closed set of native node types, so a provider describes UI without shipping code to the host. | Must | The system shall define a versioned applet wire schema (jcode.applet/1) whose view is a tree drawn from a closed set of native node types, so a provider describes UI without shipping code to the host. |
| FR-2MustThe system shall validate every document against the schema, the structural limits, and the capabilities the applet declares before the document is stored or rendered. | Must | The system shall validate every document against the schema, the structural limits, and the capabilities the applet declares before the document is stored or rendered. |
| FR-3MustThe system shall expose an `applet` tool to the agent with `mount`, `update`, `patch`, `move`, `close` and `list` actions. | Must | The system shall expose an applet tool to the agent with mount, update, patch, move, close and list actions. |
| FR-4MustThe system shall mount an instance under a generated session-local identifier when the agent does not supply one. | Must | The system shall mount an instance under a generated session-local identifier when the agent does not supply one. |
| FR-5MustThe system shall persist mounted instances per session, one file per session under the jcode home directory, and remove the file when the last instance in the session is closed. | Must | The system shall persist mounted instances per session, one file per session under the jcode home directory, and remove the file when the last instance in the session is closed. |
| FR-6MustThe system shall apply incremental updates as revision-checked patch operations restricted to the `/view`, `/state` and `/title` paths, and shall reject a patch as a whole when its result does not validate. | Must | The system shall apply incremental updates as revision-checked patch operations restricted to the /view, /state and /title paths, and shall reject a patch as a whole when its result does not validate. |
| FR-7MustThe system shall move a mounted instance to a different placement and bump the instance's document revision. | Must | The system shall move a mounted instance to a different placement and bump the instance's document revision. |
| FR-8MustThe system shall close an instance, remove it from the session snapshot, and report whether the instance existed. | Must | The system shall close an instance, remove it from the session snapshot, and report whether the instance existed. |
| FR-9MustThe system shall stream the complete set of mounted instances for a session to connected clients as a full-snapshot event on every change. | Must | The system shall stream the complete set of mounted instances for a session to connected clients as a full-snapshot event on every change. |
| FR-10MustThe system shall route a user intent back to the agent as a compact action message carrying the action name, the action arguments, the instance's current state, and the key of the node that emitted it. | Must | The system shall route a user intent back to the agent as a compact action message carrying the action name, the action arguments, the instance's current state, and the key of the node that emitted it. |
| FR-11MustThe system shall let the agent block on an applet tool call until a user action arrives on that instance, with a bounded wait. | Must | The system shall let the agent block on an applet tool call until a user action arrives on that instance, with a bounded wait. |
| FR-12MustThe system shall store host-supplied user state into an instance without changing the instance's document revision. | Must | The system shall store host-supplied user state into an instance without changing the instance's document revision. |
| FR-13ShouldThe system shall support the standalone panel, sidebar, overlay, composer strip, background and inline placements, with inline anchored to a tool call, a message, or the end of the conversation. | Should | The system shall support the standalone panel, sidebar, overlay, composer strip, background and inline placements, with inline anchored to a tool call, a message, or the end of the conversation. |
| FR-14ShouldThe system shall render MCP-UI resources returned by an MCP tool as mounted applets anchored to the tool call that produced them. | Should | The system shall render MCP-UI resources returned by an MCP tool as mounted applets anchored to the tool call that produced them. |
| FR-15MayThe system shall render sandboxed HTML inside an applet, gated by the `html` capability. | May | The system shall render sandboxed HTML inside an applet, gated by the html capability. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustNo provider code shall run in the host process. The host renders a declarative tree and executes only its own built-in host actions. | Must | Security | No provider code shall run in the host process. The host renders a declarative tree and executes only its own built-in host actions. |
| NFR-2MustThe host shall accept node types it does not know, render their fallback text, and round-trip them losslessly, so a provider built against a newer host still works on an older host. | Must | Compatibility | The host shall accept node types it does not know, render their fallback text, and round-trip them losslessly, so a provider built against a newer host still works on an older host. |
| NFR-3MustThe number of mounted instances per session shall be bounded at 64, and every document shall be bounded by structural limits on depth, node count, text size, asset size, asset count, table cells, HTML size and state size. | Must | Resource | The number of mounted instances per session shall be bounded at 64, and every document shall be bounded by structural limits on depth, node count, text size, asset size, asset count, table cells, HTML size and state size. |
| NFR-4MustHost actions and image sources shall be rejected unless the applet declares the matching capability, and `host.open_url` shall accept only `http`, `https` and `mailto` URLs. | Must | Security | Host actions and image sources shall be rejected unless the applet declares the matching capability, and host.open_url shall accept only http, https and mailto URLs. |
| NFR-5ShouldA failed mount, patch, move or state write shall leave the persisted session state unchanged. | Should | Availability | A failed mount, patch, move or state write shall leave the persisted session state unchanged. |
| NFR-6ShouldA published change shall carry a full snapshot rather than a delta, so a client never has to apply incremental updates, and the snapshot stays bounded by the per-session instance limit. | Should | Performance | A published change shall carry a full snapshot rather than a delta, so a client never has to apply incremental updates, and the snapshot stays bounded by the per-session instance limit. |
| NFR-7ShouldThe `applet` tool shall not be advertised or executable by terminal, headless, batch or codemode clients. | Should | Isolation | The applet tool shall not be advertised or executable by terminal, headless, batch or codemode clients. |
Constraints
- The applet schema is versioned as
jcode.applet/1; the version suffix changes only for breaking changes, and additive changes such as new node types keep the same version. - Placement is independent of tool calls; a tool call is one possible anchor for an inline placement.
- The host owns layout, theme, focus and scrolling; providers describe intent using spacing tokens rather than raw pixel values.
- The
applettool is registered only when the client advertises the desktop inline response renderer capability. - SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. state lives in
~/.jcode/agent_applets/, one file per session named after the session id with a.jsonsuffix; the session id may not be empty, contain a path separator, or start with a dot. - Instance ids are 1 to 64 characters drawn from
[A-Za-z0-9-_.]. - Agent-mounted instances use the applet id
jcode.agentand a session-scoped visibility scope. - The agent applet manifest declares the
open_url,clipboard,send_prompt,start_chatandhtmlcapabilities, and does not declareread_filesorremote_images.
Acceptance Criteria
Every FR and NFR shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
Acceptance criteria verify how a requirement is proven done, they do not restate it.
Write concrete, scenario-based criteria (happy path, edge cases and error states where applicable).
Write each criterion as a fenced gherkin block with a tag matching its requirement ID, so the criteria are parseable and later executable via BDD tooling (pytest-bdd, cucumber).
Multiple scenarios per requirement are allowed; tag each with the requirement ID.
-
FR-1MustThe system shall define a versioned applet wire schema (`jcode.applet/1`) whose view is a tree drawn from a closed set of native node types, so a provider describes UI without shipping code to the host.
gherkin @FR-1MustThe system shall define a versioned applet wire schema (`jcode.applet/1`) whose view is a tree drawn from a closed set of native node types, so a provider describes UI without shipping code to the host. Scenario: A provider describes UI as a validated native node tree Given an applet document whose view is a stack of text and button nodes When the document is deserialized and validated Then the view is accepted as a tree of known native node types -
FR-2MustThe system shall validate every document against the schema, the structural limits, and the capabilities the applet declares before the document is stored or rendered.
gherkin @FR-2MustThe system shall validate every document against the schema, the structural limits, and the capabilities the applet declares before the document is stored or rendered. Scenario: An invalid document is rejected before it is stored Given a mount request whose view references an image asset that was never declared When the host validates the document Then the mount fails with an unknown asset error And the session snapshot still holds the instances that were mounted before -
FR-3MustThe system shall expose an `applet` tool to the agent with `mount`, `update`, `patch`, `move`, `close` and `list` actions.
gherkin @FR-3MustThe system shall expose an `applet` tool to the agent with `mount`, `update`, `patch`, `move`, `close` and `list` actions. Scenario: The agent drives applets through one tool Given the applet tool is registered for a desktop-capable session When the agent calls the tool with action mount, patch, move, list and close in turn Then each action is accepted and reports the resulting instance and revision -
FR-4MustThe system shall mount an instance under a generated session-local identifier when the agent does not supply one.
gherkin @FR-4MustThe system shall mount an instance under a generated session-local identifier when the agent does not supply one. Scenario: A mount without an instance id gets a generated one Given the agent mounts an applet titled "Sales Chart!" without naming an instance When the host stores the instance Then the instance id is a slug of the title followed by four hex digits -
FR-5MustThe system shall persist mounted instances per session, one file per session under the jcode home directory, and remove the file when the last instance in the session is closed.
gherkin @FR-5MustThe system shall persist mounted instances per session, one file per session under the jcode home directory, and remove the file when the last instance in the session is closed. Scenario: Mounted instances survive a reload and the file disappears when empty Given a session with two mounted applets When the session snapshot is read from the applet state file and the last applet is closed Then the file for the session no longer exists -
FR-6MustThe system shall apply incremental updates as revision-checked patch operations restricted to the `/view`, `/state` and `/title` paths, and shall reject a patch as a whole when its result does not validate.
gherkin @FR-6MustThe system shall apply incremental updates as revision-checked patch operations restricted to the `/view`, `/state` and `/title` paths, and shall reject a patch as a whole when its result does not validate. Scenario: A patch updates the document and a stale or invalid patch is refused Given a mounted applet at revision 1 When a patch replaces the title at base revision 1 Then the title changes and the revision becomes 2 When the same patch is applied at base revision 1 again Then the patch is refused with a revision mismatch -
FR-7MustThe system shall move a mounted instance to a different placement and bump the instance's document revision.
gherkin @FR-7MustThe system shall move a mounted instance to a different placement and bump the instance's document revision. Scenario: Moving an instance changes its placement Given a mounted applet placed inline in the transcript When the agent moves it to the sidebar Then the instance placement becomes sidebar And the document revision increases by one -
FR-8MustThe system shall close an instance, remove it from the session snapshot, and report whether the instance existed.
gherkin @FR-8MustThe system shall close an instance, remove it from the session snapshot, and report whether the instance existed. Scenario: Closing removes the instance and reports whether it existed Given a mounted applet When the agent closes it Then the tool reports that the applet was closed And the session snapshot no longer contains the instance -
FR-9MustThe system shall stream the complete set of mounted instances for a session to connected clients as a full-snapshot event on every change.
gherkin @FR-9MustThe system shall stream the complete set of mounted instances for a session to connected clients as a full-snapshot event on every change. Scenario: Clients receive the whole snapshot on every change Given a connected client attached to a session When an applet is mounted, patched and then closed Then the client receives one applet state event per change And each event carries the complete set of instances for the session -
FR-10MustThe system shall route a user intent back to the agent as a compact action message carrying the action name, the action arguments, the instance's current state, and the key of the node that emitted it.
gherkin @FR-10MustThe system shall route a user intent back to the agent as a compact action message carrying the action name, the action arguments, the instance's current state, and the key of the node that emitted it. Scenario: A user intent reaches the agent as a compact action message Given a mounted applet with bound state When the user presses a control that emits a custom action Then the agent receives one message naming the instance, the action and the arguments And the message carries the instance's current state -
FR-11MustThe system shall let the agent block on an applet tool call until a user action arrives on that instance, with a bounded wait.
gherkin @FR-11MustThe system shall let the agent block on an applet tool call until a user action arrives on that instance, with a bounded wait. Scenario: A waiting mount returns the user action Given the agent mounts an applet with wait enabled When the user acts on the applet before the wait ends Then the tool call returns the action message And the agent is not woken separately -
FR-12MustThe system shall store host-supplied user state into an instance without changing the instance's document revision.
gherkin @FR-12MustThe system shall store host-supplied user state into an instance without changing the instance's document revision. Scenario: A user state write does not change the revision Given a mounted applet at revision 3 When the host stores new user state on the instance Then the state is updated And the document revision stays at 3 -
FR-13ShouldThe system shall support the standalone panel, sidebar, overlay, composer strip, background and inline placements, with inline anchored to a tool call, a message, or the end of the conversation.
gherkin @FR-13ShouldThe system shall support the standalone panel, sidebar, overlay, composer strip, background and inline placements, with inline anchored to a tool call, a message, or the end of the conversation. Scenario: Every documented placement is expressible Given the placement shorthands inline, end, panel, sidebar, overlay and composer When each is resolved for a session Then the resolved placements match the panel, sidebar, overlay, composer and inline forms And an inline placement defaults to anchoring at the calling tool call -
FR-14ShouldThe system shall render MCP-UI resources returned by an MCP tool as mounted applets anchored to the tool call that produced them.
gherkin @FR-14ShouldThe system shall render MCP-UI resources returned by an MCP tool as mounted applets anchored to the tool call that produced them. Scenario: An MCP UI resource becomes a mounted applet Given an MCP tool result carrying a ui:// resource with HTML content When the tool result is processed Then an applet is mounted inline at the tool call and the tool output says the UI was rendered -
FR-15MayThe system shall render sandboxed HTML inside an applet, gated by the `html` capability.
gherkin @FR-15MayThe system shall render sandboxed HTML inside an applet, gated by the `html` capability. Scenario: HTML rendering requires the html capability Given a document whose view contains an html node When the document is validated for an applet that does not declare the html capability Then validation fails with a missing capability error -
NFR-1MustNo provider code shall run in the host process. The host renders a declarative tree and executes only its own built-in host actions.
gherkin @NFR-1MustNo provider code shall run in the host process. The host renders a declarative tree and executes only its own built-in host actions. Scenario: The host runs no provider code Given an applet whose view contains only declarative nodes and host actions When the host renders and stores the document Then the host loads no provider binary and evaluates no provider script -
NFR-2MustThe host shall accept node types it does not know, render their fallback text, and round-trip them losslessly, so a provider built against a newer host still works on an older host.
gherkin @NFR-2MustThe host shall accept node types it does not know, render their fallback text, and round-trip them losslessly, so a provider built against a newer host still works on an older host. Scenario: An unknown node type degrades and round-trips Given a document containing a node type the host does not know, with fallback text When the document is deserialized, validated and re-serialized Then the node is kept as an unknown node with its fallback and its original fields -
NFR-3MustThe number of mounted instances per session shall be bounded at 64, and every document shall be bounded by structural limits on depth, node count, text size, asset size, asset count, table cells, HTML size and state size.
gherkin @NFR-3MustThe number of mounted instances per session shall be bounded at 64, and every document shall be bounded by structural limits on depth, node count, text size, asset size, asset count, table cells, HTML size and state size. Scenario: Documents and instance counts are bounded Given a session that already holds the maximum number of instances When the agent mounts one more instance Then the mount is refused with a message naming the maximum -
NFR-4MustHost actions and image sources shall be rejected unless the applet declares the matching capability, and `host.open_url` shall accept only `http`, `https` and `mailto` URLs.
gherkin @NFR-4MustHost actions and image sources shall be rejected unless the applet declares the matching capability, and `host.open_url` shall accept only `http`, `https` and `mailto` URLs. Scenario: Capabilities gate host actions and image sources Given a document with a host.open_url action When the document is validated for an applet without the open_url capability Then validation fails with a missing capability error -
NFR-5ShouldA failed mount, patch, move or state write shall leave the persisted session state unchanged.
gherkin @NFR-5ShouldA failed mount, patch, move or state write shall leave the persisted session state unchanged. Scenario: A failed write leaves the stored state untouched Given a mounted applet When a patch that would produce an invalid document is applied Then the patch is refused And the stored document is unchanged -
NFR-6ShouldA published change shall carry a full snapshot rather than a delta, so a client never has to apply incremental updates, and the snapshot stays bounded by the per-session instance limit.
gherkin @NFR-6ShouldA published change shall carry a full snapshot rather than a delta, so a client never has to apply incremental updates, and the snapshot stays bounded by the per-session instance limit. Scenario: Clients never apply deltas Given a session with one mounted applet When the applet is patched Then the event delivered to clients carries the full instance set And it carries the new revision of the patched instance -
NFR-7ShouldThe `applet` tool shall not be advertised or executable by terminal, headless, batch or codemode clients.
gherkin @NFR-7ShouldThe `applet` tool shall not be advertised or executable by terminal, headless, batch or codemode clients. Scenario: Headless clients cannot run applets Given a client that does not advertise the desktop inline response renderer capability When the tool list is built for that client Then the applet tool is absent from the list And calling it by name fails
Conflicts
None identified yet.
Open Questions
- Should adding node types bump the schema to
jcode.applet/2, or do additive node types keep version 1 forever, as the wire type documentation currently states? - The agent applet manifest grants the
htmlcapability to every agent-mounted applet by default; should sandboxed HTML require an explicit user approval instead? - A waiting
appletcall can hold a tool call open for up to one hour; should that ceiling be lowered now that the agent is woken by later action messages anyway?
Specification: Agent Applets
Overview
The applet feature is split across three crates.
crates/jcode-applet-types holds the versioned wire types, the document validator and the patch engine, with no dependency beyond serde and serde_json.
crates/jcode-base holds the per-session persistence and the MCP resource bridge.
crates/jcode-app-core holds the applet tool the agent calls and the server handlers that turn client actions into agent messages.
The harness API, the internal protocol and the Rust SDKSoftware Development Kit expose the same applet surface to external clients.
This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). (agent, MCP server, local process, native desktop code)
| no provider code runs inside the host process
| ProviderMessage: register / mount / patch / move / toast / busy / close
v
+---------------------------------------------------------------------+
| jcode-applet-types |
| Document Instance Placement Anchor Scope Lifetime |
| Node / NodeKind (closed set) PatchOp Action HostMessage |
| validate_document apply_patch NodeKind::Unknown -> fallback |
+---------------------------------------------------------------------+
| ^
| jcode-base::applets | jcode-app-core::tool::applet
v | (mount, update, patch, move, close, list)
+-------------------------------+ |
| ~/.jcode/agent_applets/ | |
| one file per session | |
| mount / patch / move / | |
| close / set_state / publish | |
+-------------------------------+ |
| |
| Bus::AppletsUpdated (full snapshot) |
v v
+---------------------------------------------------------------------+
| jcode-app-core::server |
| BusEvent::AppletsUpdated -> ServerEvent::AppletState |
| Request::AppletAction -> store state, publish, wake agent |
| Request::CloseApplet -> close, publish, no agent wake |
+---------------------------------------------------------------------+
| ServerEvent::AppletState | Request::AppletAction
v v
+---------------------------------------------------------------------+
| Client (Jcode Desktop) |
| renders the node tree, owns layout / theme / input / focus |
+---------------------------------------------------------------------+
| Request::AppletAction / Request::CloseApplet
v
jcode-protocol -> jcode-harness-api -> jcode-sdk / external clients
The persistence layer sits between the wire types and the server. Every change is written to disk first and then published as a full snapshot, so a client that misses an event still recovers the whole set on the next one.
Data Models
AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. document
The unit the host stores, persists and renders.
| Field | Type | Constraints | Description |
|---|---|---|---|
| revision | u64 | Monotonic, not null | The revision this document is at; a patch carries the revision it applies to. |
| title | String | not null | Human-readable title shown in the applet chrome. |
| view | Node | not null, must be a known or unknown node | Root of the view tree. |
| state | Value | Object, not null, size-bounded | Values bound by inputs, toggles, selects and tabs, keyed by bind. |
| assets | Vec\<AssetDecl> | Optional, count and size bounded | Binary assets referenced by id from image nodes. |
AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. instance
A mounted applet, as the host tracks it.
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | InstanceId | 1 to 64 chars of [A-Za-z0-9-_.], unique per session |
Host-unique identity of one mounted instance. |
| applet | AppletId | Forced to jcode.agent for agent-mounted instances |
The applet that owns the instance. |
| placement | Placement | not null | Where the instance appears. |
| scope | Scope | Defaults to global |
Visibility scope; agent-mounted instances use session. |
| lifetime | Lifetime | Defaults to session |
How long the host keeps the instance and its last document. |
| document | Document | not null | The rendered content. |
Placement
Where an instance appears. Placement is independent of tool calls; a tool call is one possible inline anchor.
| Variant | Fields | Meaning |
|---|---|---|
| panel | open: split, replace or background |
A first-class workspace panel that can be tiled, focused and closed. |
| sidebar | none | A compact section in the workspace sidebar. |
| overlay | corner: top_right, bottom_right, bottom_left, top_left |
A floating card over the workspace. |
| composer | session_id |
A strip directly above a session's composer. |
| inline | session_id, anchor |
Inside the conversation transcript, scrolled with the messages. |
| background | none | No visible UI; the instance can still post toasts and launch panels. |
Inline anchors are tool_call (with call_id), after_message (with message_id) and end.
Patch operation
An RFC 6902 style operation on the JSON form of a document.
| Field | Type | Constraints | Description |
|---|---|---|---|
| op | add, replace or remove |
not null | The operation kind. |
| path | String | Must be /view, /state or /title, or a path under one of them |
The target path. |
| value | Value | Required for add and replace |
The new value. |
Applying a patch copies the document, applies every operation, revalidates the result and increments the revision by one. A revision mismatch, a forbidden path, a missing path or an invalid result rejects the whole patch.
Host message
A host to provider message.
| Variant | Fields | Meaning |
|---|---|---|
| action | instance, revision, action, state, source_key |
A user intent from a node, with the instance's current local state. |
| launch | applet, launcher, instance |
A launcher fired; the provider should mount an instance. |
| resync | instance, revision, reason |
The host rejected a message; the provider should mount a full document. |
| tool_call | session_id, call_id, tool, input, output, error, done |
A claimed tool call started or finished. |
| visibility | instance, visible |
Visibility changed; providers may pause polling while hidden. |
| closed | instance |
The user or host closed the instance. |
| rejected | instance, reason |
A message failed validation and was not rendered. |
The provider to host direction uses the mirror type ProviderMessage with the variants register, mount, patch, move, toast, busy and close.
View node
The closed set of native components a provider may use.
Layout nodes are stack, grid, scroll, card, tabs, spacer and divider.
Content nodes are text, markdown, code, image, icon, key_value, table, progress, empty and error.
Control nodes are button, chip, toggle, input, select, list and list_item.
html is the sandboxed escape hatch and requires the html capability.
A node carries an optional key for stable identity across patches and an optional fallback shown by hosts that do not know the type.
API Contracts
There is no HTTP surface for applets. The contract is a tool contract plus a JSON message protocol, so the tables below describe the callable surfaces instead of REST endpoints.
applet tool
Registered only when the client advertises the desktop inline response renderer capability.
| Action | Required input | Optional input | Effect |
|---|---|---|---|
| mount | view |
instance, title, state, assets, placement, lifetime, wait |
Mounts a new instance, or replaces the instance with the same id. |
| update | instance |
title, view, state, assets, placement, lifetime, wait |
Replaces the document of an existing instance. |
| patch | instance, ops |
base_revision, wait |
Applies patch operations to the instance document. |
| move | instance, placement |
wait |
Moves the instance to a new placement. |
| close | instance |
none | Removes the instance from the session. |
| list | none | none | Lists the mounted instances with their id, revision, title and state. |
placement accepts the shorthands inline, end, panel, sidebar, overlay and composer, or a placement object.
inline defaults to anchoring at the calling tool call.
wait blocks the tool call until a user action arrives on the instance, with a default timeout of 600 seconds clamped to the range 1 to 3600 seconds.
It applies to every action except list and close, which return immediately.
Harness API requests
| Request | Fields | Effect |
|---|---|---|
applet_action |
session_id, instance, action, state, source_key |
The user pressed something; the server stores the state, publishes, then wakes the agent or resolves a waiting tool call. |
close_applet |
session_id, instance |
The user closed an instance; the agent is not woken. |
Harness API events
| Event | Fields | Effect |
|---|---|---|
applet_state |
session_id, snapshot |
The complete set of agent-mounted instances for a session. The client replaces its previous snapshot, including when the set is empty. |
The same event and request names exist in the internal protocol (jcode-protocol) and are surfaced by the Rust SDKSoftware Development Kit as applet_action, close_applet and the AppletState event.
Sequences
Mount an applet
sequenceDiagram
autonumber
participant A as Agent
participant T as applet tool
participant P as jcode-base::applets
participant V as validate_document
participant B as Event bus
participant C as Client
A->>T: action=mount, title, view
T->>P: mount(session_id, instance)
P->>V: validate(document, agent manifest, limits)
V-->>P: ok
P->>P: write ~/.jcode/agent_applets/sess_abc123.json
P-->>T: snapshot
T->>B: publish(AppletsUpdated)
B->>C: AppletState (full snapshot)
T-->>A: "AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. `chart-3f2a` revision 1"
Patch an applet
sequenceDiagram
autonumber
participant A as Agent
participant T as applet tool
participant P as jcode-base::applets
participant B as Event bus
participant C as Client
A->>T: action=patch, instance, ops, base_revision
T->>P: patch(session_id, id, base_revision, ops)
P->>P: apply_patch (revision check, path allowlist)
P->>P: validate the patched document
P->>P: write the state file
P-->>T: (snapshot, new revision)
T->>B: publish(AppletsUpdated)
B->>C: AppletState (full snapshot)
T-->>A: "AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. `chart-3f2a` revision 2"
A user acts on an applet
sequenceDiagram
autonumber
participant U as User
participant C as Client
participant S as Server
participant P as jcode-base::applets
participant B as Event bus
participant A as Agent
U->>C: presses a control
C->>S: Request::AppletAction (instance, action, state, source_key)
S->>P: set_state(session_id, instance, state)
P-->>S: (snapshot, instance)
S->>B: publish(AppletsUpdated)
B->>C: AppletState (full snapshot)
S->>A: deliver to a waiting applet tool call, or wake the agent
A-->>S: "[applet action] instance `chart-3f2a`: `select` args {...} state {...}"
Unmount an applet
sequenceDiagram
autonumber
participant A as Agent
participant T as applet tool
participant P as jcode-base::applets
participant B as Event bus
participant C as Client
A->>T: action=close, instance
T->>P: close(session_id, instance)
P->>P: remove the instance
P->>P: write the state file, or delete it when the session is empty
P-->>T: (snapshot, existed)
T->>B: publish(AppletsUpdated)
B->>C: AppletState (full snapshot, without the instance)
T-->>A: "Closed applet `chart-3f2a`."
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Wire types in their own crate | jcode-applet-types with only serde and serde_json as dependencies |
The schema is a published contract shared by the host, the protocol, the harness API and the SDKSoftware Development Kit, so it must not drag in the application stack. |
| Declarative tree instead of provider code | A closed set of node types, no provider binary in the host process | The host owns layout, theme and input, and a provider cannot compromise the app. |
| Unknown node types degrade | NodeKind::Unknown keeps the raw fields and the fallback text |
A provider built against a newer host still works on an older host, and relaying or persisting the node stays lossless. |
| Validation before storage and after every patch | validate_document runs on mount and on the patched result |
A bad patch never leaves a half-updated document on screen, and an invalid document never reaches the store. |
| Full-snapshot events | AppletState carries the whole instance set |
A client that misses an event recovers on the next one, and no client-side delta logic is needed. |
| Persist before publish | The state file is written, then the bus event is published | A client that reacts to the event always sees state that is already on disk. |
| Revision-checked patches | base_revision must match the current revision |
The provider detects that it is out of date and re-sends a full document. |
| State writes keep the revision | set_state does not bump the revision |
A patch that was computed against the state the user just produced still applies. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status.-scoped file per session | ~/.jcode/agent_applets/, one file per session named after the session id |
Sessions are independent, the file is easy to inspect, and an empty session leaves no file behind. |
| Instance ids are slugs plus four hex digits | generate_instance_id |
Ids stay readable in transcripts and messages while staying unique within a session. |
| MCP resources become applets | ui:// HTML, ui:// URI lists and native applet JSON are mapped to documents |
An MCP server ships UI without a custom client, and the resource is anchored to the tool call that produced it. |
| The tool is desktop-only | The registry registers it only when the desktop capability is on | Terminal, headless, batch and codemode clients never advertise or execute it. |
| Capability gating | Host actions and image sources require a declared capability | The user approves a capability set per applet, and validation enforces it. |
Risks and Unknowns
- The schema version policy is ambiguous. The wire types say the suffix changes only for breaking changes and that additive node types keep the same version, so a long-lived
jcode.applet/1will accumulate node types that older hosts render as fallback text. - The agent applet manifest grants the
htmlcapability by default, so every agent-mounted applet can render sandboxed HTML without a separate user approval. - A waiting
applettool call can hold a tool call open for up to an hour, and the wait is cancelled only by a timeout or a graceful shutdown signal. - The Desktop renderer is not in this repository, so the host's handling of
NodeKind::Unknownfallback text and of every placement is asserted by the wire contract and by the client protocol, not by an automated test in this repository. - The instance cap of 64 is a fixed constant, and a session that reaches it cannot mount anything new until the agent closes an instance.
- The
ui://bridge is heuristic. A URI list is read as its first non-comment line, and a resource with a non-ui://URI and a non-native mime type is silently ignored rather than reported.
Out of Scope
- The Desktop renderer that draws the node tree, including layout, theming, focus and scrolling.
- The provider side of the protocol, such as a plugin host that receives
ProviderMessageandHostMessage. - The capability approval user interface, which decides how a user grants a capability set to an applet.
- Rendering applets in the terminal client, which is excluded by the desktop-only tool registration.
- Non-image assets. The asset model currently carries only image mime types.
Test Plan: Agent Applets
Scope
Covers the applet wire types and their validation, the per-session persistence layer, the applet tool, the MCP resource bridge, and the harness API translation of the applet requests and events.
Out of scope: the Desktop renderer that draws the node tree, which lives outside this repository, and any provider-side implementation that consumes ProviderMessage and HostMessage.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Instance id generation in crates/jcode-app-core/src/tool/applet_tests.rs (ids_are_slugs_with_hex) |
Titles "Sales Chart!" and "!!" |
A slug of the title plus four hex digits, with applet- as the fallback slug for a title with no alphanumeric characters |
| TC-2 | Desktop capability gating in crates/jcode-app-core/src/tool/applet_tests.rs (applet_requires_desktop_capability) |
A Registry with desktop UI enabled and disabled |
The applet tool appears in the definitions only when enabled, is absent from the base tool map, and execution fails when disabled |
| TC-3 | Action message formatting in crates/jcode-app-core/src/tool/applet_tests.rs (action_message_is_compact) |
An action select with args {"id":2}, state {"q":"x"} |
The exact message [applet action] instance \chart-3f2a` ("Title"): `select` args {"id":2}\nstate: {"q":"x"}` |
| TC-4 | Documented node shapes validate in crates/jcode-app-core/src/tool/applet_tests.rs (documented_shapes_validate) |
A view using select, tabs, key_value, button, toggle, input, list_item, progress and text, built exactly as the tool description spells them | The description contains the documented field names, and the document deserializes and validates against the agent manifest |
| TC-5 | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. persistence lifecycle in crates/jcode-base/src/applets.rs (tests::lifecycle) |
Mount, remount, patch, state write, move and close on a session | Remount keeps the position and bumps the revision, a patch bumps it again, a stale base revision fails, a state write keeps the revision, a move bumps it, an invalid id and an invalid state fail, and close removes the instance |
| TC-6 | MCP resource to document mapping in crates/jcode-base/src/applets.rs (mcp_tests::mcp_resources_map_to_documents) |
A ui:// resource with text/html, a ui:// resource with text/uri-list, a resource with the native applet mime type, and a non-matching resource |
HTML becomes an html view, a URI list becomes a card with a host.open_url action, the native resource becomes its document, and the non-matching resource returns nothing |
| TC-7 | Agent manifest and snapshot in crates/jcode-applet-types/src/agent.rs (tests::manifest_is_valid_and_allows_html, tests::snapshot_round_trips_and_defaults_empty) |
The agent manifest and a snapshot with one instance | The manifest validates and allows html but not read_files; an empty snapshot defaults to no instances; a populated snapshot round-trips unchanged and its document validates |
| TC-8 | Agent tool surface follows the desktop capability in crates/jcode-app-core/src/agent_tests.rs (user_response_capability_updates_locked_tool_surface) |
An agent with the desktop response capability toggled on and off | The applet tool is present only while the capability is on, and an unchanged capability keeps the locked tool cache |
| TC-9 | Tool description and schema budgets in crates/jcode-app-core/src/tool/tests.rs (tool_descriptions_stay_under_token_cap, tool_parameter_descriptions_stay_under_token_cap, only_the_known_open_world_tools_are_ineligible_for_openai_strict_mode) |
The registry tool definitions | The applet description and its placement parameter description stay exempt and within the caps, and the applet schema stays on the list of tools that cannot use strict mode because its view tree is open-world |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-10 | Wire round trip of a rich document in crates/jcode-applet-types/tests/applet_types.rs (round_trips_a_rich_document_with_images_and_placements) |
A mount message with an overlay placement, a persistent lifetime, a declared asset and a stack of input, grid, image and list nodes | The message survives a serialize and deserialize round trip, the placement is an overlay, and the document validates |
| TC-11 | Placement independence from tool calls in crates/jcode-applet-types/tests/applet_types.rs (placements_are_independent_of_tool_calls) |
The panel, sidebar, composer, background and three inline placements | Every placement parses and re-serializes to the same kind, and inline placements carry the tool call, message and end anchors |
| TC-12 | Unknown node degradation in crates/jcode-applet-types/tests/applet_types.rs (unknown_nodes_degrade_to_fallback_and_survive_round_trip) |
A stack whose child is a map_view node with fallback text and an extra field |
The child becomes an unknown node keeping its type name, its fallback and its raw fields, the document still validates, and re-serialization restores the original object |
| TC-13 | Malformed known nodes fail in crates/jcode-applet-types/tests/applet_types.rs (malformed_known_nodes_are_errors) |
A button node with no on_press |
Deserialization fails with an invalid \button` node` error rather than degrading to an unknown node |
| TC-14 | Capability gating of host actions and image sources in crates/jcode-applet-types/tests/applet_types.rs (capabilities_gate_host_actions_and_image_sources) |
Documents using host.open_url, a javascript: URL, a remote image over https and http, a relative image path, an html node and an unknown host action |
Each is refused with the matching error, and the same documents pass once the matching capability is declared |
| TC-15 | Limits and references in crates/jcode-applet-types/tests/applet_types.rs (enforces_limits_and_references) |
An unknown asset reference, a duplicated node key, a tree deeper than the limit, an oversized inline image, a ragged table and an unsupported asset mime type | Each is refused with the matching validation error |
| TC-16 | Patch revisioning, atomicity and path restriction in crates/jcode-applet-types/tests/applet_types.rs (patches_are_revisioned_atomic_and_path_restricted) |
A patch that replaces a nested view field, appends a child and writes a state key, plus a stale base revision, a forbidden path, a missing path and a patch that breaks a known node | The valid patch produces revision 2 with the new view and state, and each invalid patch is refused without changing the document |
| TC-17 | Manifest schema, launchers and tool card claims in crates/jcode-applet-types/tests/applet_types.rs (manifest_schema_and_tool_card_claims) |
A manifest with sidebar, shortcut and startup launchers and a tool card claim, and a copy with schema jcode.applet/2 |
The manifest validates, singleton defaults hold, the tool card matches on tool and action but not on an unlisted action or a missing action, and a future major schema is rejected |
| TC-18 | Harness API translation in crates/jcode-harness-api-server/src/translate_tests.rs (applet_requests_and_state_translate) |
An applet_action request and a close_applet request, and an applet_state event |
The requests forward to the daemon with their instance, action, state and source key, and the event reaches clients as a full snapshot, including an empty one |
| TC-19 | AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. state during attachment hydration in crates/jcode-harness-api-server/src/translate_tests.rs (attachment_recovery_preserves_directive_in_both_history_state_orders, attachment_recovery_suppresses_empty_active_completed_and_blank_directives_once) |
A bridge that attaches a client to a session | The bridge emits an AppletState frame during attachment, next to the side panel state, in both history and state orderings |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-20 | The full agent-facing applet loop in crates/jcode-app-core/src/tool/applet_tests.rs (mount_patch_wait_and_close) |
Mount an applet in a session with an isolated JCODE_HOME, read the stored snapshot, attempt an update with an invalid view, patch the title, run an update with wait and deliver an action to the waiting call, then close the instance |
The mount stores an inline placement anchored at the calling tool call, the invalid update is rejected without changing the stored instance, the patch changes the title, the waiting call returns the delivered action, and the close empties the session |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-21 | Patch applied at a stale base revision | Refused with a revision mismatch, and the stored document is unchanged |
| TC-22 | Patch targeting a path outside /view, /state and /title |
Refused with a forbidden path error |
| TC-23 | Patch targeting a path that does not exist | Refused with a path not found error |
| TC-24 | Patch whose result is not a valid document | Refused as a whole with an invalid document error, so no half-updated document survives |
| TC-25 | Image node referencing an asset that was never declared | Validation fails with an unknown asset error |
| TC-26 | Two nodes sharing the same key |
Validation fails with a duplicate key error |
| TC-27 | View tree deeper than the depth limit | Validation fails with a too deep error |
| TC-28 | Inline base64 image above the inline image size limit | Validation fails with an inline image too large error |
| TC-29 | Table whose row width differs from the column count | Validation fails with a ragged table error |
| TC-30 | Asset declared with a mime type that is not a supported image type | Validation fails with an unsupported mime error |
| TC-31 | Known node type with a missing required field | Deserialization fails instead of degrading to an unknown node |
| TC-32 | Host action with an unknown host. prefix |
Validation fails with an invalid value error |
| TC-33 | host.open_url with a javascript: URL |
Validation fails, because only http, https and mailto are accepted |
| TC-34 | Remote image over plain http | Validation fails, because remote images must use https |
| TC-35 | Image path that is not absolute | Validation fails, because image paths must be absolute |
| TC-36 | Instance id containing characters outside [A-Za-z0-9-_.], or longer than 64 characters |
The mount is refused with an id validation error |
| TC-37 | User state written as a non-object | The state write is refused and the stored document is unchanged |
| TC-38 | applet tool called on a client that does not advertise the desktop capability |
The tool is not advertised and execution fails |
| TC-39 | MCP resource whose uri is not a ui:// uri and whose mime type is not the native applet type |
The resource is not mounted and is passed through as text |
| TC-40 | More than 64 instances in one session | The mount is refused with a message naming the maximum |
Test Infrastructure
- Every test that touches the store sets
JCODE_HOMEto a temporary directory and holdscrate::storage::lock_test_env()so parallel tests do not share state. crates/jcode-app-core/src/tool/applet_tests.rsuses aHomeguard that restores the previousJCODE_HOMEon drop.- The
applettool is exercised directly throughAppletTool::new()and through an emptyRegistryfor the capability checks. - A waiting tool call is released by calling
deliver_to_waiterfrom the test, which exercises the real oneshot path rather than a mock. - The harness API tests use the bridge translation layer directly, with no socket and no running server.
- No provider, network access or Desktop renderer is required by any test in this plan.
- Useful commands:
cargo test -p jcode-applet-types,cargo test -p jcode-base applets,cargo test -p jcode-app-core applet,cargo test -p jcode-harness-api-server translate.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall define a versioned applet wire schema (`jcode.applet/1`) whose view is a tree drawn from a closed set of native node types, so a provider describes UI without shipping code to the host. | TC-10, TC-12, TC-4 |
| FR-2MustThe system shall validate every document against the schema, the structural limits, and the capabilities the applet declares before the document is stored or rendered. | TC-14, TC-15, TC-5, TC-4 |
| FR-3MustThe system shall expose an `applet` tool to the agent with `mount`, `update`, `patch`, `move`, `close` and `list` actions. | TC-2, TC-20 |
| FR-4MustThe system shall mount an instance under a generated session-local identifier when the agent does not supply one. | TC-1, TC-20 |
| FR-5MustThe system shall persist mounted instances per session, one file per session under the jcode home directory, and remove the file when the last instance in the session is closed. | TC-5, TC-20 |
| FR-6MustThe system shall apply incremental updates as revision-checked patch operations restricted to the `/view`, `/state` and `/title` paths, and shall reject a patch as a whole when its result does not validate. | TC-16, TC-20, TC-21, TC-22, TC-23, TC-24 |
| FR-7MustThe system shall move a mounted instance to a different placement and bump the instance's document revision. | TC-5, TC-11 |
| FR-8MustThe system shall close an instance, remove it from the session snapshot, and report whether the instance existed. | TC-5, TC-20 |
| FR-9MustThe system shall stream the complete set of mounted instances for a session to connected clients as a full-snapshot event on every change. | TC-18, TC-19, TC-20 |
| FR-10MustThe system shall route a user intent back to the agent as a compact action message carrying the action name, the action arguments, the instance's current state, and the key of the node that emitted it. | TC-3, TC-18, TC-20 |
| FR-11MustThe system shall let the agent block on an applet tool call until a user action arrives on that instance, with a bounded wait. | TC-20 |
| FR-12MustThe system shall store host-supplied user state into an instance without changing the instance's document revision. | TC-5, TC-18, TC-37 |
| FR-13ShouldThe system shall support the standalone panel, sidebar, overlay, composer strip, background and inline placements, with inline anchored to a tool call, a message, or the end of the conversation. | TC-11, TC-5, TC-20 |
| FR-14ShouldThe system shall render MCP-UI resources returned by an MCP tool as mounted applets anchored to the tool call that produced them. | TC-6, TC-39 |
| FR-15MayThe system shall render sandboxed HTML inside an applet, gated by the `html` capability. | TC-14, TC-6 |
| NFR-1MustNo provider code shall run in the host process. The host renders a declarative tree and executes only its own built-in host actions. | TC-10, TC-4 |
| NFR-2MustThe host shall accept node types it does not know, render their fallback text, and round-trip them losslessly, so a provider built against a newer host still works on an older host. | TC-12, TC-13 |
| NFR-3MustThe number of mounted instances per session shall be bounded at 64, and every document shall be bounded by structural limits on depth, node count, text size, asset size, asset count, table cells, HTML size and state size. | TC-15, TC-27, TC-28, TC-29, TC-30 |
| NFR-4MustHost actions and image sources shall be rejected unless the applet declares the matching capability, and `host.open_url` shall accept only `http`, `https` and `mailto` URLs. | TC-14, TC-32, TC-33, TC-34, TC-35 |
| NFR-5ShouldA failed mount, patch, move or state write shall leave the persisted session state unchanged. | TC-5, TC-16, TC-24, TC-37 |
| NFR-6ShouldA published change shall carry a full snapshot rather than a delta, so a client never has to apply incremental updates, and the snapshot stays bounded by the per-session instance limit. | TC-18, TC-19 |
| NFR-7ShouldThe `applet` tool shall not be advertised or executable by terminal, headless, batch or codemode clients. | TC-2, TC-8, TC-38 |
Known gaps
- The 64-instance cap has no dedicated automated test. TC-40 records the expected behavior, but no test mounts 65 instances to prove it.
- No test covers the Desktop renderer. The fallback rendering of an unknown node, the placement geometry, and the host action execution are asserted by the wire contract and the client protocol, not by a test in this repository.
- The MCP mount path (
mount_mcp_resource) is covered for document mapping, but the anchored placement, the generated instance id and the rendered-UI tool output are not asserted by a test. - The
waittimeout and the graceful shutdown interruption are not covered; only the successful delivery path is tested.
requirements
- Should adding node types bump the schema to
jcode.applet/2, or do additive node types keep version 1 forever, as the wire type documentation currently states? - The agent applet manifest grants the
htmlcapability to every agent-mounted applet by default; should sandboxed HTML require an explicit user approval instead? - A waiting
appletcall can hold a tool call open for up to one hour; should that ceiling be lowered now that the agent is woken by later action messages anyway?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. HibernationEvicting an idle session from memory, with transparent wake on the next interaction.
Overview
An open terminal is not evidence of active work, so a long-idle session keeps memory resident that nothing will read. SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. hibernation frees that memory without closing the terminal, without losing the input draft, and without interrupting a tool, an agent turn, or a scheduled wake. The daemon reclaims lazy reproducible caches for idle sessions, and the terminal client reclaims its derived render caches and its retained heap. The canonical transcript stays live on both sides, so waking is transparent: the next interaction restores the session. Three hibernation depths are offered, from dropping rebuildable caches to exiting the client process entirely. This feature documents already-implemented functionality that was reverse-engineered from the existing codebase during an SDLC sync.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Terminal user | Memory that is freed while the session is idle, without a visible loss of the session |
| Terminal user | A wake that is invisible, so the first typed character is not swallowed |
| Operator | A daemon that does not hold provider caches for sessions nobody is using |
| Operator | Measured memory release rather than an estimated one |
| Maintainer | A boundary that keeps authoritative state resident and only discards derived state |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall release reloadable memory for a session that has had no work and no interaction for the configured idle period, and shall treat an idle period of `0` as hibernation disabled. | Must | The system shall release reloadable memory for a session that has had no work and no interaction for the configured idle period, and shall treat an idle period of 0 as hibernation disabled. |
| FR-2MustThe system shall read the idle period and the hibernation depth from the `[session]` configuration table, using the key `hibernation_idle_secs` for the period and `hibernation_mode` for the depth. | Must | The system shall read the idle period and the hibernation depth from the [session] configuration table, using the key hibernation_idle_secs for the period and hibernation_mode for the depth. |
| FR-3MustThe daemon shall sweep idle sessions on a 10 second interval and shall reclaim only lazy reproducible caches, namely the provider message cache and the reconstructible tool output indexes. | Must | The daemon shall sweep idle sessions on a 10 second interval and shall reclaim only lazy reproducible caches, namely the provider message cache and the reconstructible tool output indexes. |
| FR-4MustThe daemon shall refuse to hibernate a session that has an active turn, pending input, a queued alert or soft interrupt, an in-flight compaction, an in-flight tool, or a migration lease. | Must | The daemon shall refuse to hibernate a session that has an active turn, pending input, a queued alert or soft interrupt, an in-flight compaction, an in-flight tool, or a migration lease. |
| FR-5MustThe daemon shall reset the idle window of a session it declines to hibernate because work is pending, and shall re-arm the idle window when a turn starts and finishes entirely between two sweeps. | Must | The daemon shall reset the idle window of a session it declines to hibernate because work is pending, and shall re-arm the idle window when a turn starts and finishes entirely between two sweeps. |
| FR-6MustThe daemon shall keep the canonical transcript live across hibernation, retaining the original messages, the frozen tool definitions, the captured instructions, the rewind undo snapshot, and the provider session handle. | Must | The daemon shall keep the canonical transcript live across hibernation, retaining the original messages, the frozen tool definitions, the captured instructions, the rewind undo snapshot, and the provider session handle. |
| FR-7MustThe daemon shall purge retained heap once per sweep, after releasing every session lock, and shall record the released session ids, the released provider cache bytes, the released tool index entries, and the before and after resident memory. | Must | The daemon shall purge retained heap once per sweep, after releasing every session lock, and shall record the released session ids, the released provider cache bytes, the released tool index entries, and the before and after resident memory. |
| FR-8MustThe terminal client shall release its derived render caches, namely the prepared transcript and body frames, the rendered message lines, the syntax highlighting cache, the copy viewport snapshot, the derived side panel, diff and image state, the incremental markdown renderer, and the local provider message cache. | Must | The terminal client shall release its derived render caches, namely the prepared transcript and body frames, the rendered message lines, the syntax highlighting cache, the copy viewport snapshot, the derived side panel, diff and image state, the incremental markdown renderer, and the local provider message cache. |
| FR-9MustThe terminal client shall retain the authoritative source data across hibernation, keeping the input draft, the cursor position, the scroll offset, the scroll lock state, the attachments, the pasted contents, and the local-only display messages. | Must | The terminal client shall retain the authoritative source data across hibernation, keeping the input draft, the cursor position, the scroll offset, the scroll lock state, the attachments, the pasted contents, and the local-only display messages. |
| FR-10MustThe terminal client shall keep a bounded copy of the last completed terminal frame, and shall refuse to freeze a frame that is missing or that exceeds the cell or symbol bounds. | Must | The terminal client shall keep a bounded copy of the last completed terminal frame, and shall refuse to freeze a frame that is missing or that exceeds the cell or symbol bounds. |
| FR-11MustThe terminal client shall measure its own memory before and after the release and shall report the measured change in the hibernation notice, showing an increase as an increase and an unchanged reading as unchanged. | Must | The terminal client shall measure its own memory before and after the release and shall report the measured change in the hibernation notice, showing an increase as an increase and an unchanged reading as unchanged. |
| FR-12MustThe next interaction shall wake the session transparently, processing the waking event normally including its first character, and leaving the draft, the cursor, the scroll position and the session state untouched by the wake. | Must | The next interaction shall wake the session transparently, processing the waking event normally including its first character, and leaving the draft, the cursor, the scroll position and the session state untouched by the wake. |
| FR-13MustThe terminal client shall re-check every queued and active work guard at the moment of eviction, and shall not evict anything when work has arrived since the idle timer was scheduled. | Must | The terminal client shall re-check every queued and active work guard at the moment of eviction, and shall not evict anything when work has arrived since the idle timer was scheduled. |
| FR-14MustThe terminal client shall not wake on presence traffic, on acknowledgments, or on read-only debug queries, and shall wake on any event that may change the conversation content or start active work. | Must | The terminal client shall not wake on presence traffic, on acknowledgments, or on read-only debug queries, and shall wake on any event that may change the conversation content or start active work. |
| FR-15MustThe terminal client shall trim its retained heap with a per-client growth budget of 16 MiB, an idle trim after 60 seconds of quiet, and a re-trim cadence of 300 seconds while the client stays idle. | Must | The terminal client shall trim its retained heap with a per-client growth budget of 16 MiB, an idle trim after 60 seconds of quiet, and a re-trim cadence of 300 seconds while the client stays idle. |
| FR-16ShouldThe system shall offer three hibernation depths selected by `hibernation_mode`, namely `caches` for rebuildable render caches only, `transcript` for the in-memory transcript as well, and `exit` for the client process, with `caches` as the default. | Should | The system shall offer three hibernation depths selected by hibernation_mode, namely caches for rebuildable render caches only, transcript for the in-memory transcript as well, and exit for the client process, with caches as the default. |
| FR-17ShouldIn `transcript` mode the terminal client shall drop the in-memory transcript, clear the remote side pane images, and mark the history as needing a reload so that it is refetched from the server on wake. | Should | In transcript mode the terminal client shall drop the in-memory transcript, clear the remote side pane images, and mark the history as needing a reload so that it is refetched from the server on wake. |
| FR-18ShouldIn `exit` mode an idle remote client shall re-exec the process into a tiny waiter that resumes the session on the next key press. | Should | In exit mode an idle remote client shall re-exec the process into a tiny waiter that resumes the session on the next key press. |
| FR-19ShouldThe system shall expose a read-only debug query that returns the hibernation state, the scope, the measured memory readings, the hibernation and wake counts and the last wake reason, and a debug command that requests an immediate hibernation. | Should | The system shall expose a read-only debug query that returns the hibernation state, the scope, the measured memory readings, the hibernation and wake counts and the last wake reason, and a debug command that requests an immediate hibernation. |
| FR-20MayThe `JCODE_HIBERNATION_IDLE_SECS` and `JCODE_HIBERNATION_MODE` environment variables shall override the corresponding file configuration values, and an invalid override shall leave the file value in place. | May | The JCODE_HIBERNATION_IDLE_SECS and JCODE_HIBERNATION_MODE environment variables shall override the corresponding file configuration values, and an invalid override shall leave the file value in place. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustThe released memory shall be measured, not estimated. A flat or unavailable reading shall never be displayed as a positive saving. | Must | Resource | The released memory shall be measured, not estimated. A flat or unavailable reading shall never be displayed as a positive saving. |
| NFR-2MustThe wake shall be transparent. Rebuilding a released cache shall not invoke resume hooks, shall not cancel work, and shall not append a new environment snapshot. | Must | Availability | The wake shall be transparent. Rebuilding a released cache shall not invoke resume hooks, shall not cancel work, and shall not append a new environment snapshot. |
| NFR-3MustHibernationEvicting an idle session from memory, with transparent wake on the next interaction. shall not write the session file, and no disk-backed authoritative state shall be dropped on the strength of a queued save or of a save skipped because of a migration lease. | Must | Reliability | HibernationEvicting an idle session from memory, with transparent wake on the next interaction. shall not write the session file, and no disk-backed authoritative state shall be dropped on the strength of a queued save or of a save skipped because of a migration lease. |
| NFR-4MustThe idle detection cost shall be bounded. The daemon shall sweep on a fixed 10 second interval, and the client shall poll on its existing tick, so no extra thread or timer is created per session. | Must | Performance | The idle detection cost shall be bounded. The daemon shall sweep on a fixed 10 second interval, and the client shall poll on its existing tick, so no extra thread or timer is created per session. |
| NFR-5MustThe frozen terminal frame shall be bounded to 128 thousand cells and 8 MiB of symbol bytes, and the per-client retained heap growth budget shall be capped at 16 MiB even when the global threshold is larger. | Must | Resource | The frozen terminal frame shall be bounded to 128 thousand cells and 8 MiB of symbol bytes, and the per-client retained heap growth budget shall be capped at 16 MiB even when the global threshold is larger. |
| NFR-6MustHibernationEvicting an idle session from memory, with transparent wake on the next interaction. shall not discard or cancel active work, pending input, or a scheduled wake. | Must | Availability | HibernationEvicting an idle session from memory, with transparent wake on the next interaction. shall not discard or cancel active work, pending input, or a scheduled wake. |
| NFR-7ShouldThe session shall survive hibernation with its identity, model settings, draft, transcript and scroll state intact. | Should | Availability | The session shall survive hibernation with its identity, model settings, draft, transcript and scroll state intact. |
| NFR-8ShouldRepeated idle ticks shall not repeatedly rebuild and discard the same caches. | Should | Performance | Repeated idle ticks shall not repeatedly rebuild and discard the same caches. |
| NFR-9ShouldA configuration file without a `[session]` table shall inherit the default idle period of 30 minutes and the default mode of `caches`, and the settings shall round-trip through the configuration file. | Should | Compatibility | A configuration file without a [session] table shall inherit the default idle period of 30 minutes and the default mode of caches, and the settings shall round-trip through the configuration file. |
| NFR-10ShouldThe exit-mode waiter shall hold only a few hundred KiB of private memory while it waits, and shall resume the session in about one second. | Should | Resource | The exit-mode waiter shall hold only a few hundred KiB of private memory while it waits, and shall resume the session in about one second. |
| NFR-11ShouldThe daemon shall record the hibernation outcome in its log, and the client shall record the wake reason and the measured change, so an operator can tell an idle release from a failed one. | Should | Observability | The daemon shall record the hibernation outcome in its log, and the client shall record the wake reason and the measured change, so an operator can tell an idle release from a failed one. |
Constraints
- The idle period and the mode are read from the
[session]table of the jcode configuration file. - The daemon sweep reclaims derived caches only. The canonical transcript, the frozen prompts and tools, the rewind undo state, the provider handle and the hook state stay resident.
- Reloading a session from disk is not a wake operation, and is not used as one.
- The client keeps a bounded copy of the last frame instead of repainting the transcript into new caches on every idle tick.
- The daemon measures its own process separately from the client, and the client measurement is not attributed to the daemon or to other sessions.
- HibernationEvicting an idle session from memory, with transparent wake on the next interaction. is not process suspension, and it does not promise a near-zero-memory session.
- The exit mode applies to a remote client, because the daemon owns the session that the waiter resumes.
Acceptance Criteria
Every FR and NFR shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
Acceptance criteria verify how a requirement is proven done, they do not restate it.
Write concrete, scenario-based criteria (happy path, edge cases and error states where applicable).
Write each criterion as a fenced gherkin block with a tag matching its requirement ID, so the criteria are parseable and later executable via BDD tooling (pytest-bdd, cucumber).
Multiple scenarios per requirement are allowed; tag each with the requirement ID.
-
FR-1MustThe system shall release reloadable memory for a session that has had no work and no interaction for the configured idle period, and shall treat an idle period of `0` as hibernation disabled.
gherkin @FR-1MustThe system shall release reloadable memory for a session that has had no work and no interaction for the configured idle period, and shall treat an idle period of `0` as hibernation disabled. Scenario: An idle session releases its reloadable memory Given a session whose configured idle period has elapsed without work or interaction When the idle sweep runs Then the session releases its reloadable memory -
FR-2MustThe system shall read the idle period and the hibernation depth from the `[session]` configuration table, using the key `hibernation_idle_secs` for the period and `hibernation_mode` for the depth.
gherkin @FR-2MustThe system shall read the idle period and the hibernation depth from the `[session]` configuration table, using the key `hibernation_idle_secs` for the period and `hibernation_mode` for the depth. Scenario: The idle period and the mode come from the session configuration table Given a configuration file with "[session]" holding an idle period and a mode When the daemon and the client read their idle policy Then both read the same idle period and the same mode from the session table -
FR-3MustThe daemon shall sweep idle sessions on a 10 second interval and shall reclaim only lazy reproducible caches, namely the provider message cache and the reconstructible tool output indexes.
gherkin @FR-3MustThe daemon shall sweep idle sessions on a 10 second interval and shall reclaim only lazy reproducible caches, namely the provider message cache and the reconstructible tool output indexes. Scenario: The daemon sweep reclaims only reproducible caches Given an idle session with a populated provider message cache and tool output indexes When the daemon sweep runs Then the provider message cache and the tool output indexes are released And the original messages are still resident -
FR-4MustThe daemon shall refuse to hibernate a session that has an active turn, pending input, a queued alert or soft interrupt, an in-flight compaction, an in-flight tool, or a migration lease.
gherkin @FR-4MustThe daemon shall refuse to hibernate a session that has an active turn, pending input, a queued alert or soft interrupt, an in-flight compaction, an in-flight tool, or a migration lease. Scenario: A session with pending work is not hibernated Given an idle session with a queued alert, an in-flight compaction or an in-flight tool When the daemon sweep runs Then the session keeps its provider message cache And the sweep reports that no release happened for that session -
FR-5MustThe daemon shall reset the idle window of a session it declines to hibernate because work is pending, and shall re-arm the idle window when a turn starts and finishes entirely between two sweeps.
gherkin @FR-5MustThe daemon shall reset the idle window of a session it declines to hibernate because work is pending, and shall re-arm the idle window when a turn starts and finishes entirely between two sweeps. Scenario: The idle window is reset when work is pending Given a session that was declined for hibernation because work was pending When the work settles and the sweep runs again before the original idle period elapses Then the session is not hibernated yetgherkin @FR-5MustThe daemon shall reset the idle window of a session it declines to hibernate because work is pending, and shall re-arm the idle window when a turn starts and finishes entirely between two sweeps. Scenario: A turn that starts and finishes between two sweeps is detected Given a session whose turn started and finished between two sweeps When the next sweep runs Then the idle window is re-armed from the moment the turn finished -
FR-6MustThe daemon shall keep the canonical transcript live across hibernation, retaining the original messages, the frozen tool definitions, the captured instructions, the rewind undo snapshot, and the provider session handle.
gherkin @FR-6MustThe daemon shall keep the canonical transcript live across hibernation, retaining the original messages, the frozen tool definitions, the captured instructions, the rewind undo snapshot, and the provider session handle. Scenario: The canonical transcript survives hibernation Given an idle session with frozen tool definitions, captured instructions, a rewind undo snapshot and a provider session handle When the daemon hibernates the session Then the messages, the frozen tools, the captured instructions, the undo snapshot and the provider handle are unchanged -
FR-7MustThe daemon shall purge retained heap once per sweep, after releasing every session lock, and shall record the released session ids, the released provider cache bytes, the released tool index entries, and the before and after resident memory.
gherkin @FR-7MustThe daemon shall purge retained heap once per sweep, after releasing every session lock, and shall record the released session ids, the released provider cache bytes, the released tool index entries, and the before and after resident memory. Scenario: One sweep purges retained heap once and records the outcome Given two idle sessions that are both released in the same sweep When the sweep completes Then the retained heap purge runs once after the session locks are released And the log records both session ids, the released cache bytes, the released tool index entries and the before and after resident memory -
FR-8MustThe terminal client shall release its derived render caches, namely the prepared transcript and body frames, the rendered message lines, the syntax highlighting cache, the copy viewport snapshot, the derived side panel, diff and image state, the incremental markdown renderer, and the local provider message cache.
gherkin @FR-8MustThe terminal client shall release its derived render caches, namely the prepared transcript and body frames, the rendered message lines, the syntax highlighting cache, the copy viewport snapshot, the derived side panel, diff and image state, the incremental markdown renderer, and the local provider message cache. Scenario: The client releases its derived render caches Given an idle terminal client with prepared frames, rendered message lines and a populated local provider message cache When the client hibernates Then the prepared frames, the rendered message lines, the highlighting cache, the copy viewport, the derived side panel, diff and image state, the incremental markdown renderer and the local provider message cache are released -
FR-9MustThe terminal client shall retain the authoritative source data across hibernation, keeping the input draft, the cursor position, the scroll offset, the scroll lock state, the attachments, the pasted contents, and the local-only display messages.
gherkin @FR-9MustThe terminal client shall retain the authoritative source data across hibernation, keeping the input draft, the cursor position, the scroll offset, the scroll lock state, the attachments, the pasted contents, and the local-only display messages. Scenario: The draft, the cursor and the scroll state survive hibernation Given an idle terminal client with a draft, a cursor position, a scroll offset, an attachment and a pasted content When the client hibernates Then the draft, the cursor, the scroll offset, the attachment and the pasted content are unchanged -
FR-10MustThe terminal client shall keep a bounded copy of the last completed terminal frame, and shall refuse to freeze a frame that is missing or that exceeds the cell or symbol bounds.
gherkin @FR-10MustThe terminal client shall keep a bounded copy of the last completed terminal frame, and shall refuse to freeze a frame that is missing or that exceeds the cell or symbol bounds. Scenario: A frame that is too large to freeze is refused Given an idle terminal client whose last frame exceeds the cell or the symbol bound When the client hibernates Then no frame is frozen And the client does not retry the oversized frame on every idle tick -
FR-11MustThe terminal client shall measure its own memory before and after the release and shall report the measured change in the hibernation notice, showing an increase as an increase and an unchanged reading as unchanged.
gherkin @FR-11MustThe terminal client shall measure its own memory before and after the release and shall report the measured change in the hibernation notice, showing an increase as an increase and an unchanged reading as unchanged. Scenario: The notice reports the measured change Given an idle terminal client that measured a lower private memory after the release When the hibernation notice is rendered Then the notice shows the measured decrease and the resulting private memory -
FR-12MustThe next interaction shall wake the session transparently, processing the waking event normally including its first character, and leaving the draft, the cursor, the scroll position and the session state untouched by the wake.
gherkin @FR-12MustThe next interaction shall wake the session transparently, processing the waking event normally including its first character, and leaving the draft, the cursor, the scroll position and the session state untouched by the wake. Scenario: The first typed character wakes the session and is not swallowed Given a hibernated terminal client with a draft and a cursor position When the user types one character Then the client is awake And the character is appended to the draft at the original cursor position And the scroll position is unchanged -
FR-13MustThe terminal client shall re-check every queued and active work guard at the moment of eviction, and shall not evict anything when work has arrived since the idle timer was scheduled.
gherkin @FR-13MustThe terminal client shall re-check every queued and active work guard at the moment of eviction, and shall not evict anything when work has arrived since the idle timer was scheduled. Scenario: Work that arrives after the timer prevents the eviction Given an idle terminal client whose idle timer already elapsed When work is queued before the paint happens Then nothing is evicted And the client stays awake -
FR-14MustThe terminal client shall not wake on presence traffic, on acknowledgments, or on read-only debug queries, and shall wake on any event that may change the conversation content or start active work.
gherkin @FR-14MustThe terminal client shall not wake on presence traffic, on acknowledgments, or on read-only debug queries, and shall wake on any event that may change the conversation content or start active work. Scenario: Presence traffic does not wake the client Given a hibernated terminal client When a heartbeat acknowledgment and a read-only debug query arrive Then the client stays hibernated And the wake count does not changegherkin @FR-14MustThe terminal client shall not wake on presence traffic, on acknowledgments, or on read-only debug queries, and shall wake on any event that may change the conversation content or start active work. Scenario: A conversation event wakes the client Given a hibernated terminal client When a text delta arrives from the server Then the client is awake And the wake count increased by one -
FR-15MustThe terminal client shall trim its retained heap with a per-client growth budget of 16 MiB, an idle trim after 60 seconds of quiet, and a re-trim cadence of 300 seconds while the client stays idle.
gherkin @FR-15MustThe terminal client shall trim its retained heap with a per-client growth budget of 16 MiB, an idle trim after 60 seconds of quiet, and a re-trim cadence of 300 seconds while the client stays idle. Scenario: The client trims its retained heap while it stays idle Given a terminal client that has been quiet for longer than the idle trim delay When the periodic tick runs Then the client trims its retained heap against the per-client budget And it trims again on the re-trim cadence while the client stays idle -
FR-16ShouldThe system shall offer three hibernation depths selected by `hibernation_mode`, namely `caches` for rebuildable render caches only, `transcript` for the in-memory transcript as well, and `exit` for the client process, with `caches` as the default.
gherkin @FR-16ShouldThe system shall offer three hibernation depths selected by `hibernation_mode`, namely `caches` for rebuildable render caches only, `transcript` for the in-memory transcript as well, and `exit` for the client process, with `caches` as the default. Scenario: The mode selects the hibernation depth Given a configuration file that sets no mode When the hibernation policy is resolved Then the depth is the caches mode -
FR-17ShouldIn `transcript` mode the terminal client shall drop the in-memory transcript, clear the remote side pane images, and mark the history as needing a reload so that it is refetched from the server on wake.
gherkin @FR-17ShouldIn `transcript` mode the terminal client shall drop the in-memory transcript, clear the remote side pane images, and mark the history as needing a reload so that it is refetched from the server on wake. Scenario: The transcript mode refetches the history on wake Given a remote terminal client in the transcript mode that hibernated When the client wakes Then the history is marked as needing a reload And the in-memory transcript was released at hibernation time -
FR-18ShouldIn `exit` mode an idle remote client shall re-exec the process into a tiny waiter that resumes the session on the next key press.
gherkin @FR-18ShouldIn `exit` mode an idle remote client shall re-exec the process into a tiny waiter that resumes the session on the next key press. Scenario: The exit mode re-execs into a waiter and resumes on the next key press Given an idle remote terminal client in the exit mode When the client hibernates Then the client process is replaced by a waiter that holds the session id And the first byte of input resumes the session from the daemon -
FR-19ShouldThe system shall expose a read-only debug query that returns the hibernation state, the scope, the measured memory readings, the hibernation and wake counts and the last wake reason, and a debug command that requests an immediate hibernation.
gherkin @FR-19ShouldThe system shall expose a read-only debug query that returns the hibernation state, the scope, the measured memory readings, the hibernation and wake counts and the last wake reason, and a debug command that requests an immediate hibernation. Scenario: The debug query reports the state without changing it Given a hibernated terminal client When the read-only debug query runs Then it returns the state, the scope, the measured readings, the hibernation and wake counts and the last wake reason And the client stays hibernatedgherkin @FR-19ShouldThe system shall expose a read-only debug query that returns the hibernation state, the scope, the measured memory readings, the hibernation and wake counts and the last wake reason, and a debug command that requests an immediate hibernation. Scenario: The debug command hibernates immediately Given an idle terminal client with no queued work When the debug hibernation command runs Then the client hibernates without waiting for the idle period -
FR-20MayThe `JCODE_HIBERNATION_IDLE_SECS` and `JCODE_HIBERNATION_MODE` environment variables shall override the corresponding file configuration values, and an invalid override shall leave the file value in place.
gherkin @FR-20MayThe `JCODE_HIBERNATION_IDLE_SECS` and `JCODE_HIBERNATION_MODE` environment variables shall override the corresponding file configuration values, and an invalid override shall leave the file value in place. Scenario: The environment override replaces the file value Given a configuration file that sets an idle period When the environment sets a different idle period Then the environment value wins And an invalid environment value leaves the file value in place -
NFR-1MustThe released memory shall be measured, not estimated. A flat or unavailable reading shall never be displayed as a positive saving.
gherkin @NFR-1MustThe released memory shall be measured, not estimated. A flat or unavailable reading shall never be displayed as a positive saving. Scenario: An unchanged or unavailable reading is not shown as a saving Given a client whose memory reading did not change or could not be taken When the hibernation notice is rendered Then the notice shows an unchanged or unavailable reading And it does not claim a positive saving -
NFR-2MustThe wake shall be transparent. Rebuilding a released cache shall not invoke resume hooks, shall not cancel work, and shall not append a new environment snapshot.
gherkin @NFR-2MustThe wake shall be transparent. Rebuilding a released cache shall not invoke resume hooks, shall not cancel work, and shall not append a new environment snapshot. Scenario: Waking rebuilds caches without resume side effects Given a hibernated session whose caches were released When the next turn runs Then the provider receives the retained tool pairs And no resume hook ran and no new environment snapshot was appended -
NFR-3MustHibernationEvicting an idle session from memory, with transparent wake on the next interaction. shall not write the session file, and no disk-backed authoritative state shall be dropped on the strength of a queued save or of a save skipped because of a migration lease.
gherkin @NFR-3MustHibernationEvicting an idle session from memory, with transparent wake on the next interaction. shall not write the session file, and no disk-backed authoritative state shall be dropped on the strength of a queued save or of a save skipped because of a migration lease. Scenario: HibernationEvicting an idle session from memory, with transparent wake on the next interaction. does not write the session file Given a session file saved before hibernation When the session is hibernated Then the session file bytes and its modification time are unchanged -
NFR-4MustThe idle detection cost shall be bounded. The daemon shall sweep on a fixed 10 second interval, and the client shall poll on its existing tick, so no extra thread or timer is created per session.
gherkin @NFR-4MustThe idle detection cost shall be bounded. The daemon shall sweep on a fixed 10 second interval, and the client shall poll on its existing tick, so no extra thread or timer is created per session. Scenario: Idle detection uses a fixed cadence Given a running daemon with connected sessions When the daemon idles Then the sweep runs on a fixed 10 second interval And no extra thread or timer is created per session -
NFR-5MustThe frozen terminal frame shall be bounded to 128 thousand cells and 8 MiB of symbol bytes, and the per-client retained heap growth budget shall be capped at 16 MiB even when the global threshold is larger.
gherkin @NFR-5MustThe frozen terminal frame shall be bounded to 128 thousand cells and 8 MiB of symbol bytes, and the per-client retained heap growth budget shall be capped at 16 MiB even when the global threshold is larger. Scenario: The frozen frame and the client budget stay bounded Given a terminal frame with more cells than the bound or with more symbol bytes than the bound When the client considers freezing it Then the frame is refusedgherkin @NFR-5MustThe frozen terminal frame shall be bounded to 128 thousand cells and 8 MiB of symbol bytes, and the per-client retained heap growth budget shall be capped at 16 MiB even when the global threshold is larger. Scenario: The per-client budget caps the global threshold Given a global retained heap threshold of 64 MiB When the client resolves its own growth budget Then the client budget is 16 MiB And a lower global threshold is honored and a disabled threshold stays disabled -
NFR-6MustHibernationEvicting an idle session from memory, with transparent wake on the next interaction. shall not discard or cancel active work, pending input, or a scheduled wake.
gherkin @NFR-6MustHibernationEvicting an idle session from memory, with transparent wake on the next interaction. shall not discard or cancel active work, pending input, or a scheduled wake. Scenario: Active work is never discarded Given a session with a running turn and a tool in flight When the idle sweep runs Then the turn and the tool are not cancelled And the session caches are untouched -
NFR-7ShouldThe session shall survive hibernation with its identity, model settings, draft, transcript and scroll state intact.
gherkin @NFR-7ShouldThe session shall survive hibernation with its identity, model settings, draft, transcript and scroll state intact. Scenario: The session identity and the local transcript survive hibernation Given a client with a session id, stored source messages and local-only display messages When the client hibernates Then the session id, the stored source messages and the local-only display messages are unchanged -
NFR-8ShouldRepeated idle ticks shall not repeatedly rebuild and discard the same caches.
gherkin @NFR-8ShouldRepeated idle ticks shall not repeatedly rebuild and discard the same caches. Scenario: Repeated idle ticks do not rebuild the caches Given a hibernated client that is repainted several times When the renderer draws the frozen frame again Then the prepared frame caches stay released And they are rebuilt only after the client wakes -
NFR-9ShouldA configuration file without a `[session]` table shall inherit the default idle period of 30 minutes and the default mode of `caches`, and the settings shall round-trip through the configuration file.
gherkin @NFR-9ShouldA configuration file without a `[session]` table shall inherit the default idle period of 30 minutes and the default mode of `caches`, and the settings shall round-trip through the configuration file. Scenario: A configuration file without a session table inherits the defaults Given a configuration file with no session table When the configuration is parsed Then the idle period is 30 minutes and the mode is the caches mode And the settings round-trip through the file unchanged -
NFR-10ShouldThe exit-mode waiter shall hold only a few hundred KiB of private memory while it waits, and shall resume the session in about one second.
gherkin @NFR-10ShouldThe exit-mode waiter shall hold only a few hundred KiB of private memory while it waits, and shall resume the session in about one second. Scenario: The waiter is small and resumes quickly Given a client that hibernated in the exit mode When the waiter waits for a key press Then the waiter holds only a few hundred KiB of private memory And the session resumes in about one second -
NFR-11ShouldThe daemon shall record the hibernation outcome in its log, and the client shall record the wake reason and the measured change, so an operator can tell an idle release from a failed one.
gherkin @NFR-11ShouldThe daemon shall record the hibernation outcome in its log, and the client shall record the wake reason and the measured change, so an operator can tell an idle release from a failed one. Scenario: The outcome of a release is recorded Given an idle session that was released by the daemon When the sweep completes Then the log records the release with its session id and its measured memory change And a client wake records its reason
Conflicts
None identified yet.
Open Questions
- The exit mode applies only to a remote client today, because the daemon must own the session that the waiter resumes. Should a local client be able to exit into a waiter as well?
- The daemon sweep reads the idle period from the configuration on every tick, so a configuration change takes effect within 10 seconds. Should the daemon log a notice when the period changes under it?
- The transcript mode drops local-only display messages and the exact scroll position, and reloads the history from the server on wake. Should that mode be deprecated in favour of the caches mode?
Specification: SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. HibernationEvicting an idle session from memory, with transparent wake on the next interaction.
Overview
SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. hibernation is split between the daemon and the terminal client.
The daemon runs a background sweep that reclaims lazy reproducible caches for sessions that have been idle for long enough.
The terminal client releases its derived render caches and its retained heap after the same kind of idle period, keeps a bounded copy of its last frame, and measures its own memory before and after the release.
The wake is transparent: the next interaction restores the session without a thaw protocol, because the canonical transcript never left memory.
A third mode goes further and replaces the client process with a tiny waiter that resumes the session on the next key press.
The shared policy lives in crates/jcode-config-types/src/session.rs so the daemon and the client read the same idle period and the same mode.
This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
[session] config (crates/jcode-config-types/src/session.rs)
hibernation_idle_secs = 1800 (0 disables)
hibernation_mode = caches | transcript | exit
+---------------------------------------------+ +---------------------------------------------+
| [session] config (jcode-config-types) | | jcode-base::process_memory |
| | | snapshot() rss / pss_anon |
| jcode-base::config | | release_retained_heap() |
| Config.session | | |
| env override: JCODE_HIBERNATION_IDLE_SECS | | |
| JCODE_HIBERNATION_MODE | | |
+---------------------------------------------+ +---------------------------------------------+
| |
v v
+---------------------------------------------+ +---------------------------------------------+
| jcode-app-core::server::idle_hibernation | | jcode-tui::app::idle_hibernation |
| spawn() every 10 s | | poll_idle_hibernation() |
| try_read sessions / members | | enter_idle_hibernation() |
| IdleState { since, last_status_change, | | wake_idle_hibernation() |
| released } | | finish_idle_hibernation_frame() |
| reclaim_idle_caches() | | |
| -> Agent::hibernate_idle_caches() | | jcode-tui::app::idle_heap_release |
| -> release_retained_heap() | | maybe_release_idle_heap() |
| | | 16 MiB budget, 60 s idle, 300 s re-trim |
+---------------------------------------------+ +---------------------------------------------+
| |
v v
+---------------------------------------------+ +---------------------------------------------+
| jcode-app-core::agent | | derived render caches released |
| hibernate_idle_caches() | | prepared frames, rendered lines, |
| refuses: active turn, migration lease, | | highlighting, copy viewport, side pane, |
| pending alerts, soft interrupts, | | diff and image state, markdown renderer |
| compaction, in-flight tool | | frame frozen (bounded) |
| returns IdleCacheRelease | | private memory measured before / after |
+---------------------------------------------+ +---------------------------------------------+
|
v
+---------------------------------------------+
| session cache release |
| release_provider_messages_cache() |
| tool_call_ids = {} |
| tool_result_ids = {} |
| tool_output_scan_index = 0 |
+---------------------------------------------+
exit mode (remote client only)
App::hibernate_exit_requested -> RunResult.hibernate_session
-> cli::hot_exec::execute_requested_action
-> cli::hibernate_wait::waiter_command
(JCODE_HIBERNATE_WAIT=1, --resume SESSION_ID)
-> platform::replace_process
-> main() intercepts before the tokio runtime
-> draw_notice() -> wait_for_input()
-> replace_process (same args, marker removed)
The daemon never suspends the scheduler and never replaces the live Agent or session.
The client never rebuilds the transcript from disk to wake; it only drops derived state that the renderer recreates.
Data Models
IdleCacheRelease
The report of what one daemon-side hibernation released.
Defined in crates/jcode-app-core/src/agent/idle_hibernation.rs.
| Field | Type | Constraints | Description |
|---|---|---|---|
| provider_cache_bytes | usize | not null, may be 0 | The size in bytes of the provider message cache that was released, taken from the session memory profile snapshot before the release. |
| tool_index_entries | usize | not null, may be 0 | The number of entries in the tool call and tool result id sets that were released. |
The report is summed across the sessions released in one sweep and written to the log together with the before and after resident memory of the daemon process.
SessionConfig
The shared idle policy, defined in crates/jcode-config-types/src/session.rs and embedded in Config as the session field.
| Field | Type | Constraints | Description |
|---|---|---|---|
| hibernation_idle_secs | u64 | Default 1800, 0 disables hibernation |
The number of seconds without work or interaction before memory is released. |
| hibernation_mode | HibernationMode | Default Caches |
How much an idle terminal client releases when it hibernates. |
The table is optional in the configuration file, and a file without it inherits the defaults.
JCODE_HIBERNATION_IDLE_SECS and JCODE_HIBERNATION_MODE override the file values, and an invalid override is ignored.
HibernationMode
The depth of idle terminal client hibernation, from cheapest wake to largest saving.
| Variant | Serialized name | Aliases | Behavior |
|---|---|---|---|
| Caches | caches |
cache |
Drop rebuildable render caches only. The wake is instant and lossless. This is the default. |
| Transcript | transcript |
none | Also drop the in-memory transcript and reload it from the server on wake. Local-only notices and the exact scroll position are not kept. |
| Exit | exit |
process |
Exit the client process entirely, leaving a tiny waiter that resumes the session on the next key press. The largest saving, and a wake of about one second. |
Client idle state
The client-side state machine, defined in crates/jcode-tui/src/tui/app/idle_hibernation.rs.
| Field | Type | Description |
|---|---|---|
| last_busy | Instant | The last moment the client was busy; the idle period is measured from it. |
| pending | bool | The idle period elapsed and the client asked for a full repaint, but the eviction has not happened yet. |
| frame | Option\<Buffer> | The bounded copy of the last completed terminal frame, kept on screen while hibernated. |
| notice | String | The one-line hibernation status, including the measured memory change. |
| rss_before | Option\<u64> | The private memory measured before the release. |
| rss_after | Option\<u64> | The private memory measured after the release, and again after the first frozen frame was painted. |
| measure_after_frame | bool | Set when the eviction point sample was taken and the frame sample is still owed. |
| notice_dirty | bool | Set when the notice changed and the screen must be repainted. |
| transcript_dropped | bool | Set in the transcript mode when the in-memory transcript was released. |
| history_reload_needed | bool | Set on wake when the transcript was dropped, so the history is refetched. |
| wake_count | u64 | The number of wakes so far. |
| hibernation_count | u64 | The number of hibernations so far. |
| last_wake_reason | Option\<String> | The reason of the last wake, for the debug query. |
Daemon idle state
The per-session idle bookkeeping of the daemon sweep, defined in crates/jcode-app-core/src/server/idle_hibernation.rs.
| Field | Type | Description |
|---|---|---|
| since | Instant | The start of the current idle window. |
| last_status_change | Instant | The swarm status generation observed at the last sweep, used to detect a turn that started and finished between two sweeps. |
| released | bool | Whether the session was already released, so it is not released twice. |
API Contracts
There is no HTTP surface for session hibernation. The contract is a configuration contract plus a debug command surface, so the tables below describe the callable surfaces instead of REST endpoints.
Configuration
| Setting | Type | Default | Effect |
|---|---|---|---|
[session] hibernation_idle_secs |
u64 | 1800 | Seconds of inactivity before memory is released. 0 disables hibernation. |
[session] hibernation_mode |
string | caches |
caches, transcript or exit. |
Debug commands
| Command | Kind | Effect |
|---|---|---|
client:hibernation |
read-only | Returns the state, the scope, the source transcript retention flag, the memory metric, the busy flag, the hibernation and wake counts, the last wake reason, the measured readings, the signed change, the measurement phase, the frozen cell count and the notice. |
client:hibernate |
mutating | Requests an immediate hibernation. It bypasses the elapsed time requirement, but not the active work guards and not the disable setting. |
Process contract for the exit mode
| Variable | Meaning |
|---|---|
JCODE_HIBERNATE_WAIT |
Set to 1 on the waiter process. main intercepts it before the tokio runtime is built, so the waiter holds only a few hundred KiB. |
JCODE_RESUMING |
Set to 1 on the waiter and on the resumed client, so the client knows it is resuming an existing session. |
JCODE_RELOAD_FAST_START |
Set to 1 on the resumed client, so it paints and accepts input before the authoritative history arrives. |
Sequences
Hibernate an idle session and wake it
sequenceDiagram
autonumber
participant T as TUITerminal User Interface tick
participant A as App (client)
participant M as process_memory
participant U as User
T->>A: poll_idle_hibernation()
A->>A: hibernation_has_work() == false
A->>A: now - last activity >= hibernation_idle_secs
A->>A: pending = true, force_full_repaint = true
T->>A: enter_idle_hibernation(last_frame)
A->>A: hibernation_has_work() re-check
A->>A: frame_can_be_frozen(frame)
A->>M: private_memory_bytes() (before)
A->>A: release provider message cache and derived render caches
A->>M: release_retained_heap("tui_hibernation")
A->>M: private_memory_bytes() (after)
A->>A: notice = "Hibernated, private mem -N MiB"
T->>A: draw_full -> finish_idle_hibernation_frame()
A->>M: private_memory_bytes() (after frame)
A->>A: notice updated with the frame sample
U->>A: key press
A->>A: wake_idle_hibernation() before the event is handled
A->>A: frame dropped, notice cleared, force_full_repaint = true
A->>U: the same key press is then handled normally
The daemon sweep releases an idle session
sequenceDiagram
autonumber
participant S as idle sweep (10 s)
participant R as sessions / members
participant A as Agent
participant M as process_memory
S->>R: try_read sessions and members
R-->>S: busy readers refuse, the sweep is skipped
S->>A: hibernate_idle_caches()
A->>A: refuse on active turn, lease, alerts, queue, compaction, in-flight tool
A-->>S: None (the idle window is reset)
A-->>S: Some(IdleCacheRelease)
S->>M: release_retained_heap("server_idle_hibernation")
S->>M: snapshot before and after
S->>S: log the released sessions and the measured change
The exit mode re-execs into a waiter
sequenceDiagram
autonumber
participant A as App (client)
participant X as cli::hot_exec
participant W as hibernate_wait (waiter)
participant D as Daemon
A->>A: mode == exit, remote session id known
A->>A: save_input_for_reload(session_id)
A->>A: hibernate_exit_requested = Some(session_id), should_quit = true
A->>X: RunResult.hibernate_session
X->>X: waiter_command(session_id) with JCODE_HIBERNATE_WAIT=1
X->>X: platform::replace_process(cmd)
W->>W: main intercepts before the tokio runtime
W->>W: draw_notice(), wait_for_input()
W->>W: replace_process(same args, marker removed, JCODE_RELOAD_FAST_START=1)
W->>D: resume the session
D-->>W: the session continues
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Release derived state, not authoritative state | Only lazy reproducible caches are discarded | Reloading a session is not a transparent wake operation, so the canonical transcript, the frozen prompts and tools, the rewind undo state, the provider handle and the hook state stay resident. |
| The daemon sweeps on a fixed interval | A 10 second tokio interval with a skipped missed tick |
A fixed cadence bounds the detection cost and needs no timer per session. |
| The sweep never queues behind a lock | try_read on the session and member maps, try_lock on the agent |
The sweep must never delay a live turn, a roster change or a session operation. |
| The sweep releases the heap once per sweep | One process-wide purge after every agent and roster lock is dropped | RSS is a process-wide metric, so purging once avoids repeated allocator work for the same saving. |
| The idle window is tracked per session | A map from session id to an idle state | A session that becomes busy is dropped from the map, and a session that is released once is not released again until it becomes busy again. |
| A turn between two sweeps is detected by generation | The status change instant is compared, not its age | A whole turn can start and finish between two sweeps, even for thresholds below 10 seconds. |
| A decline resets the idle window | since is set to now when the agent refuses |
Pending input, alerts, compaction and live tools all mean the session is not idle, so the window restarts. |
| The client freezes a bounded copy of the last frame | At most 128 thousand cells and 8 MiB of symbol bytes | Repainting the transcript into new caches on every idle tick would undo the saving, and an unbounded frame could hold more memory than it saves. |
| The client measures private memory, not shared pages | The anonymous proportional set size when the platform provides it, otherwise the resident set size | RSS counts the executable and the shared libraries that every client maps once, so a plain RSS change overstates what hibernation actually freed. |
| The final client sample is taken after the first frozen frame | The frame sample replaces the eviction point sample | The retained screen buffers belong to the hibernated state, so the reported number has to include them. |
| A positive change is shown as an increase | The notice formats the signed difference | A flat or unavailable reading must never be presented as a saving. |
| The wake happens before the event is handled | wake_idle_hibernation runs on the way into the handler and never consumes the event |
The first typed character is inserted at the original cursor position, and the draft, the cursor and the scroll state are untouched. |
| Presence traffic does not wake the client | Heartbeats, acknowledgments, swarm status, side panel state, usage, model catalogs, memory activity and MCP status are excluded | These are read-only or periodic traffic, and waking on them would rebuild the caches on every tick. |
| The work guard is re-checked at the eviction point | hibernation_has_work runs again inside enter_idle_hibernation |
Work can arrive between the timer and the paint, and the eviction must not cancel it. |
| The transcript mode reloads the history on wake | A history_reload_needed flag is set only when the transcript was dropped |
The remote history fetch is not a lossless snapshot of the local view, so the flag exists only for the mode that actually drops it. |
| The exit mode replaces the process | The client execs into a waiter that holds a few hundred KiB | Leaving the process in place cannot free its heap, and the daemon still owns the session, so the waiter can resume it. |
| The waiter is intercepted before the tokio runtime | main checks JCODE_HIBERNATE_WAIT first |
A runtime would keep worker threads and their stacks resident, which defeats the purpose of the exit mode. |
| The client trims its retained heap separately from hibernation | A 16 MiB per-client budget, a 60 second idle delay and a 300 second re-trim cadence | A workspace runs one process per open terminal, so the shared global threshold would retain hundreds of MiB in aggregate. |
| The per-client budget honors a lower global threshold | The client budget is the minimum of the global threshold and 16 MiB | An operator who set a lower threshold keeps it, and a disabled threshold stays disabled. |
The config type lives in jcode-config-types |
SessionConfig and HibernationMode are shared types |
The daemon and the client must read the same policy, and the crate keeps the shared data models free of the application stack. |
Risks and Unknowns
- The released memory is a measurement, not a promise. Allocator behavior, shared pages and concurrent work all affect it, and a controlled 64 MiB fixture released about 63 MiB while a small real TUITerminal User Interface fixture released only about 278 KB.
- The daemon sweep reads the configuration on every tick, so the idle period can change under a running daemon without a notice.
- The exit mode applies only to a remote client today, because the daemon must own the session that the waiter resumes. A local client cannot use it.
- The transcript mode drops local-only display messages and the exact scroll position, because the remote history fetch cannot restore them.
- The client polls the idle policy on its existing tick, so the effective idle period is the configured period plus up to one tick of latency.
- The frozen frame is a copy of the terminal buffer, and its bound of 8 MiB of symbol bytes is a heuristic. A frame with very large inline image payloads can be refused and then retried on later idle ticks.
- The daemon release is counted per session, but the resident memory it reports is process-wide, so a single sweep that releases several sessions reports one combined change.
- The manual RSS measurement test in the agent module is ignored by default, because the allocator and the other tests in the same process perturb the reading.
- The transcript mode marks the history for reload but does not define a reconciliation for local-only messages that were never sent to the server.
Out of Scope
- Process suspension, swapping the scheduler or suspending the OS.
- Evicting the authoritative client transcript outside the explicit transcript mode.
- Serializing and destroying the whole agent, which needs a separate audited persistence and thaw boundary.
- A cross-session memory budget or a workspace-wide eviction policy.
- Changing the memory budget of the daemon itself beyond the idle cache sweep and the allocator purge.
- The daemon side of the transcript and exit modes, which are client-side depths only.
Test Plan: SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. HibernationEvicting an idle session from memory, with transparent wake on the next interaction.
Scope
Covers the shared idle policy in the configuration layer, the daemon idle sweep and the agent cache release, the terminal client hibernation and wake, the client retained heap trim, and the remote history reload that the transcript mode triggers.
Out of scope: the exit-mode process re-exec and the waiter process in src/cli/hibernate_wait.rs, which have no automated test in this repository, and the measured resident memory of an ordinary session, which depends on the workload and the allocator.
The tests live in the modules they cover, as #[cfg(test)] mod tests blocks, not as separate test files.
Each row below names the file and the test function that exists in it.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | The idle due check in crates/jcode-app-core/src/server/idle_hibernation.rs (idle_hibernation_due_respects_disable_idle_and_recent_activity) |
An idle state built at a start instant, a 30 second threshold, and variations of the threshold, the status idle age and the activity age | A zero threshold is never due, an unreached threshold is not due, a status that changed recently is not due, a recent activity age is not due, and the fully idle state is due |
| TC-2 | The idle re-arm in crates/jcode-app-core/src/server/idle_hibernation.rs (idle_hibernation_rearms_for_turn_entirely_between_monitor_ticks) |
A released idle state, a 1 second threshold, a turn that finished 2 seconds after the start, and a sweep at 10 seconds | The state is not due while the status change is recent, it becomes due once the turn that started and finished between two sweeps is observed, and it is not due again while it stays released |
| TC-3 | The agent refusal guards in crates/jcode-app-core/src/agent/idle_hibernation.rs (idle_hibernation_refuses_queued_alerts_busy_compaction_and_live_tools) |
An agent with a queued pending alert, a queued soft interrupt, a held soft interrupt queue, a held compaction write lock, a tool marked in flight, and a registered active turn | Each guard makes hibernate_idle_caches return None, the provider cache keeps its two messages while the tool is in flight, and the release succeeds once the turn is dropped |
| TC-4 | The agent cache release in crates/jcode-app-core/src/agent/idle_hibernation.rs (idle_hibernation_releases_cache_and_rebuilds_exact_history_and_indexes) |
An agent with a large paired tool result, frozen tools, a captured instructions snapshot, a provider session handle and a rewind undo snapshot | The release reports more than one million provider cache bytes and two tool index entries, the provider cache count drops to zero, the tool id sets are emptied, the serialized session, the provider messages, the frozen tools, the captured instructions, the undo snapshot and the provider handle are unchanged, and the next turn rebuilds the indexes without adding synthetic duplicates |
| TC-5 | The no-write and lease behaviour in crates/jcode-app-core/src/agent/idle_hibernation.rs (idle_hibernation_does_not_write_session_and_refuses_migration_lease) |
A saved session file, an unsaved local message, and a migration lease written for the session | The release leaves the session file bytes and its modification time unchanged, a save under the lease succeeds without writing, the release is refused while the lease is present, and the local message and the provider cache survive |
| TC-6 | The client idle trigger in crates/jcode-tui/src/tui/app/idle_hibernation.rs (idle_hibernation_respects_timeout_typing_streaming_and_disabled_config) |
An expired idle timer, a zero idle period, a 1802 second idle period, a fresh user interaction, a fresh stream activity | A zero period never hibernates, a period that has not elapsed does not hibernate, a fresh user interaction does not hibernate, a fresh stream activity does not hibernate, and the elapsed period does hibernate |
| TC-7 | The eviction point work guard in crates/jcode-tui/src/tui/app/idle_hibernation.rs (idle_hibernation_rechecks_every_queued_and_active_work_guard) |
Sixteen busy states, each applied after the idle timer elapsed but before the paint | For every state no frame is frozen and the client stays awake |
| TC-8 | The retained client state in crates/jcode-tui/src/tui/app/idle_hibernation.rs (idle_hibernation_keeps_sources_draft_scroll_and_first_typed_character) |
A client with a local-only display message, a provider source message, a stored session message, a draft, a cursor, an attachment, a pasted content, a scroll offset and a paused scroll | The draft, the cursor, the scroll offset, the paused scroll, the session id, the source messages, the stored messages, the attachment and the pasted content survive the hibernation, and the first typed character is appended at the original cursor with the scroll offset unchanged and the notice cleared |
| TC-9 | The wake triggers in crates/jcode-tui/src/tui/app/idle_hibernation.rs (idle_hibernation_paste_resize_and_display_changes_wake_without_loss) |
A hibernated client that is then pasted into, resized, and given a new display message | Each of the three wakes the client, the pasted text lands in the input, and the new display message is kept |
| TC-10 | The frame bounds in crates/jcode-tui/src/tui/app/idle_hibernation.rs (idle_hibernation_rejects_unbounded_and_missing_screen_snapshots) |
A missing frame, a frame with a single oversized symbol, and an empty frame | No frame is frozen when the frame is missing, the oversized frame is refused by the freeze check, and the empty frame is refused |
| TC-11 | The memory metric in crates/jcode-tui/src/tui/app/idle_hibernation.rs (private_memory_metric_prefers_pss_anon) |
The process memory snapshot taken twice in a row, on a platform that reports the anonymous proportional set size | The measured private memory matches the reported anonymous proportional set size within 64 MiB |
| TC-12 | The transcript reload flag in crates/jcode-tui/src/tui/app/idle_hibernation.rs (transcript_drop_marks_history_reload_on_wake_only_when_dropped) |
A client that hibernated in the caches mode, and a client whose transcript was dropped | The caches mode does not request a history reload, the dropped transcript does, and the dropped flag is cleared |
| TC-13 | The notice formatting in crates/jcode-tui/src/tui/app/idle_hibernation.rs (idle_hibernation_rss_notice_reports_measurement_without_inventing_savings) |
A before and after pair 30 MiB apart in each direction, an equal pair, and a missing reading | The notice reports -30.0 MiB, reports +30.0 MiB for an increase, reports unchanged for a flat reading, and never breaks the line when a reading is missing |
| TC-14 | The wake event filter in crates/jcode-tui/src/tui/app/idle_hibernation.rs (idle_hibernation_ignores_heartbeat_but_wakes_before_remote_stream_event) |
A hibernated remote client that receives a pong, an acknowledgment and a text delta | The pong and the acknowledgment leave the client hibernated with a wake count of zero, and the text delta wakes the client, clears the notice and raises the wake count to one |
| TC-15 | The debug surface in crates/jcode-tui/src/tui/app/idle_hibernation.rs (idle_hibernation_debug_request_survives_recent_input_and_read_only_queries) |
A client with a recent user interaction that requests a debug hibernation and then reads the debug state three times | The state is pending before the paint, hibernated afterwards, the hibernation count is one, the wake count is zero, and reading the state does not wake the client |
| TC-16 | The retention check cadence in crates/jcode-tui/src/tui/app/idle_heap_release.rs (retention_check_runs_immediately_then_obeys_interval) |
No previous check, a check at the current instant, and a check one interval old | The check is due when it never ran, not due again in the same instant, and due once one retention check interval has passed |
| TC-17 | The per-client budget in crates/jcode-tui/src/tui/app/idle_heap_release.rs (client_retention_threshold_caps_default_but_honors_lower_and_disabled) |
A global threshold of 64 MiB, of 8 MiB, and a disabled threshold | The 64 MiB global threshold is capped to 16 MiB, the lower 8 MiB threshold is honored, and the disabled threshold stays disabled |
| TC-18 | The idle re-trim cadence in crates/jcode-tui/src/tui/app/idle_heap_release.rs (idle_retrim_waits_for_first_trim_then_fires_on_cadence) |
No trim yet this idle period, a trim at the current instant, and a trim one re-trim interval old | The re-trim is not due before the first trim of the idle period, not due again in the same instant, and due once the re-trim interval has passed |
| TC-19 | The config defaults in crates/jcode-config-types/src/session.rs (missing_setting_defaults_to_thirty_minutes) |
A session config deserialized from an empty object | The idle period is 1800 seconds and the mode is the caches mode |
| TC-20 | The config round trip in crates/jcode-config-types/src/session.rs (zero_disables_hibernation_and_roundtrips) |
A session config with a zero idle period and the exit mode, serialized and deserialized | The serialized form contains "exit", and the restored config keeps both the zero period and the exit mode |
| TC-21 | The mode aliases in crates/jcode-config-types/src/session.rs (mode_parses_aliases) |
The strings " Transcript ", "process" and "bogus" |
The first parses as the transcript mode, the second as the exit mode, and the third is refused |
| TC-22 | The environment override in crates/jcode-base/src/config_tests.rs (hibernation_environment_override_accepts_seconds_and_zero_but_not_invalid_values) |
The values 60, " 0 ", -1 and invalid for JCODE_HIBERNATION_IDLE_SECS |
The first two are applied, and the two invalid values leave the default of 1800 in place |
| TC-23 | The configuration file in crates/jcode-base/src/config/default_file.rs (default_config_template_parses, session_hibernation_config_defaults_and_roundtrips) |
The shipped configuration template, an empty file, a file with a zero idle period, and a file with the exit mode | The shipped template parses and holds an idle period of 1800, an empty file inherits the default, a zero period round-trips through the file, and the exit mode parses from the file |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-24 | The daemon sweep in crates/jcode-app-core/src/server/idle_hibernation.rs (idle_hibernation_monitor_skips_busy_and_running_then_releases_once) |
A real Agent behind a tokio mutex, a real swarm member whose status is changed, and a one second threshold |
The sweep releases nothing while the agent lock is held and drops the session from the idle map, releases nothing while the member is running, releases once when the member is ready, does not release the same session twice, and clears the idle map when the threshold is zero |
| TC-25 | The next turn after a release in crates/jcode-app-core/src/agent/idle_hibernation.rs (idle_hibernation_next_turn_sends_original_tool_pairs_without_duplicates) |
A real Agent with a capturing provider, a paired tool result from before the release, and an isolated JCODE_HOME |
The release succeeds, the next turn runs and returns the provider text, and the captured request holds exactly one tool use and one tool result for the pre-hibernation tool, with the original result text and no missing-output placeholder |
| TC-26 | The frozen frame and the render caches in crates/jcode-tui/src/tui/app/idle_hibernation.rs (idle_hibernation_frozen_frames_do_not_repopulate_prepared_caches) |
A real ratatui TestBackend terminal, a drawn frame, and a weakly held prepared chat frame |
The prepared frame owners are all released at hibernation, the render caches stay empty across three redraws of the frozen frame, the screen shows the hibernation notice and the measured change, the frozen frame is not replaced by a later hibernation attempt, and the caches are rebuilt only after the client wakes |
| TC-27 | The hibernation status row in crates/jcode-tui/src/tui/app/idle_hibernation.rs (idle_hibernation_notice_shows_measured_rss_on_one_status_row) |
A hibernated client rendered through a real ratatui TestBackend terminal of 70 by 10 cells |
The rendered screen contains the hibernation word, the measured change of -30.0 MiB and the resume hint |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-28 | The measured resident memory of a release in crates/jcode-app-core/src/agent/idle_hibernation.rs (idle_hibernation_measured_rss_delta) |
Run the ignored test on an isolated process: build an agent with a 64 MiB tool result, warm the provider cache, snapshot the resident memory, release, purge the retained heap, snapshot again | The release reports the provider cache size, the two resident memory readings differ by the released amount, and the provider cache count is zero while the session still holds its two messages. The test is marked #[ignore] because the allocator and the other tests in the same process perturb the reading, so it is a manual measurement rather than an automated one |
| TC-29 | The remote history reload in crates/jcode-tui/src/tui/app/tests/remote_events_reload_03/part_02.rs (test_delta_history_without_prefix_requests_full_history) |
Deliver a delta history event that carries no prefix to a client that had dropped its transcript | The client marks the history as needing a reload and does not treat the remote history as loaded |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-30 | The idle period is set to zero | HibernationEvicting an idle session from memory, with transparent wake on the next interaction. is disabled on both the daemon and the client, the daemon clears its idle map, and the debug hibernation command refuses with a disabled error |
| TC-31 | The environment override carries a negative or a non-numeric value | The override is ignored and the file value stays in place |
| TC-32 | A whole turn starts and finishes between two daemon sweeps | The idle window is re-armed from the moment the turn finished, so the session is not hibernated by the sweep that missed the turn |
| TC-33 | A session is running a turn, or a tool is in flight | The daemon declines the release, resets the idle window, and neither the turn nor the tool is cancelled |
| TC-34 | A queued alert or a queued soft interrupt is pending | The daemon declines the release, so a scheduled wake is never dropped by hibernation |
| TC-35 | A compaction is in flight | The daemon declines the release, so the compaction is not disturbed |
| TC-36 | A migration lease is held for the session | The daemon declines the release, and a save under the lease is a successful no-op that does not write the file |
| TC-37 | The session file was saved before the hibernation | The file bytes and the modification time are unchanged after the release |
| TC-38 | The frozen frame is missing, empty, oversized in cells, or oversized in symbol bytes | The release still happens, no frame is frozen, and the client does not retry the oversized frame on every idle tick |
| TC-39 | The memory reading is flat, or cannot be taken | The notice reports unchanged or a reading without a saving, and it never claims a positive saving |
| TC-40 | The memory reading increased after the release | The notice reports the increase with a + sign, and the change is not presented as a saving |
| TC-41 | The client receives a heartbeat, an acknowledgment or a read-only debug query while hibernated | The client stays hibernated, the wake count does not change, and the idle clock is not reset |
| TC-42 | The client receives an event that may change the conversation content | The client wakes, the notice is cleared, and the wake count increases by one |
| TC-43 | Work is queued between the idle timer and the paint | Nothing is evicted, the client stays awake, and the queued work is not cancelled |
| TC-44 | The client is repainted repeatedly while hibernated | The prepared frame caches stay released and are rebuilt only after the wake |
| TC-45 | The global retained heap threshold is disabled | The client never trims its retained heap, and the disabled state is preserved |
| TC-46 | The global retained heap threshold is lower than the per-client budget | The lower threshold is honored |
| TC-47 | The client stays idle for a long stretch with only heartbeats and remote snapshots | The retained heap is re-trimmed on the re-trim cadence, not only once per idle period |
Test Infrastructure
- The daemon and agent tests take
crate::storage::lock_test_env()and setJCODE_HOMEto a temporary directory, so parallel tests do not share session state. - The agent tests use a
TestProviderthat fails the test if the provider is called, so a hibernation path can never silently issue a request. - The next turn test uses a
CaptureProviderthat records the message list it receives, so the request that follows a release can be inspected. - The daemon sweep test builds a real
Agent, a realSwarmMemberand a realSessionAgentsmap, so the sweep exercises the same locks and the same status flags as production. - The client tests use
crate::tui::app::tests::create_test_app()and a ratatuiTestBackendterminal, so the frame bounds, the frozen frame and the rendered status row are exercised through the real renderer. - The render tests take
crate::tui::ui::render_state_test_lock(), because the prepared frame caches are process-global. - The idle timer is expired deterministically by moving
app_started,last_busy,last_user_interactionandlast_stream_activityinto the past, so no test sleeps for the idle period. - The manual RSS measurement test is marked
#[ignore]and is meant to be run on an isolated process. - Useful commands:
cargo test -p jcode-app-core idle_hibernation,cargo test -p jcode-tui idle_hibernation,cargo test -p jcode-tui idle_heap_release,cargo test -p jcode-config-types session,cargo test -p jcode-base hibernation.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall release reloadable memory for a session that has had no work and no interaction for the configured idle period, and shall treat an idle period of `0` as hibernation disabled. | TC-1, TC-6, TC-19, TC-20 |
| FR-2MustThe system shall read the idle period and the hibernation depth from the `[session]` configuration table, using the key `hibernation_idle_secs` for the period and `hibernation_mode` for the depth. | TC-19, TC-20, TC-21, TC-23 |
| FR-3MustThe daemon shall sweep idle sessions on a 10 second interval and shall reclaim only lazy reproducible caches, namely the provider message cache and the reconstructible tool output indexes. | TC-3, TC-4, TC-24 |
| FR-4MustThe daemon shall refuse to hibernate a session that has an active turn, pending input, a queued alert or soft interrupt, an in-flight compaction, an in-flight tool, or a migration lease. | TC-3, TC-24, TC-33, TC-34, TC-35 |
| FR-5MustThe daemon shall reset the idle window of a session it declines to hibernate because work is pending, and shall re-arm the idle window when a turn starts and finishes entirely between two sweeps. | TC-1, TC-2, TC-24, TC-32 |
| FR-6MustThe daemon shall keep the canonical transcript live across hibernation, retaining the original messages, the frozen tool definitions, the captured instructions, the rewind undo snapshot, and the provider session handle. | TC-4, TC-5 |
| FR-7MustThe daemon shall purge retained heap once per sweep, after releasing every session lock, and shall record the released session ids, the released provider cache bytes, the released tool index entries, and the before and after resident memory. | TC-24, TC-28 |
| FR-8MustThe terminal client shall release its derived render caches, namely the prepared transcript and body frames, the rendered message lines, the syntax highlighting cache, the copy viewport snapshot, the derived side panel, diff and image state, the incremental markdown renderer, and the local provider message cache. | TC-26, TC-44 |
| FR-9MustThe terminal client shall retain the authoritative source data across hibernation, keeping the input draft, the cursor position, the scroll offset, the scroll lock state, the attachments, the pasted contents, and the local-only display messages. | TC-8, TC-9, TC-41 |
| FR-10MustThe terminal client shall keep a bounded copy of the last completed terminal frame, and shall refuse to freeze a frame that is missing or that exceeds the cell or symbol bounds. | TC-10, TC-38 |
| FR-11MustThe terminal client shall measure its own memory before and after the release and shall report the measured change in the hibernation notice, showing an increase as an increase and an unchanged reading as unchanged. | TC-11, TC-13, TC-27, TC-39, TC-40 |
| FR-12MustThe next interaction shall wake the session transparently, processing the waking event normally including its first character, and leaving the draft, the cursor, the scroll position and the session state untouched by the wake. | TC-8, TC-9, TC-42 |
| FR-13MustThe terminal client shall re-check every queued and active work guard at the moment of eviction, and shall not evict anything when work has arrived since the idle timer was scheduled. | TC-7, TC-43 |
| FR-14MustThe terminal client shall not wake on presence traffic, on acknowledgments, or on read-only debug queries, and shall wake on any event that may change the conversation content or start active work. | TC-14, TC-15, TC-41, TC-42 |
| FR-15MustThe terminal client shall trim its retained heap with a per-client growth budget of 16 MiB, an idle trim after 60 seconds of quiet, and a re-trim cadence of 300 seconds while the client stays idle. | TC-16, TC-17, TC-18, TC-45, TC-46, TC-47 |
| FR-16ShouldThe system shall offer three hibernation depths selected by `hibernation_mode`, namely `caches` for rebuildable render caches only, `transcript` for the in-memory transcript as well, and `exit` for the client process, with `caches` as the default. | TC-19, TC-21, TC-23 |
| FR-17ShouldIn `transcript` mode the terminal client shall drop the in-memory transcript, clear the remote side pane images, and mark the history as needing a reload so that it is refetched from the server on wake. | TC-12, TC-29 |
| FR-18ShouldIn `exit` mode an idle remote client shall re-exec the process into a tiny waiter that resumes the session on the next key press. | TC-23 |
| FR-19ShouldThe system shall expose a read-only debug query that returns the hibernation state, the scope, the measured memory readings, the hibernation and wake counts and the last wake reason, and a debug command that requests an immediate hibernation. | TC-15, TC-30 |
| FR-20MayThe `JCODE_HIBERNATION_IDLE_SECS` and `JCODE_HIBERNATION_MODE` environment variables shall override the corresponding file configuration values, and an invalid override shall leave the file value in place. | TC-22, TC-31 |
| NFR-1MustThe released memory shall be measured, not estimated. A flat or unavailable reading shall never be displayed as a positive saving. | TC-11, TC-13, TC-39, TC-40 |
| NFR-2MustThe wake shall be transparent. Rebuilding a released cache shall not invoke resume hooks, shall not cancel work, and shall not append a new environment snapshot. | TC-4, TC-25 |
| NFR-3MustHibernationEvicting an idle session from memory, with transparent wake on the next interaction. shall not write the session file, and no disk-backed authoritative state shall be dropped on the strength of a queued save or of a save skipped because of a migration lease. | TC-5, TC-36, TC-37 |
| NFR-4MustThe idle detection cost shall be bounded. The daemon shall sweep on a fixed 10 second interval, and the client shall poll on its existing tick, so no extra thread or timer is created per session. | TC-16, TC-24 |
| NFR-5MustThe frozen terminal frame shall be bounded to 128 thousand cells and 8 MiB of symbol bytes, and the per-client retained heap growth budget shall be capped at 16 MiB even when the global threshold is larger. | TC-10, TC-17, TC-38 |
| NFR-6MustHibernationEvicting an idle session from memory, with transparent wake on the next interaction. shall not discard or cancel active work, pending input, or a scheduled wake. | TC-3, TC-7, TC-24, TC-33 |
| NFR-7ShouldThe session shall survive hibernation with its identity, model settings, draft, transcript and scroll state intact. | TC-8, TC-29 |
| NFR-8ShouldRepeated idle ticks shall not repeatedly rebuild and discard the same caches. | TC-26, TC-44 |
| NFR-9ShouldA configuration file without a `[session]` table shall inherit the default idle period of 30 minutes and the default mode of `caches`, and the settings shall round-trip through the configuration file. | TC-19, TC-20, TC-23 |
| NFR-10ShouldThe exit-mode waiter shall hold only a few hundred KiB of private memory while it waits, and shall resume the session in about one second. | TC-28 |
| NFR-11ShouldThe daemon shall record the hibernation outcome in its log, and the client shall record the wake reason and the measured change, so an operator can tell an idle release from a failed one. | TC-24, TC-28 |
Known gaps
- The exit mode has no automated test.
src/cli/hibernate_wait.rsand the exit branch ofcrates/jcode-tui/src/tui/app/idle_hibernation.rsare not covered by any test, so the waiter command, the re-exec and the resume on the next key press are unverified. FR-18ShouldIn `exit` mode an idle remote client shall re-exec the process into a tiny waiter that resumes the session on the next key press. and NFR-10ShouldThe exit-mode waiter shall hold only a few hundred KiB of private memory while it waits, and shall resume the session in about one second. are mapped to the configuration test only. - The daemon sweep interval of 10 seconds is a constant in the source. No test asserts the interval, and the sweep test drives
reclaim_idle_cachesdirectly instead of waiting for the timer. - The daemon log line, the client log line and the memory history entries named
server_idle_hibernation_beforeandserver_idle_hibernation_afterare not asserted by a test. The sweep test checks the release counts, not the log output. - The provider cache byte count and the tool index entry count are reported by the release, but the daemon-side aggregation of those counts across the sessions of one sweep is not asserted.
- The real terminal path of the exit mode, where the daemon owns the session and the waiter resumes it, was validated manually and is described in
docs/SESSION_HIBERNATION.md, not by a test. - The
transcriptmode path that clears the remote side pane images and shrinks the display messages is not covered, only the reload flag is.
requirements
- The exit mode applies only to a remote client today, because the daemon must own the session that the waiter resumes. Should a local client be able to exit into a waiter as well?
- The daemon sweep reads the idle period from the configuration on every tick, so a configuration change takes effect within 10 seconds. Should the daemon log a notice when the period changes under it?
- The transcript mode drops local-only display messages and the exact scroll position, and reloads the history from the server on wake. Should that mode be deprecated in favour of the caches mode?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Agent Memory System
Overview
The agent memory system gives jcode a persistent, searchable memory across sessions. Memories are extracted from sessions, stored in a memory graph, embedded locally with an ONNXOpen Neural Network Exchange MiniLM model, and re-injected into prompts on later turns. A rerank and consolidation pipeline keeps recall relevant and merges memories over time. This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | The agent remembers project context across sessions and finds relevant past work without manual prompts |
| Maintainer | Low-footprint local embedding, tunable recall quality, and auditable memory behavior |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall extract memories from session content for later recall. | Must | The system shall extract memories from session content for later recall. |
| FR-2MustThe system shall compute local text embeddings for memories using a bundled ONNXOpen Neural Network Exchange MiniLM model so no external embedding API is required. | Must | The system shall compute local text embeddings for memories using a bundled ONNXOpen Neural Network Exchange MiniLM model so no external embedding API is required. |
| FR-3MustThe system shall store memories in a persistent memory graph and expose memory operations through the CLI (`jcode memory list`, `search`, `export`, `import`, `stats`). | Must | The system shall store memories in a persistent memory graph and expose memory operations through the CLI (jcode memory list, search, export, import, stats). |
| FR-4MustThe system shall support both keyword and semantic search over memories. | Must | The system shall support both keyword and semantic search over memories. |
| FR-5MustThe system shall inject relevant memories into the agent prompt on session turns. | Must | The system shall inject relevant memories into the agent prompt on session turns. |
| FR-6ShouldThe system shall rerank candidate memories (configurable cadence and votes) to keep recall precise. | Should | The system shall rerank candidate memories (configurable cadence and votes) to keep recall precise. |
| FR-7ShouldThe system shall consolidate and merge related memories over time, including overnight consolidation. | Should | The system shall consolidate and merge related memories over time, including overnight consolidation. |
| FR-8MayThe system shall expose a memory sidecar agent for autonomous memory maintenance. | May | The system shall expose a memory sidecar agent for autonomous memory maintenance. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustLocal embedding inference shall not stall the server; the embedding stack is pinned to optimized profiles. | Must | Performance | Local embedding inference shall not stall the server; the embedding stack is pinned to optimized profiles. |
| NFR-2MustMemory embeddings and extraction shall run locally without sending session content to third parties. | Must | Privacy | Memory embeddings and extraction shall run locally without sending session content to third parties. |
| NFR-3ShouldSessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. search shall scale to multi-megabyte session files (SIMD-backed matching). | Should | Performance | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. search shall scale to multi-megabyte session files (SIMD-backed matching). |
| NFR-4ShouldMemory storage must be durable across restarts. | Should | Reliability | Memory storage must be durable across restarts. |
Constraints
- Embeddings must work out of the box in default builds (the
embeddingsfeature is on by default). - A
localembedding backend is required; anopenaibackend is optional.
Acceptance Criteria
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FR-1MustThe system shall extract memories from session content for later recall.
- Given a completed session
- When memory extraction runs
- Then candidate memories are persisted to the memory store
- FR-2MustThe system shall compute local text embeddings for memories using a bundled ONNXOpen Neural Network Exchange MiniLM model so no external embedding API is required.
- Given a memory to embed
- When the local embedding backend is selected
- Then a numeric embedding is produced without any network call
- FR-3MustThe system shall store memories in a persistent memory graph and expose memory operations through the CLI (`jcode memory list`, `search`, `export`, `import`, `stats`).
- Given stored memories
- When the user runs
jcode memory listandjcode memory stats - Then the memories and their counts are shown
- FR-4MustThe system shall support both keyword and semantic search over memories.
- Given stored memories
- When the user searches by keyword or by semantic similarity
- Then relevant memories are returned in ranking order
- FR-5MustThe system shall inject relevant memories into the agent prompt on session turns.
- Given an active session
- When a turn begins
- Then relevant memories are injected into the prompt
- FR-6ShouldThe system shall rerank candidate memories (configurable cadence and votes) to keep recall precise.
- Given candidate memories for a turn
- When reranking is enabled and due
- Then the injected set is reordered by rerank score
- FR-7ShouldThe system shall consolidate and merge related memories over time, including overnight consolidation.
- Given accumulated memories
- When consolidation (including overnight) runs
- Then related memories are merged and redundant ones are removed
- FR-8MayThe system shall expose a memory sidecar agent for autonomous memory maintenance.
- Given the memory sidecar enabled
- When the sidecar agent runs
- Then it performs autonomous memory maintenance within its configured budget
- NFR-1MustLocal embedding inference shall not stall the server; the embedding stack is pinned to optimized profiles.
- Given an active server
- When embedding inference runs
- Then the agent loop does not stall waiting on the embedding model
- NFR-2MustMemory embeddings and extraction shall run locally without sending session content to third parties.
- Given memory extraction and embedding
- When observed on the network
- Then no session content leaves the machine via the memory subsystem
- NFR-3ShouldSessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. search shall scale to multi-megabyte session files (SIMD-backed matching).
- Given a large session file
- When session search runs
- Then results return quickly using SIMD-optimized matching
- NFR-4ShouldMemory storage must be durable across restarts.
- Given a server restart
- When memory commands run afterwards
- Then previously stored memories are still present
Conflicts
None identified yet.
Open Questions
- What is the exact recall budget per turn (how many memories are injected and at what token cost)? The tuning knobs exist in config but the defaults are inferred from code.
Specification: Agent Memory System
Overview
The memory system lives in crates/jcode-base/src/memory/ (activity, cache, pending) with the extraction agent and graph logic in memory.rs, memory_agent.rs, memory_graph.rs, and memory_rerank.rs. Local embeddings come from the jcode-embedding crate (tract ONNXOpen Neural Network Exchange inference of all-MiniLM-L6-v2). Recall and injection happen in the agent turn loop; consolidation runs as a background/overnight job. This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
session turns ──► memory.rs / memory_agent.rs ──► memory graph (persistent)
│ │
▼ ▼
embedding (ONNXOpen Neural Network Exchange MiniLM) memory_rerank.rs
│ │
▼ ▼
memory store ──► recall ──► prompt injection on later turns
▲
│ (overnight consolidation merges memories)
Data Models
Memory Entry
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | string | PK | Stable identifier of the memory. |
| text | string | not null | The memory content. |
| embedding | vector |
backend dependent | Local embedding for semantic recall. |
| extracted_at | timestamp | not null | When the memory was created. |
| score | float | rerank output | Rerank score used for ranking. |
SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. Search
Search over multi-megabyte session files uses memchr-based case-insensitive matching (pinned to opt-level = 3).
API Contracts
CLI: jcode memory list | search | export | import | stats
list— enumerate stored memories.search <query>— keyword and/or semantic search.export/import— serialize/deserialize the memory store.stats— counts and store health.clear-test— test-only clearing helper.
Sequences
Recall on a turn
TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). start → query memory store → keyword + semantic candidates
→ rerank (if due) → select injection set → inject into prompt → run turn
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Local ONNXOpen Neural Network Exchange embeddings | jcode-embedding with all-MiniLM-L6-v2 |
Privacy (NFR-2MustMemory embeddings and extraction shall run locally without sending session content to third parties.) and no external API dependency; feature-gated but enabled by default. |
opt-level = 3 pin for embedding stack |
tract/ndarray/tokenizers pinned | Unoptimized inference measured ~666 ms per embed; optimized keeps the agent loop responsive. |
| Memory as graph + store | memory_graph.rs plus durable store |
Supports consolidation and relationship-aware recall. |
| Rerank with cadence/votes | memory_rerank.rs |
Keeps recall precise at a tunable cost. |
Risks and Unknowns
- The exact default recall budget and rerank cadence are not documented; behavior was inferred from config and code.
- Memory extraction quality depends on the extraction agent's prompt, which may drift with model updates.
Out of Scope
- Cloud-hosted memory sync (a Jade cloud integration exists elsewhere but is not part of this subsystem).
- EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. backends beyond local ONNXOpen Neural Network Exchange and the optional OpenAI backend.
Test Plan: Agent Memory System
Scope
Covers memory extraction, embedding, storage, search, reranking, and injection. Out of scope: live provider round-trips and real-model quality evaluation (guarded behind dedicated cohorts and scripts).
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Memory store operations | crates/jcode-base/src/memory_tests.rs |
Store persists and recalls memories correctly |
| TC-2 | Memory extraction agent behavior | crates/jcode-base/src/memory_agent_tests.rs |
Agent produces valid memory candidates |
| TC-3 | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. search scoring | crates/jcode-session-types/src/session_search_tests.rs |
Results ranked correctly |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-4 | EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. numeric stability across inference engines | CIContinuous Integration minilm_embedding_is_numerically_stable_across_inference_engines cohort |
Embeddings stable across engines |
| TC-5 | Memory e2e flows | scripts/test_memory.py |
Extract/search/recall works end to end |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-6 | Empty memory store | Search returns no results without error |
| TC-7 | Very large session files | Search still responsive (SIMD path) |
Test Infrastructure
- Python script suite (
scripts/test_memory.py). - CIContinuous Integration numeric-stability cohort for embeddings.
jcode memory clear-testhelper for sandboxed runs.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall extract memories from session content for later recall. | TC-2 |
| FR-2MustThe system shall compute local text embeddings for memories using a bundled ONNXOpen Neural Network Exchange MiniLM model so no external embedding API is required. | TC-4 |
| FR-3MustThe system shall store memories in a persistent memory graph and expose memory operations through the CLI (`jcode memory list`, `search`, `export`, `import`, `stats`). | TC-1 |
| FR-4MustThe system shall support both keyword and semantic search over memories. | TC-3, TC-5 |
| NFR-2MustMemory embeddings and extraction shall run locally without sending session content to third parties. | TC-4 |
| NFR-3ShouldSessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. search shall scale to multi-megabyte session files (SIMD-backed matching). | TC-7 |
requirements
- What is the exact recall budget per turn (how many memories are injected and at what token cost)? The tuning knobs exist in config but the defaults are inferred from code.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Cloud SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. Handoff
Overview
A jcode session is a single linear transcript, so it cannot run on two machines at the same time.
jcode cloud move hands a live session to a cloud host, carrying the transcript, the todo list, the project memory, and the repository state.
jcode cloud return brings the session back and merges the cloud work into the local checkout as a 3-way merge.
A per-machine lease file decides which machine owns the session at any moment, so a stale local copy can neither run a turn nor overwrite a newer transcript.
This feature was reverse-engineered from the existing codebase during an SDLC sync, so it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Developer moving a session to a cloud host | Keep the conversation, the todos, and the uncommitted work, and keep the local files editable while the session is away |
| Developer working on the cloud host | Receive a transcript that still makes sense, and know what did not travel with it |
| Developer returning to the local machine | Get the cloud work back without losing the local edits made in the meantime |
| Operator of a shared or cloud machine | Have exactly one machine running turns for a session at a time |
| Maintainer | One ownership rule, the lease, that the CLI, the TUITerminal User Interface, and the agent all enforce the same way |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall stage the session transcript, the todo list, the project memory, and the repository state, transfer them to the target host, and verify the cloud copy before ownership changes. | Must | The system shall stage the session transcript, the todo list, the project memory, and the repository state, transfer them to the target host, and verify the cloud copy before ownership changes. |
| FR-2MustThe system shall refuse to move a session whose lease names an away host, and shall tell the operator to run `jcode cloud return` first. | Must | The system shall refuse to move a session whose lease names an away host, and shall tell the operator to run jcode cloud return first. |
| FR-3MustThe system shall refuse to move a session that is mid-turn unless `--allow-active` is passed. | Must | The system shall refuse to move a session that is mid-turn unless --allow-active is passed. |
| FR-4Must`jcode cloud move --dry-run` shall stage and verify the cloud copy without writing a lease, without changing the working tree, and without changing the index. | Must | jcode cloud move --dry-run shall stage and verify the cloud copy without writing a lease, without changing the working tree, and without changing the index. |
| FR-5MustThe system shall increment a monotonic migration epoch on every move and return, and shall stamp the shipped transcript with that epoch. | Must | The system shall increment a monotonic migration epoch on every move and return, and shall stamp the shipped transcript with that epoch. |
| FR-6MustThe system shall check before staging that the cloud host's jcode supports the move protocol, and shall name the host and the remedy when it does not. | Must | The system shall check before staging that the cloud host's jcode supports the move protocol, and shall name the host and the remedy when it does not. |
| FR-7MustThe system shall capture the repository as a git bundle plus a snapshot commit that includes the staged, unstaged, and untracked non-ignored work, without modifying the user's index or working tree. | Must | The system shall capture the repository as a git bundle plus a snapshot commit that includes the staged, unstaged, and untracked non-ignored work, without modifying the user's index or working tree. |
| FR-8MustThe system shall restore the repository on the cloud host at the same absolute path, on the same branch, with the same uncommitted work, and with the git identity when the cloud checkout has none. | Must | The system shall restore the repository on the cloud host at the same absolute path, on the same branch, with the same uncommitted work, and with the git identity when the cloud checkout has none. |
| FR-9MustThe system shall carry only allowlisted environment variables, and shall copy only allowlisted ignored files that are git-ignored and at most 256 KiB each, so that no machine-local, display, secret, or build-output state travels. | Must | The system shall carry only allowlisted environment variables, and shall copy only allowlisted ignored files that are git-ignored and at most 256 KiB each, so that no machine-local, display, secret, or build-output state travels. |
| FR-10MustThe system shall append an agent-facing migration notice to the transcript that covers the source and target hosts, the epoch, the repository path, branch, and uncommitted state, the build caches that did not travel, the toolchain hints, the local MCP servers, and the local background tasks that did not travel. | Must | The system shall append an agent-facing migration notice to the transcript that covers the source and target hosts, the epoch, the repository path, branch, and uncommitted state, the build caches that did not travel, the toolchain hints, the local MCP servers, and the local background tasks that did not travel. |
| FR-11MustThe system shall close any unanswered tool use in the last assistant message with a tool result, so that the shipped transcript stays valid for the provider. | Must | The system shall close any unanswered tool use in the last assistant message with a tool result, so that the shipped transcript stays valid for the provider. |
| FR-12MustThe system shall hand ownership to the cloud host only after the cloud copy is verified, and shall restore the previous local lease when the activation fails. | Must | The system shall hand ownership to the cloud host only after the cloud copy is verified, and shall restore the previous local lease when the activation fails. |
| FR-13MustThe system shall refuse to overwrite a cloud checkout that holds work jcode did not place there, and shall name the path in the refusal. | Must | The system shall refuse to overwrite a cloud checkout that holds work jcode did not place there, and shall name the path in the refusal. |
| FR-14Must`jcode cloud return` shall install the cloud transcript locally, replacing the local snapshot and removing the old journal. | Must | jcode cloud return shall install the cloud transcript locally, replacing the local snapshot and removing the old journal. |
| FR-15MustThe system shall merge the cloud repository work into the local checkout as a 3-way merge whose base is the snapshot both sides agreed on at move time. | Must | The system shall merge the cloud repository work into the local checkout as a 3-way merge whose base is the snapshot both sides agreed on at move time. |
| FR-16MustThe system shall report the merge outcome as no repository, unchanged, refs only, applied, or conflicts, and shall name the conflicting files. | Must | The system shall report the merge outcome as no repository, unchanged, refs only, applied, or conflicts, and shall name the conflicting files. |
| FR-17MustOn a conflict the system shall leave the local working tree untouched, shall keep the cloud work reachable at `refs/jcode-cloud/session_abc/cloud`, and shall tell the operator how to resolve it. | Must | On a conflict the system shall leave the local working tree untouched, shall keep the cloud work reachable at refs/jcode-cloud/session_abc/cloud, and shall tell the operator how to resolve it. |
| FR-18Must`jcode cloud return --refs-only` shall fetch the cloud work into refs without touching the working tree. | Must | jcode cloud return --refs-only shall fetch the cloud work into refs without touching the working tree. |
| FR-19MustThe system shall append a return notice to the transcript that names the cloud host, the local machine, the time, the merge outcome, and the fact that the cloud processes did not come back. | Must | The system shall append a return notice to the transcript that names the cloud host, the local machine, the time, the merge outcome, and the fact that the cloud processes did not come back. |
| FR-20MustThe system shall restore local ownership and bump the epoch when a session comes back. | Must | The system shall restore local ownership and bump the epoch when a session comes back. |
| FR-21MustThe system shall refuse to return a session that was never moved, and shall refuse to return a session that already lives on this machine. | Must | The system shall refuse to return a session that was never moved, and shall refuse to return a session that already lives on this machine. |
| FR-22Must`jcode cloud where` shall report, for every moved session, the session id, the location, the epoch, the repository root, and the number of commits the local checkout is ahead of the last synced head. | Must | jcode cloud where shall report, for every moved session, the session id, the location, the epoch, the repository root, and the number of commits the local checkout is ahead of the last synced head. |
| FR-23Must`jcode cloud attach` shall attach this terminal to the host that owns the session and resume the same session id there. | Must | jcode cloud attach shall attach this terminal to the host that owns the session and resume the same session id there. |
| FR-24MustThe system shall resolve the target host from `--host` or `JCODE_CLOUD_HOST`, and the remote binary from `--remote-binary` or `JCODE_CLOUD_REMOTE_BINARY`, and shall name both in the error when they are missing. | Must | The system shall resolve the target host from --host or JCODE_CLOUD_HOST, and the remote binary from --remote-binary or JCODE_CLOUD_REMOTE_BINARY, and shall name both in the error when they are missing. |
| FR-25MustThe system shall keep one lease file per session under `~/.jcode/session_leases`, named after the session id, recording the epoch, the away host, the repository root, the last agreed snapshot and head, and the update time. | Must | The system shall keep one lease file per session under ~/.jcode/session_leases, named after the session id, recording the epoch, the away host, the repository root, the last agreed snapshot and head, and the update time. |
| FR-26MustA session copy on a machine whose lease says the session moved away shall neither start a turn nor persist. | Must | A session copy on a machine whose lease says the session moved away shall neither start a turn nor persist. |
| FR-27MustA session copy whose epoch is older than the lease epoch shall neither start a turn nor persist. | Must | A session copy whose epoch is older than the lease epoch shall neither start a turn nor persist. |
| FR-28MustA session that never migrated shall run and persist normally. | Must | A session that never migrated shall run and persist normally. |
| FR-29ShouldThe TUITerminal User Interface shall offer `/cloud [host]`, `/cloud back`, `/cloud return`, `/cloud status`, and `/local`, shall run the matching CLI command between turns, and shall reattach at the new location. | Should | The TUITerminal User Interface shall offer /cloud [host], /cloud back, /cloud return, /cloud status, and /local, shall run the matching CLI command between turns, and shall reattach at the new location. |
| FR-30ShouldThe TUITerminal User Interface shall refuse a move or a return while the agent is mid-turn, and shall leave everything where it was. | Should | The TUITerminal User Interface shall refuse a move or a return while the agent is mid-turn, and shall leave everything where it was. |
| FR-31Should`jcode cloud sessions` shall upload, upload the latest, sync, list, verify, render a dashboard for, and view session transcripts through the private Jade helper, and shall pass the API token in the helper environment rather than on the command line. | Should | jcode cloud sessions shall upload, upload the latest, sync, list, verify, render a dashboard for, and view session transcripts through the private Jade helper, and shall pass the API token in the helper environment rather than on the command line. |
| FR-32Should`jcode cloud sessions configure` shall persist the Jade defaults with owner-only file permissions, `jcode cloud sessions status` shall report them without printing the token, and `--clear` shall remove the config file. | Should | jcode cloud sessions configure shall persist the Jade defaults with owner-only file permissions, jcode cloud sessions status shall report them without printing the token, and --clear shall remove the config file. |
| FR-33Should`jcode cloud sessions sync` shall skip unchanged sessions, shall honor `--since-days`, `--max`, `--min-interval-mins`, `--force`, and `--dry-run`, and shall not record sync state during a dry run. | Should | jcode cloud sessions sync shall skip unchanged sessions, shall honor --since-days, --max, --min-interval-mins, --force, and --dry-run, and shall not record sync state during a dry run. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustThe system shall not lose a transcript message across a move or a return: the cloud copy shall be verified to hold the same session id, the same epoch, and the same message count as the local copy before ownership changes. | Must | Integrity | The system shall not lose a transcript message across a move or a return: the cloud copy shall be verified to hold the same session id, the same epoch, and the same message count as the local copy before ownership changes. |
| NFR-2MustAt most one machine shall run turns for a given session at a time, enforced by the lease check before every turn, before every turn-loop iteration, and before every save. | Must | Isolation | At most one machine shall run turns for a given session at a time, enforced by the lease check before every turn, before every turn-loop iteration, and before every save. |
| NFR-3MustA return shall merge the cloud tree into the local tree with a real 3-way merge, so that edits made on either side during the migration survive, and a merge that cannot complete shall not modify the working tree. | Must | Correctness | A return shall merge the cloud tree into the local tree with a real 3-way merge, so that edits made on either side during the migration survive, and a merge that cannot complete shall not modify the working tree. |
| NFR-4MustThe lease file shall be written to a temporary file and then renamed, so that a crash during the write cannot leave a corrupt lease. | Must | Durability | The lease file shall be written to a temporary file and then renamed, so that a crash during the write cannot leave a corrupt lease. |
| NFR-5MustThe system shall not persist secrets into the lease, the manifest, or the transcript, and shall not copy machine-local or secret environment variables. | Must | Security | The system shall not persist secrets into the lease, the manifest, or the transcript, and shall not copy machine-local or secret environment variables. |
| NFR-6MustA session id used as a lease file name shall be restricted to ASCII alphanumerics, underscore, dash, and dot, and shall not start with a dot, so that a session id cannot escape the lease directory. | Must | Security | A session id used as a lease file name shall be restricted to ASCII alphanumerics, underscore, dash, and dot, and shall not start with a dot, so that a session id cannot escape the lease directory. |
| NFR-7MustA failed move shall leave the local session usable: the previous lease shall be restored, the local transcript shall be untouched, and the failure shall name the stage that failed. | Must | Operability | A failed move shall leave the local session usable: the previous lease shall be restored, the local transcript shall be untouched, and the failure shall name the stage that failed. |
| NFR-8ShouldThe transfer size shall stay proportional to the tracked source, because build output, dependency trees, and other ignored directories are never copied. | Should | Performance | The transfer size shall stay proportional to the tracked source, because build output, dependency trees, and other ignored directories are never copied. |
| NFR-9ShouldA cloud host whose jcode predates the move protocol shall be detected before any state changes, and the error shall name the host. | Should | Compatibility | A cloud host whose jcode predates the move protocol shall be detected before any state changes, and the error shall name the host. |
| NFR-10ShouldThe transfer format shall carry a version number, and a host that does not support the incoming format shall refuse the move and name the version it expects. | Should | Compatibility | The transfer format shall carry a version number, and a host that does not support the incoming format shall refuse the move and name the version it expects. |
| NFR-11ShouldThe move and the return shall emit one progress line per stage, and shall emit none when `JCODE_CLOUD_QUIET` is set. | Should | Observability | The move and the return shall emit one progress line per stage, and shall emit none when JCODE_CLOUD_QUIET is set. |
| NFR-12ShouldThe `where` report shall show how far the local checkout has diverged from the last synchronized head, so the operator can tell whether local work is pending. | Should | Operability | The where report shall show how far the local checkout has diverged from the last synchronized head, so the operator can tell whether local work is pending. |
Constraints
- The transfer runs over SSH to the target host, so the target host must be reachable with key-based authentication in batch mode.
- The repository is restored at the same absolute path on the cloud host, because every path in the transcript must stay valid.
- The cloud host must run a jcode that understands the
cloud receive,cloud activate, andcloud exportsubcommands. - The transfer format version is currently 1, and the manifest carries it in every transfer.
- The lease lives on local disk under the jcode home, so a machine that loses its jcode home loses its proof of ownership.
- The
jcode cloud sessionshalf talks to a private Jade helper that lives outside this repository. - The managed AWS control plane described in
docs/JCODE_CLOUD_AWS.mdis a design document and is not part of this feature.
Acceptance Criteria
Every FR and NFR shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
-
FR-1MustThe system shall stage the session transcript, the todo list, the project memory, and the repository state, transfer them to the target host, and verify the cloud copy before ownership changes.
gherkin @FR-1MustThe system shall stage the session transcript, the todo list, the project memory, and the repository state, transfer them to the target host, and verify the cloud copy before ownership changes. Scenario: Move a live session to a cloud host Given a local session with a transcript, todos, and a git checkout When the operator runs `jcode cloud move --session session_abc --host cloud-e2e` Then the cloud host holds the transcript, the todos, and the repository state And the move reports the cloud host, the epoch, and the snapshot commit -
FR-2MustThe system shall refuse to move a session whose lease names an away host, and shall tell the operator to run `jcode cloud return` first.
gherkin @FR-2MustThe system shall refuse to move a session whose lease names an away host, and shall tell the operator to run `jcode cloud return` first. Scenario: Refuse to move a session that already lives elsewhere Given a session whose lease names an away host When the operator runs `jcode cloud move` Then the move fails and names the away host And the message tells the operator to run `jcode cloud return` first -
FR-3MustThe system shall refuse to move a session that is mid-turn unless `--allow-active` is passed.
gherkin @FR-3MustThe system shall refuse to move a session that is mid-turn unless `--allow-active` is passed. Scenario: Refuse to move a session that is mid-turn Given a session with a turn in flight When the operator runs `jcode cloud move` Then the move fails and says the session is mid-turn And the move proceeds when `--allow-active` is passed -
FR-4Must`jcode cloud move --dry-run` shall stage and verify the cloud copy without writing a lease, without changing the working tree, and without changing the index.
gherkin @FR-4Must`jcode cloud move --dry-run` shall stage and verify the cloud copy without writing a lease, without changing the working tree, and without changing the index. Scenario: A dry run leaves the local session alone Given a local session and a reachable cloud host When the operator runs `jcode cloud move --dry-run` Then the cloud copy is staged and verified And no lease file is written locally And the local working tree and the local index are unchanged -
FR-5MustThe system shall increment a monotonic migration epoch on every move and return, and shall stamp the shipped transcript with that epoch.
gherkin @FR-5MustThe system shall increment a monotonic migration epoch on every move and return, and shall stamp the shipped transcript with that epoch. Scenario: The epoch increments on every move Given a session that has never moved When the session is moved to a cloud host Then the shipped transcript carries migration epoch 1 And the next move of the same session ships epoch 2 -
FR-6MustThe system shall check before staging that the cloud host's jcode supports the move protocol, and shall name the host and the remedy when it does not.
gherkin @FR-6MustThe system shall check before staging that the cloud host's jcode supports the move protocol, and shall name the host and the remedy when it does not. Scenario: The cloud host does not speak the move protocol Given a cloud host whose jcode does not know the `cloud receive` subcommand When the operator runs `jcode cloud move` Then the move fails before any state changes And the error names the host and points at `--remote-binary` or `JCODE_CLOUD_REMOTE_BINARY` -
FR-7MustThe system shall capture the repository as a git bundle plus a snapshot commit that includes the staged, unstaged, and untracked non-ignored work, without modifying the user's index or working tree.
gherkin @FR-7MustThe system shall capture the repository as a git bundle plus a snapshot commit that includes the staged, unstaged, and untracked non-ignored work, without modifying the user's index or working tree. Scenario: The snapshot captures the whole working tree Given a checkout with a committed change, a staged file, an untracked file, and an ignored file When the session is moved Then the snapshot commit holds the committed, staged, and untracked work And the ignored file is not in the snapshot And the local index and the local working tree are unchanged -
FR-8MustThe system shall restore the repository on the cloud host at the same absolute path, on the same branch, with the same uncommitted work, and with the git identity when the cloud checkout has none.
gherkin @FR-8MustThe system shall restore the repository on the cloud host at the same absolute path, on the same branch, with the same uncommitted work, and with the git identity when the cloud checkout has none. Scenario: The cloud checkout matches the local one Given a session moved from a checkout at `/work/repo` on branch `main` When the cloud host stages the move Then the repository exists at `/work/repo` on branch `main` And the uncommitted and untracked work is present And the git identity is set when the cloud checkout has none -
FR-9MustThe system shall carry only allowlisted environment variables, and shall copy only allowlisted ignored files that are git-ignored and at most 256 KiB each, so that no machine-local, display, secret, or build-output state travels.
gherkin @FR-9MustThe system shall carry only allowlisted environment variables, and shall copy only allowlisted ignored files that are git-ignored and at most 256 KiB each, so that no machine-local, display, secret, or build-output state travels. Scenario: Only allowlisted environment and ignored files travel Given a local machine with `EDITOR` set, `DISPLAY` set, and a git-ignored `.env` file When the session is moved Then the manifest carries `EDITOR` and does not carry `DISPLAY` And the `.env` file is copied to the cloud host And no build output is copied -
FR-10MustThe system shall append an agent-facing migration notice to the transcript that covers the source and target hosts, the epoch, the repository path, branch, and uncommitted state, the build caches that did not travel, the toolchain hints, the local MCP servers, and the local background tasks that did not travel.
gherkin @FR-10MustThe system shall append an agent-facing migration notice to the transcript that covers the source and target hosts, the epoch, the repository path, branch, and uncommitted state, the build caches that did not travel, the toolchain hints, the local MCP servers, and the local background tasks that did not travel. Scenario: The transcript explains where the session now runs Given a session that is moved to a cloud host When the cloud host installs the transcript Then the transcript ends with a notice naming the source host, the target host, and the epoch And the notice states the repository path, the branch, and the uncommitted state And the notice names the build caches, the local MCP servers, and the background tasks that did not travel -
FR-11MustThe system shall close any unanswered tool use in the last assistant message with a tool result, so that the shipped transcript stays valid for the provider.
gherkin @FR-11MustThe system shall close any unanswered tool use in the last assistant message with a tool result, so that the shipped transcript stays valid for the provider. Scenario: The interrupted tool call is closed Given a transcript whose last assistant message has an unanswered tool use When the session is moved Then the shipped transcript carries a tool result for that tool use And the tool result says the call was interrupted by the move -
FR-12MustThe system shall hand ownership to the cloud host only after the cloud copy is verified, and shall restore the previous local lease when the activation fails.
gherkin @FR-12MustThe system shall hand ownership to the cloud host only after the cloud copy is verified, and shall restore the previous local lease when the activation fails. Scenario: Ownership moves only after the cloud copy is verified Given a cloud host that stages the move but fails to activate When the operator runs `jcode cloud move` Then the move fails and the local lease is left as it was And the local session stays usable -
FR-13MustThe system shall refuse to overwrite a cloud checkout that holds work jcode did not place there, and shall name the path in the refusal.
gherkin @FR-13MustThe system shall refuse to overwrite a cloud checkout that holds work jcode did not place there, and shall name the path in the refusal. Scenario: The cloud checkout holds unrelated work Given a cloud checkout whose files match neither the snapshot jcode placed nor its HEAD When a move arrives for that path Then the receive is refused with a message that names the path And the existing files are left alone -
FR-14Must`jcode cloud return` shall install the cloud transcript locally, replacing the local snapshot and removing the old journal.
gherkin @FR-14Must`jcode cloud return` shall install the cloud transcript locally, replacing the local snapshot and removing the old journal. Scenario: Return installs the cloud transcript locally Given a session that lives on a cloud host When the operator runs `jcode cloud return` Then the local transcript is the cloud transcript And the local journal file is gone -
FR-15MustThe system shall merge the cloud repository work into the local checkout as a 3-way merge whose base is the snapshot both sides agreed on at move time.
gherkin @FR-15MustThe system shall merge the cloud repository work into the local checkout as a 3-way merge whose base is the snapshot both sides agreed on at move time. Scenario: Both sides keep their edits Given a local edit and a cloud edit to different parts of the same file When the operator runs `jcode cloud return` Then the merged file holds both the local edit and the cloud edit -
FR-16MustThe system shall report the merge outcome as no repository, unchanged, refs only, applied, or conflicts, and shall name the conflicting files.
gherkin @FR-16MustThe system shall report the merge outcome as no repository, unchanged, refs only, applied, or conflicts, and shall name the conflicting files. Scenario: The merge outcome is reported Given a session that is returned When the return finishes Then the report names one of no repository, unchanged, refs only, applied, or conflicts And a conflicts outcome names the conflicting files -
FR-17MustOn a conflict the system shall leave the local working tree untouched, shall keep the cloud work reachable at `refs/jcode-cloud/session_abc/cloud`, and shall tell the operator how to resolve it.
gherkin @FR-17MustOn a conflict the system shall leave the local working tree untouched, shall keep the cloud work reachable at `refs/jcode-cloud/session_abc/cloud`, and shall tell the operator how to resolve it. Scenario: A conflicting return keeps the working tree intact Given a local edit and a cloud edit to the same lines When the operator runs `jcode cloud return` Then the local file content is unchanged And the cloud work is reachable at `refs/jcode-cloud/session_abc/cloud` And the transcript tells the operator how to resolve the conflict -
FR-18Must`jcode cloud return --refs-only` shall fetch the cloud work into refs without touching the working tree.
gherkin @FR-18Must`jcode cloud return --refs-only` shall fetch the cloud work into refs without touching the working tree. Scenario: A refs-only return does not touch the working tree Given a session that lives on a cloud host When the operator runs `jcode cloud return --refs-only` Then the cloud work is fetched into `refs/jcode-cloud/session_abc/cloud` And the local working tree is unchanged -
FR-19MustThe system shall append a return notice to the transcript that names the cloud host, the local machine, the time, the merge outcome, and the fact that the cloud processes did not come back.
gherkin @FR-19MustThe system shall append a return notice to the transcript that names the cloud host, the local machine, the time, the merge outcome, and the fact that the cloud processes did not come back. Scenario: The transcript explains the return Given a session that is returned from a cloud host When the local transcript is installed Then the transcript ends with a notice naming the cloud host, the local machine, and the time And the notice states the merge outcome And the notice states that the cloud processes did not come back -
FR-20MustThe system shall restore local ownership and bump the epoch when a session comes back.
gherkin @FR-20MustThe system shall restore local ownership and bump the epoch when a session comes back. Scenario: The local machine owns the session again Given a session that lives on a cloud host When the operator runs `jcode cloud return` Then the local lease names no away host And the epoch is one higher than it was before the move -
FR-21MustThe system shall refuse to return a session that was never moved, and shall refuse to return a session that already lives on this machine.
gherkin @FR-21MustThe system shall refuse to return a session that was never moved, and shall refuse to return a session that already lives on this machine. Scenario: Refuse to return a session that never moved Given a session with no lease file When the operator runs `jcode cloud return` Then the return fails and says the session was never moved -
FR-22Must`jcode cloud where` shall report, for every moved session, the session id, the location, the epoch, the repository root, and the number of commits the local checkout is ahead of the last synced head.
gherkin @FR-22Must`jcode cloud where` shall report, for every moved session, the session id, the location, the epoch, the repository root, and the number of commits the local checkout is ahead of the last synced head. Scenario: Where reports the location of a moved session Given a session that lives on a cloud host When the operator runs `jcode cloud where` Then the report names the session id, the location, the epoch, and the repository root And the report says how many commits the local checkout is ahead of the last synced head -
FR-23Must`jcode cloud attach` shall attach this terminal to the host that owns the session and resume the same session id there.
gherkin @FR-23Must`jcode cloud attach` shall attach this terminal to the host that owns the session and resume the same session id there. Scenario: Attach resumes the session on the owning host Given a session that lives on a cloud host When the operator runs `jcode cloud attach` Then this terminal is replaced by a client that resumes the same session id on the owning host -
FR-24MustThe system shall resolve the target host from `--host` or `JCODE_CLOUD_HOST`, and the remote binary from `--remote-binary` or `JCODE_CLOUD_REMOTE_BINARY`, and shall name both in the error when they are missing.
gherkin @FR-24MustThe system shall resolve the target host from `--host` or `JCODE_CLOUD_HOST`, and the remote binary from `--remote-binary` or `JCODE_CLOUD_REMOTE_BINARY`, and shall name both in the error when they are missing. Scenario: The target host is resolved from a flag or the environment Given no `--host` flag When the environment variable `JCODE_CLOUD_HOST` is set Then the move targets that host And with neither the flag nor the variable the move fails with a message that names both -
FR-25MustThe system shall keep one lease file per session under `~/.jcode/session_leases`, named after the session id, recording the epoch, the away host, the repository root, the last agreed snapshot and head, and the update time.
gherkin @FR-25MustThe system shall keep one lease file per session under `~/.jcode/session_leases`, named after the session id, recording the epoch, the away host, the repository root, the last agreed snapshot and head, and the update time. Scenario: The lease records the ownership state Given a session that was moved to a cloud host When the local lease file is read Then it holds the epoch, the away host, the repository root, the last synced snapshot and head, and the update time -
FR-26MustA session copy on a machine whose lease says the session moved away shall neither start a turn nor persist.
gherkin @FR-26MustA session copy on a machine whose lease says the session moved away shall neither start a turn nor persist. Scenario: The old machine cannot run the session after a move Given a session that was moved to a cloud host When an agent on the old machine tries to run a turn Then the turn is refused with a message that names the new host -
FR-27MustA session copy whose epoch is older than the lease epoch shall neither start a turn nor persist.
gherkin @FR-27MustA session copy whose epoch is older than the lease epoch shall neither start a turn nor persist. Scenario: A stale copy cannot overwrite a returned transcript Given a session that was returned with a higher epoch When an in-memory copy at the old epoch tries to save Then the save is skipped and the on-disk transcript is unchanged -
FR-28MustA session that never migrated shall run and persist normally.
gherkin @FR-28MustA session that never migrated shall run and persist normally. Scenario: A session that never migrated is unaffected Given a session with no lease file When the agent runs a turn and saves Then the turn runs and the transcript is written -
FR-29ShouldThe TUITerminal User Interface shall offer `/cloud [host]`, `/cloud back`, `/cloud return`, `/cloud status`, and `/local`, shall run the matching CLI command between turns, and shall reattach at the new location.
gherkin @FR-29ShouldThe TUITerminal User Interface shall offer `/cloud [host]`, `/cloud back`, `/cloud return`, `/cloud status`, and `/local`, shall run the matching CLI command between turns, and shall reattach at the new location. Scenario: The TUITerminal User Interface moves and returns the session Given an idle agent in the TUITerminal User Interface When the operator types `/cloud cloud-e2e` Then the session is moved and the terminal reattaches on the cloud host And when the operator types `/local` the session comes back and the terminal resumes it locally -
FR-30ShouldThe TUITerminal User Interface shall refuse a move or a return while the agent is mid-turn, and shall leave everything where it was.
gherkin @FR-30ShouldThe TUITerminal User Interface shall refuse a move or a return while the agent is mid-turn, and shall leave everything where it was. Scenario: The TUITerminal User Interface refuses a move during a turn Given an agent that is mid-turn in the TUITerminal User Interface When the operator types `/cloud` Then the TUITerminal User Interface reports that the move happens between turns And nothing moves -
FR-31Should`jcode cloud sessions` shall upload, upload the latest, sync, list, verify, render a dashboard for, and view session transcripts through the private Jade helper, and shall pass the API token in the helper environment rather than on the command line.
gherkin @FR-31Should`jcode cloud sessions` shall upload, upload the latest, sync, list, verify, render a dashboard for, and view session transcripts through the private Jade helper, and shall pass the API token in the helper environment rather than on the command line. Scenario: Uploading a session to Jade cloud storage Given a configured Jade helper When the operator runs `jcode cloud sessions upload session_abc.json` Then the helper is invoked with the session file And the API token is passed in the helper environment rather than on the command line -
FR-32Should`jcode cloud sessions configure` shall persist the Jade defaults with owner-only file permissions, `jcode cloud sessions status` shall report them without printing the token, and `--clear` shall remove the config file.
gherkin @FR-32Should`jcode cloud sessions configure` shall persist the Jade defaults with owner-only file permissions, `jcode cloud sessions status` shall report them without printing the token, and `--clear` shall remove the config file. Scenario: Configuring the Jade defaults Given an empty Jade config When the operator runs `jcode cloud sessions configure --api-base https://jade.example --api-token-env JADE_TOKEN` Then the config file is written with owner-only permissions And `jcode cloud sessions status` reports the base URL and that a token is configured, without printing the token And `jcode cloud sessions configure --clear` removes the file -
FR-33Should`jcode cloud sessions sync` shall skip unchanged sessions, shall honor `--since-days`, `--max`, `--min-interval-mins`, `--force`, and `--dry-run`, and shall not record sync state during a dry run.
gherkin @FR-33Should`jcode cloud sessions sync` shall skip unchanged sessions, shall honor `--since-days`, `--max`, `--min-interval-mins`, `--force`, and `--dry-run`, and shall not record sync state during a dry run. Scenario: Syncing is idempotent and throttled Given sessions that were already uploaded When the operator runs `jcode cloud sessions sync --all` Then the unchanged sessions are skipped And a run with `--min-interval-mins` inside the interval is skipped And a dry run reports the plan without uploading and without writing sync state -
NFR-1MustThe system shall not lose a transcript message across a move or a return: the cloud copy shall be verified to hold the same session id, the same epoch, and the same message count as the local copy before ownership changes.
gherkin @NFR-1MustThe system shall not lose a transcript message across a move or a return: the cloud copy shall be verified to hold the same session id, the same epoch, and the same message count as the local copy before ownership changes. Scenario: No transcript message is lost across a move Given a local session with 42 messages When the session is moved to a cloud host Then the cloud report states 42 messages and the same session id and epoch And the move is abandoned before ownership changes when the count differs -
NFR-2MustAt most one machine shall run turns for a given session at a time, enforced by the lease check before every turn, before every turn-loop iteration, and before every save.
gherkin @NFR-2MustAt most one machine shall run turns for a given session at a time, enforced by the lease check before every turn, before every turn-loop iteration, and before every save. Scenario: One machine runs the session Given a session that was moved to a cloud host When a turn is requested on the old machine and on the cloud host Then the request on the old machine is refused And the request on the cloud host runs -
NFR-3MustA return shall merge the cloud tree into the local tree with a real 3-way merge, so that edits made on either side during the migration survive, and a merge that cannot complete shall not modify the working tree.
gherkin @NFR-3MustA return shall merge the cloud tree into the local tree with a real 3-way merge, so that edits made on either side during the migration survive, and a merge that cannot complete shall not modify the working tree. Scenario: A merge that cannot complete leaves the tree alone Given a local edit and a cloud edit to the same lines When the operator runs `jcode cloud return` Then no conflict markers are written into the local files And the local file content is byte for byte what it was before the return -
NFR-4MustThe lease file shall be written to a temporary file and then renamed, so that a crash during the write cannot leave a corrupt lease.
gherkin @NFR-4MustThe lease file shall be written to a temporary file and then renamed, so that a crash during the write cannot leave a corrupt lease. Scenario: The lease is written atomically Given a session that is moved to a cloud host When the lease is written Then the lease file is created by renaming a temporary file into place And a reader never sees a partially written lease -
NFR-5MustThe system shall not persist secrets into the lease, the manifest, or the transcript, and shall not copy machine-local or secret environment variables.
gherkin @NFR-5MustThe system shall not persist secrets into the lease, the manifest, or the transcript, and shall not copy machine-local or secret environment variables. Scenario: Secrets stay out of the moved state Given a local machine with a secret in its environment and a git-ignored `.env` file When the session is moved Then the manifest, the lease, and the transcript contain no environment secret And only the allowlisted environment variables are recorded -
NFR-6MustA session id used as a lease file name shall be restricted to ASCII alphanumerics, underscore, dash, and dot, and shall not start with a dot, so that a session id cannot escape the lease directory.
gherkin @NFR-6MustA session id used as a lease file name shall be restricted to ASCII alphanumerics, underscore, dash, and dot, and shall not start with a dot, so that a session id cannot escape the lease directory. Scenario: A hostile session id cannot escape the lease directory Given a session id of `../escape` When the lease is written Then the write fails with an invalid session id error And no file is created outside the lease directory -
NFR-7MustA failed move shall leave the local session usable: the previous lease shall be restored, the local transcript shall be untouched, and the failure shall name the stage that failed.
gherkin @NFR-7MustA failed move shall leave the local session usable: the previous lease shall be restored, the local transcript shall be untouched, and the failure shall name the stage that failed. Scenario: A failed move leaves the session local Given a cloud host that cannot be reached When the operator runs `jcode cloud move` Then the move fails and names the stage that failed And the local transcript and the local lease are unchanged And the session can still run a turn on this machine -
NFR-8ShouldThe transfer size shall stay proportional to the tracked source, because build output, dependency trees, and other ignored directories are never copied.
gherkin @NFR-8ShouldThe transfer size shall stay proportional to the tracked source, because build output, dependency trees, and other ignored directories are never copied. Scenario: The transfer skips build output Given a checkout with a large ignored build directory When the session is moved Then the transfer does not contain the build directory And the transfer size grows with the tracked source rather than with the build output -
NFR-9ShouldA cloud host whose jcode predates the move protocol shall be detected before any state changes, and the error shall name the host.
gherkin @NFR-9ShouldA cloud host whose jcode predates the move protocol shall be detected before any state changes, and the error shall name the host. Scenario: An old cloud host is detected early Given a cloud host whose jcode predates the move protocol When the operator runs `jcode cloud move` Then the failure happens before any local or remote state changes And the error names the host -
NFR-10ShouldThe transfer format shall carry a version number, and a host that does not support the incoming format shall refuse the move and name the version it expects.
gherkin @NFR-10ShouldThe transfer format shall carry a version number, and a host that does not support the incoming format shall refuse the move and name the version it expects. Scenario: An unsupported transfer format is refused Given a move package whose format version is not the one the host supports When the cloud host receives it Then the receive is refused and the expected format version is named -
NFR-11ShouldThe move and the return shall emit one progress line per stage, and shall emit none when `JCODE_CLOUD_QUIET` is set.
gherkin @NFR-11ShouldThe move and the return shall emit one progress line per stage, and shall emit none when `JCODE_CLOUD_QUIET` is set. Scenario: The stages are visible unless quiet mode is on Given a move that runs to completion When the move prints its progress Then one line is printed for the prepare, transfer, verify, and commit stages And with `JCODE_CLOUD_QUIET` set no progress line is printed -
NFR-12ShouldThe `where` report shall show how far the local checkout has diverged from the last synchronized head, so the operator can tell whether local work is pending.
gherkin @NFR-12ShouldThe `where` report shall show how far the local checkout has diverged from the last synchronized head, so the operator can tell whether local work is pending. Scenario: The divergence of the local checkout is visible Given a local checkout that is three commits ahead of the last synced head When the operator runs `jcode cloud where` Then the report says the local checkout is three commits ahead
Conflicts
None identified yet.
Open Questions
- Should the cloud host lease the session for a fixed period, so that a host that dies mid-session releases the session automatically?
Today the operator runs
jcode cloud returnby hand. - Should the ignored-file allowlist be configurable, and should the operator be warned that
.envfiles are copied to the cloud host? Today the allowlist is a fixed constant insrc/cli/cloud_move.rs. - Should a mid-turn move wait for the turn to finish instead of requiring
--allow-active? Today the agent itself passes--allow-activewhen the operator types/cloudfrom inside a turn. - Should the managed AWS control plane in
docs/JCODE_CLOUD_AWS.mdreplace the SSH transport for the move and return path? The document is a design direction and the control plane is not deployed.
Specification: Cloud SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. Handoff
Overview
The handoff lives in src/cli/cloud_move.rs, in the root crate.
It implements a staged transfer of a live session between two machines: run_move prepares a package on the local side, transfers it over the remote transport, verifies what the far side received, and only then hands ownership over, and run_return reverses the flow and merges the cloud work back into the local checkout.
The remote half of the protocol is three hidden subcommands of the same binary, cloud receive, cloud activate, and cloud export, so the far side needs nothing but a jcode binary.
Ownership is decided by a per-machine lease file in crates/jcode-storage/src/session_lease.rs, which carries a monotonic migration epoch, and the agent consults that lease before every turn and before every save.
The TUITerminal User Interface surface is crates/jcode-tui/src/tui/app/commands_cloud.rs, which runs the same CLI commands between turns and then reattaches at the new location.
A separate half of the jcode cloud surface, jcode cloud sessions, uploads session transcripts to Jade cloud storage through a private helper and shares no state with the move protocol.
This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
local machine (laptop) cloud host
+--------------------------------+ +-------------------------------+
| jcode cloud move | | jcode cloud receive (hidden) |
| src/cli/cloud_move.rs | | jcode cloud activate (hidden) |
| run_move() | | jcode cloud export (hidden) |
| | | |
| prepare | | receive |
| load session transcript | | read move.tar from stdin |
| snapshot_repo() -> bundle | | restore_repo() same path |
| build MoveManifest | | stage in cloud_inbox |
| tar -> move.tar | | |
| | | activate |
| transfer | | install transcript + todos |
| ssh host jcode cloud receive | ------> | write lease, away_host=none |
| | | |
| verify | | export |
| id, epoch, messages, snapshot| | stop owning here |
| | | snapshot_repo() -> bundle |
| commit | <------ | stream return.tar on stdout |
| write lease, away_host=host | | |
| ssh host jcode cloud activate| | |
| git update-ref .../base | | |
+--------------------------------+ +-------------------------------+
| |
v v
~/.jcode/session_leases/session_abc.json ~/.jcode/session_leases/session_abc.json
local lease: epoch, away_host = host, cloud lease: epoch, away_host = none
repo_root, last_sync_snapshot, last_sync_head
The lease is the only shared state between the two machines, and each machine keeps its own copy of it. The epoch in the lease is the tie-breaker: it is bumped on every move and every return, and each transcript carries the epoch of the migration that delivered it. A copy may run turns and persist only when the lease says the session lives here and the copy is at least as new as the lease.
The repository travels as a git bundle plus a snapshot commit, and the merge back is a plain git 3-way merge. Four refs carry the moved state in the local repository:
| Ref | Meaning |
|---|---|
refs/jcode-cloud/session_abc/base |
The snapshot both sides agreed on at move time. This is the merge base for the return. |
refs/jcode-cloud/session_abc/outgoing |
The snapshot commit taken on the sending side. |
refs/jcode-cloud/session_abc/cloud |
The cloud snapshot fetched back into the local repository. |
refs/jcode-cloud/session_abc/cloud-head |
The branch head the cloud side had, when the cloud side committed. |
The agent side of the lease lives in three places, and all three consult the same helper:
crates/jcode-app-core/src/agent/turn_execution.rscallsensure_session_leasebefore a turn starts.crates/jcode-app-core/src/agent/turn_loops.rsandcrates/jcode-app-core/src/agent/turn_streaming_mpsc.rsre-check the lease on every loop iteration, so a move that happens during a long turn stops the loop.crates/jcode-base/src/session/persistence.rsrefuses to write a session whose copy is blocked, so a stale in-memory copy cannot overwrite a newer transcript.
Data Models
SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. lease (jcode_storage::SessionLease)
Persisted at ~/.jcode/session_leases/session_abc.json.
| Field | Type | Constraints | Description |
|---|---|---|---|
| session_id | string | PK, not null, restricted character set | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. the lease belongs to. |
| epoch | u64 | not null, monotonic | Migration counter shared by both machines. |
| away_host | string | optional, omitted when absent | None when the session lives on this machine, otherwise the host that owns it. |
| repo_root | string | optional | Absolute repository root the session works in. |
| last_sync_snapshot | string | optional | Snapshot commit both machines last agreed on, used as the merge base. |
| last_sync_head | string | optional | Branch HEAD both machines last agreed on. |
| updated_at | string | not null, RFC 3339 | Time of the last lease write. |
The session id is validated before it becomes a file name: it must be non-empty, may hold only ASCII alphanumerics, underscore, dash, and dot, and must not start with a dot.
The lease is written to a .json.tmp file and then renamed into place, so a crash cannot leave a corrupt lease.
A missing lease file means the session never migrated and is not blocked.
Lease block (jcode_storage::SessionLeaseBlock)
The reason a session copy may not run a turn or persist on this machine.
| Variant | Fields | Meaning |
|---|---|---|
| MovedAway | host, epoch | The lease says the session lives on another host. |
| StaleCopy | copy_epoch, lease_epoch | This in-memory copy is older than the lease. |
Move manifest (cloud_move::MoveManifest)
The header of the transfer package, written as manifest.json inside the tarball.
| Field | Type | Constraints | Description |
|---|---|---|---|
| format_version | u32 | not null, currently 1 | Version of the transfer format. |
| session_id | string | not null | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. the package carries. |
| epoch | u64 | not null | Migration epoch of this move. |
| source_host | string | not null | Label of the sending machine. |
| target_host | string | not null | Host alias of the receiving machine. |
| created_at | string | not null, RFC 3339 | Time the package was built. |
| repo | RepoManifest | optional | Repository state, absent when the session has no git checkout. |
| env | list of (string, string) | not null | Allowlisted environment variables present on the sender. |
| toolchain_hints | list of string | not null | Toolchains the repository implies, for example rust (rust-toolchain.toml). |
| not_transferred | list of string | not null | Local background tasks that were running and did not travel. |
| mcp_servers | list of string | not null | Locally configured MCP server names that are not connected on the far side. |
Repository manifest (cloud_move::RepoManifest)
| Field | Type | Constraints | Description |
|---|---|---|---|
| root | string | not null | Absolute repository root, restored at the same path so transcript paths stay valid. |
| working_dir | string | not null | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. working directory, possibly a subdirectory of root. |
| branch | string | optional | Checked-out branch, absent when the head is detached. |
| head | string | not null | Commit the branch pointed at. |
| snapshot | string | not null | Snapshot commit holding the full working tree state. |
| dirty | bool | not null | Whether the snapshot differs from the HEAD tree. |
| origin_url | string | optional | origin remote URL. |
| git_user_name | string | optional | Repository user.name. |
| git_user_email | string | optional | Repository user.email. |
| ignored_files | list of string | not null | Allowlisted ignored files that were copied. |
Receive report (cloud_move::ReceiveReport)
The JSON the cloud host prints after staging a move, and the document the sender verifies against.
| Field | Type | Constraints | Description |
|---|---|---|---|
| session_id | string | not null | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. that was staged. |
| epoch | u64 | not null | Epoch of the staged move. |
| messages | number | not null | MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. count in the staged transcript. |
| snapshot | string | optional | Snapshot commit created on the cloud host. |
| repo_root | string | optional | Repository root restored on the cloud host. |
Move report (cloud_move::MoveReport)
The JSON jcode cloud move prints.
| Field | Type | Constraints | Description |
|---|---|---|---|
| session_id | string | not null | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. that was moved. |
| host | string | not null | Host that now owns the session. |
| epoch | u64 | not null | Epoch of this move. |
| repo_root | string | optional | Repository root on the cloud host. |
| snapshot | string | optional | Snapshot commit that was transferred. |
| dry_run | bool | not null | Whether this was a dry run. |
| attach_command | string | not null | Suggested jcode cloud attach command. |
| return_command | string | not null | Suggested jcode cloud return command. |
Return report (cloud_move::ReturnReport)
| Field | Type | Constraints | Description |
|---|---|---|---|
| session_id | string | not null | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. that came back. |
| host | string | not null | Host the session came from. |
| epoch | u64 | not null | Epoch of the return. |
| messages | number | not null | MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. count in the returned transcript. |
| merge | MergeOutcome | not null | Outcome of the repository merge. |
Merge outcome (cloud_move::MergeOutcome)
Serialized as an object with a result tag.
| Result | Fields | Meaning |
|---|---|---|
| no_repo | none | The session had no repository, so there was nothing to merge. |
| unchanged | none | The cloud snapshot equals the snapshot both sides agreed on. |
| refs_only | cloud_snapshot | The cloud work was fetched into refs and the working tree was not touched. |
| applied | cloud_snapshot, branch, head | The cloud work was merged into the local checkout. |
| conflicts | cloud_snapshot, files | The merge conflicted, the working tree was left untouched, and the conflicting files are named. |
Where entry (cloud_move::WhereEntry)
| Field | Type | Constraints | Description |
|---|---|---|---|
| session_id | string | not null | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. the entry describes. |
| location | string | not null | local, or the host that owns the session. |
| epoch | u64 | not null | Epoch the lease records. |
| repo_root | string | optional | Repository root. |
| local_ahead_of_sync | number | optional | Commits the local HEAD is ahead of the last synced head. |
API Contracts
The handoff is a command-line protocol, not an HTTP API, so there is no OpenAPI document for it.
The normative contract is this section, and the jcode cloud argument definitions in src/cli/args.rs and src/cli/args/cloud_sessions.rs are the machine-readable form of it.
Move and return surface
| Command | Purpose |
|---|---|
jcode cloud move --session session_abc --host cloud-e2e |
Hand the session to the cloud host, and report the new host, the epoch, and the snapshot. |
jcode cloud move --dry-run |
Stage and verify the cloud copy without changing ownership. |
jcode cloud move --allow-active |
Allow the move while a turn is in flight. |
jcode cloud move --attach |
Attach this terminal to the cloud session after a successful move. |
jcode cloud move --json |
Print the move report as JSON. |
jcode cloud return --session session_abc |
Bring the session back and merge the cloud work into the local checkout. |
jcode cloud return --refs-only |
Fetch the cloud work into refs without touching the working tree. |
jcode cloud return --attach |
Resume the session locally after the return. |
jcode cloud return --json |
Print the return report as JSON. |
jcode cloud where [--session session_abc] |
Report where the moved sessions live and how far the local checkouts have diverged. |
jcode cloud attach [--session session_abc] |
Attach this terminal to the host that owns the session. |
Remote surface, hidden from the help output
| Command | Purpose |
|---|---|
jcode cloud receive --json |
Read a move package from stdin, restore the repository, stage the package, and print the receive report. |
jcode cloud activate --session session_abc --epoch 1 |
Take ownership of a staged package by installing the transcript, the todos, and the memory, and by writing the local lease. |
jcode cloud export --session session_abc --epoch 2 |
Stop owning the session here, snapshot the repository, and stream the return package on stdout. |
Jade cloud sessions surface
| Command | Purpose |
|---|---|
jcode cloud sessions configure |
Save the Jade API base URL, the bearer token, the token id, the user id, and the helper path. |
jcode cloud sessions status |
Report the saved Jade defaults without printing the token. |
jcode cloud sessions upload session_abc.json |
Upload one local session file to Jade cloud storage. |
jcode cloud sessions upload-latest |
Upload the newest local session file. |
jcode cloud sessions sync |
Upload new or changed local sessions, idempotently and safe to schedule. |
jcode cloud sessions list |
List the sessions in the Jade index. |
jcode cloud sessions verify session_abc |
Check that the cloud metadata and the S3 session blob both exist. |
jcode cloud sessions dashboard |
Render a local HTML dashboard of the uploaded sessions. |
jcode cloud sessions view session_abc |
Download and view one uploaded session. |
Environment variables
| Variable | Purpose |
|---|---|
JCODE_CLOUD_HOST |
Default target host, used when --host is absent. |
JCODE_CLOUD_REMOTE_BINARY |
Default remote binary name or path, used when --remote-binary is absent. |
JCODE_CLOUD_TRANSPORT |
Default local command used in place of ssh cloud-e2e, used when --transport is absent. |
JCODE_CLOUD_HOST_LABEL |
Label the machine reports for itself in the manifest and in the notices. |
JCODE_CLOUD_QUIET |
When set, the stage progress lines are suppressed. |
JCODE_SESSION_ID |
The session a move or return acts on when --session is absent. |
Failure modes
| Stage | Condition | MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | State left behind |
|---|---|---|---|
| resolve | Neither --host nor JCODE_CLOUD_HOST is set |
No cloud host configured, naming both sources | Nothing changed. |
| preflight | The remote jcode does not know the cloud receive subcommand |
The host does not support cloud move yet, naming --remote-binary and JCODE_CLOUD_REMOTE_BINARY |
Nothing changed. |
| move | The lease names an away host | The session already lives on that host, use jcode cloud return first |
Nothing changed. |
| move | A turn is in flight and --allow-active is absent |
The session is mid-turn | Nothing changed. |
| prepare | The repository has no commits yet | Commit once before moving | Nothing changed. |
| receive | The incoming format version is not supported | The format version is not supported and the expected version is named | Nothing changed. |
| receive | The host already holds the session at that epoch or later | The host already has the session at that epoch | Nothing changed. |
| receive | The cloud checkout holds work jcode did not place | The path has changes that were never returned, and the paths to clean it are named | The existing files are untouched. |
| verify | The cloud report names another session, another epoch, another message count, or another snapshot | The mismatch is reported with both values | Ownership is not handed over. |
| commit | The activation on the cloud host fails | Cloud activation failed and the session stays local | The previous local lease is restored. |
| return | The session has no lease | The session was never moved | Nothing changed. |
| return | The lease names no away host | The session already lives here | Nothing changed. |
| export | The host does not own the session | The session does not live on this host | The host keeps ownership. |
| export | The requested epoch is not newer than the host epoch | The stale epoch and the current epoch are reported | The host keeps ownership. |
| export | A turn is in flight on the cloud host | The session is mid-turn on the cloud host | The host keeps ownership. |
| merge | The merge conflicts | The conflicting files are named and the cloud ref is named | The working tree is untouched. |
Sequences
Move a session to a cloud host
sequenceDiagram
autonumber
actor U as Operator
participant L as jcode cloud move
participant FS as Local filesystem
participant C as Cloud host
participant LE as Local lease
U->>L: jcode cloud move --session session_abc --host cloud-e2e
L->>FS: read the lease, refuse if the session is away or mid-turn
L->>C: jcode cloud receive --help
C-->>L: the protocol is supported
L->>FS: load the transcript, snapshot the repo into a bundle
L->>FS: write the manifest, the transcript, the todos, the memory
L->>FS: tar the package into move.tar
L->>C: jcode cloud receive --json, move.tar on stdin
C->>C: restore the repo at the same path, stage the package
C-->>L: the receive report
L->>L: verify the session id, the epoch, the message count, the snapshot
L->>LE: write the lease, away_host = host, epoch = n
L->>C: jcode cloud activate --session session_abc --epoch 1
C->>C: install the transcript, the todos, the memory, write the local lease
L->>FS: git update-ref refs/jcode-cloud/session_abc/base
L-->>U: the host, the epoch, the attach and return commands
Work on the cloud host
sequenceDiagram
autonumber
actor U as Operator
participant L as Old machine
participant C as Cloud host
participant A as Cloud agent
U->>C: jcode --resume session_abc run
C->>C: the lease says the session lives here and the copy is current
A->>A: reads the migration notice in the transcript
A->>C: runs the task, commits, edits files
Note over L: the old machine is refused, its lease says the session moved away
Return the session to the local machine
sequenceDiagram
autonumber
actor U as Operator
participant L as jcode cloud return
participant C as Cloud host
participant FS as Local filesystem
U->>L: jcode cloud return --session session_abc
L->>FS: read the lease, take the away host, bump the epoch
L->>C: jcode cloud export --session session_abc --epoch 2
C->>C: stop owning the session, snapshot the repo
C-->>L: the return package on stdout
L->>L: verify the manifest session id and epoch
L->>FS: git fetch the bundle into refs/jcode-cloud/session_abc/cloud
L->>FS: git merge-tree the local tree, the base, and the cloud snapshot
alt no conflict
L->>FS: read-tree the merged tree into the working tree
else conflict
L->>L: leave the working tree alone, name the conflicting files
end
L->>FS: install the cloud transcript, drop the old journal
L->>FS: write the lease, away_host = none, epoch = n
L-->>U: the message count and the merge outcome
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Conversation ownership | A per-machine lease file with a monotonic epoch | A transcript is linear, so exactly one machine may run turns. A shared counter is cheaper than a lock service and needs no control plane. |
| Code transfer | A git bundle plus a snapshot commit | Git already knows how to move a working tree, and a bundle carries the history without a server. |
| Snapshot creation | A temporary index through GIT_INDEX_FILE, then git add -A and git write-tree |
The snapshot captures the staged, unstaged, and untracked work while the user's index and working tree stay untouched. |
| Snapshot commit | git commit-tree on top of HEAD, with a fallback identity only when the repository has none |
The snapshot is a real commit, so the bundle carries it and the merge base is a normal commit. |
| Merge on return | git merge-tree --write-tree with an explicit --merge-base |
The merge is computed on trees, so a conflict can be reported without writing conflict markers into the user's files. |
| Merge base | The snapshot both sides agreed on at move time, stored in the lease | The base is the exact state the move started from, so edits on both sides merge cleanly. |
| Refs namespace | refs/jcode-cloud/session_abc/{base,outgoing,cloud,cloud-head} |
Every piece of moved state stays reachable from a ref, so nothing is lost even when the merge is refused. |
| Path preservation | The repository is restored at the same absolute path | Every path mentioned in the transcript stays valid on the cloud host. |
| Environment transfer | A fixed allowlist of locale, editor, git identity, and build variables | Machine-local, display, and secret variables must not travel. |
| Ignored files | A fixed allowlist, git-ignored only, at most 256 KiB each | A .env file is often needed to run, but build output must never travel. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | ssh cloud-e2e by default, overridable with --transport |
SSH is already how operators reach their machines, and the override makes the whole flow testable without a second machine. |
| Handoff shape | Prepare, transfer, verify, commit | A failure before the commit is a no-op, so the local session stays usable and the agent can read the error and fix it. |
| Lease write | Write to a temporary file, then rename | A crash during the write cannot leave a corrupt lease. |
| Remote commands | Hidden cloud receive, cloud activate, and cloud export subcommands |
The remote half is invoked over SSH and is not part of the user-facing surface. |
| Journal handling | The incoming snapshot replaces the local snapshot and the old journal is deleted | The incoming transcript is complete and newer, so the old journal would be stale. |
| TUITerminal User Interface integration | The TUITerminal User Interface runs the CLI between turns and then reattaches | The CLI stays the single implementation, and the TUITerminal User Interface only decides when to call it. |
| Jade uploads | A separate helper process driven by jcode cloud sessions |
The upload half talks to a cloud index and shares no state with the move protocol, so it stays out of the lease design. |
| Managed control plane | Not part of this implementation | docs/JCODE_CLOUD_AWS.md is a design direction, and the control plane it describes is not deployed. |
Risks and Unknowns
- The transfer is unencrypted at the application layer, so confidentiality depends entirely on the SSH transport.
- The lease lives on local disk, so a machine that loses its jcode home forgets its proof of ownership and can no longer tell whether it is the owner.
- The lease is checked at the start of a turn and on every loop iteration, not at the provider-request boundary inside one streaming request, so a move that lands during a streaming request can let that request finish.
- The merge base is the snapshot agreed at move time, so a local rebase, reset, or branch switch between the move and the return can make the base inapplicable and force a conflict.
- The cloud overwrite guard compares the current tree against the snapshots jcode placed and the HEAD tree, so work that matches neither is preserved by refusing the move, and the operator has to clean the cloud checkout by hand.
git merge-tree --write-treeneeds a recent git, and an older git makes the merge fail rather than degrade.- The ignored-file allowlist copies
.envand similar files to the cloud host, so the cloud host ends up holding local secrets. - The
wherereport counts commits against the last synced head, so it does not show uncommitted local work. - The
jcode cloud sessionshalf talks to a private Jade helper that lives outside this repository, so its upload path cannot be exercised from this codebase alone. - The transfer format carries a single version number, so a protocol change that is not backward compatible breaks the move for every older cloud host at once.
- The move protocol assumes the cloud host runs the same jcode major version, and the preflight only detects a missing subcommand, not a behavioral difference.
Out of Scope
- The managed AWS control plane in
docs/JCODE_CLOUD_AWS.md, including per-user hosts, account activation, theapi.jcode.sh/v1cloud endpoints, and the subscription tiers. That document is a design direction, and the control plane is not deployed. The only live AWS deployment it names is a single internal reference host inus-east-1. - Migrating background processes, dev servers, terminals, and background tasks. They are detected and named in the manifest, not carried.
- The native SSH attach implementation itself, which
jcode cloud attachand/cloudreuse. It is described indocs/NATIVE_SSH.md. - The remote handoff design sketch in
docs/REMOTE_HANDOFF.md, which proposes a transport abstraction that is not implemented. - The Jade cloud index and the S3 session storage behind it. The
jcode cloud sessionscommands are documented here only as a CLI surface.
Test Plan: Cloud SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. Handoff
Scope
Covers the lease that decides which machine owns a session, the move that hands a session to a cloud host, the return that merges the cloud work back, the where and attach commands, the /cloud and /local TUITerminal User Interface commands, and the Jade cloud session upload surface that shares the jcode cloud command tree.
Test files that exist for this feature:
crates/jcode-storage/src/session_lease.rs, the inlinemod testsblock, covering the lease read, write, and block decision.crates/jcode-tui/src/tui/app/commands_cloud.rs, the inlinemod testsblock, covering the/cloudand/localparser.crates/jcode-app-core/src/agent/idle_hibernation.rs, the inlinemod testsblock, covering the lease guard on the session save path.src/cli/args/tests.rs, covering the parsing of thejcode cloud sessionssubcommands.src/cli/commands_tests.rs, covering the Jade config, the helper argument contract, the sync candidate selection, the sync throttle, and the dashboard rendering.scripts/test_cloud_move_e2e.sh, a two-machine end-to-end script forjcode cloud moveandjcode cloud return.scripts/test_cloud_move_agent_e2e.sh, an agent-level end-to-end script with real model turns on both machines.scripts/test_cloud_move_tui_e2e.sh, an interactive end-to-end script that drives the TUITerminal User Interface over SSH.
Files and paths with no test coverage for this feature:
src/cli/cloud_move.rshas nomod testsblock at all. Every function in it, includingrun_move,run_return,run_receive,run_activate,run_export,run_where,snapshot_repo,restore_repo, andmerge_back, is covered only by the three shell scripts.src/cli/args/tests.rsdoes not parsejcode cloud move,jcode cloud return,jcode cloud where, orjcode cloud attach, so the flags of the handoff commands have no parsing test.crates/jcode-app-core/src/agent/turn_execution.rs,crates/jcode-app-core/src/agent/turn_loops.rs, andcrates/jcode-app-core/src/agent/turn_streaming_mpsc.rshave no test that asserts the lease block stops a turn.crates/jcode-app-core/src/agent_tests.rscallsensure_session_lease()insaved_account_restore_mismatch_blocks_model_turnand in the account-route test, but both assert the account-restore error, not the lease block.crates/jcode-base/src/session/persistence.rshas a test module, but it does not exercise the lease guard insave_inner. That guard is covered by the idle hibernation test.- No Rust integration test under
tests/covers the handoff. The three shell scripts are not referenced by any workflow in.github/workflows/, so they run only when a person invokes them.
Out of scope: the Jade cloud index and its S3 storage, the managed AWS control plane described in docs/JCODE_CLOUD_AWS.md, the native SSH attach implementation that jcode cloud attach reuses, and the migration of background processes and dev servers.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | A session with no lease is never blocked | crates/jcode-storage/src/session_lease.rs (no_lease_never_blocks) |
With no lease file, session_lease_block returns nothing for any epoch |
| TC-2 | A moved-away lease blocks every copy | crates/jcode-storage/src/session_lease.rs (moved_away_blocks_every_copy) |
With a lease at epoch 3 and an away host, a copy at epoch 3 is blocked with the MovedAway variant |
| TC-3 | A returned lease blocks only stale copies | crates/jcode-storage/src/session_lease.rs (returned_session_blocks_only_stale_copies) |
With a lease at epoch 4 and no away host, a copy at epoch 2 is blocked with the StaleCopy variant and a copy at epoch 4 is not |
| TC-4 | A path-like session id is rejected | crates/jcode-storage/src/session_lease.rs (rejects_path_like_ids) |
Reading the lease for ../x returns nothing and writing it fails with an invalid session id error |
| TC-5 | The /cloud and /local parser |
crates/jcode-tui/src/tui/app/commands_cloud.rs (parses_cloud_commands) |
/cloud moves with no host, /cloud my-box moves to that host, /local and /cloud back return, /cloud status reports the location, and /cloudy is not claimed |
| TC-6 | A blocked copy does not write the session | crates/jcode-app-core/src/agent/idle_hibernation.rs (idle_hibernation_does_not_write_session_and_refuses_migration_lease) |
With a lease that names an away host, save_prepared succeeds without writing, the file on disk is byte for byte unchanged, and the hibernation is refused |
| TC-7 | The Jade helper argument contract | src/cli/commands_tests.rs (cloud_sessions_args_match_jade_helper_contract) |
The helper is called with the documented subcommand, the user id, the profile, the region, and the format flags, in that order |
| TC-8 | The Jade config keeps the secret out of the arguments | src/cli/commands_tests.rs (cloud_sessions_config_persists_secret_and_feeds_helper_env_without_args) |
The config file is written with mode 0o600, the token is passed to the helper through the environment, the token never appears in the argument list, and --clear removes the file |
| TC-9 | The syncable session file filter | src/cli/commands_tests.rs (is_syncable_session_stem_filters_non_session_files) |
session_abc_123 and imported_codex_456 are syncable, and req, test_selfdev_session, and session_abc.journal are not |
| TC-10 | The sync candidate collection | src/cli/commands_tests.rs (collect_sync_candidates_picks_only_session_json) |
Only the real session JSON files in the directory are collected, and the backups and journals are skipped |
| TC-11 | A sync dry run does not upload and does not write state | src/cli/commands_tests.rs (cloud_sessions_sync_dry_run_reports_without_uploading_or_writing_state) |
The run succeeds, the helper that would fail is never invoked, and no sync state file is created |
| TC-12 | The sync throttle | src/cli/commands_tests.rs (cloud_sessions_sync_respects_min_interval_throttle) |
With a recent last_sync_at and --min-interval-mins 60, the run returns successfully without invoking the helper and without recording the session as uploaded |
| TC-13 | The dashboard HTML escapes the session data | src/cli/commands_tests.rs (render_cloud_sessions_dashboard_html_escapes_and_lists_rows) |
The title markup is escaped, both sessions are listed, and numeric and string message counts both render |
| TC-14 | The dashboard HTML with no sessions | src/cli/commands_tests.rs (render_cloud_sessions_dashboard_html_handles_empty) |
The page reports zero sessions and the empty-state message |
| TC-15 | The dashboard HTML links the generated viewers | src/cli/commands_tests.rs (render_cloud_sessions_dashboard_html_links_rows_with_view_files) |
A session with a viewer file gets an anchor to it, and a session without one stays plain text |
| TC-16 | The jcode cloud sessions argument parsing |
src/cli/args/tests.rs (cloud_sessions_subcommands_parse, and the jcode cloud sessions dashboard assertions in model_list_subcommand_parses) |
configure, status, upload-latest, view, and sync parse with their flags, and dashboard parses with --limit, --open, --with-view, and --user-id |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-17 | The staged move and the cloud checkout | scripts/test_cloud_move_e2e.sh, steps 1 to 4, with JCODE_BIN pointing at the binary under test |
A dry run writes no lease and leaves the working tree and the index unchanged. The real move writes a local lease with away_host set, restores the repository on the cloud host at the same absolute path with the same uncommitted, untracked, and staged files, copies the allowlisted .env but not the ignored build output, keeps the same HEAD, branch, and git identity, installs the transcript and the todos, and writes a cloud lease with no away host. The shipped transcript carries the migration notice, the dangling tool call is closed, and the migration epoch is 1. A second move is refused, and jcode cloud where shows the cloud host |
| TC-18 | The return merges both sides | scripts/test_cloud_move_e2e.sh, step 5, after the cloud side commits and the local side edits a different hunk |
The report says the merge was applied, the local branch is fast-forwarded to the cloud commits, the cloud file and the cloud uncommitted edit are present, the local edit in the same file survives, the local-only file survives, the ignored build output is untouched, the local lease names no away host, the cloud lease records away_host as returned, and the returned transcript holds the cloud turn, the return notice, and migration epoch 2 |
| TC-19 | A second round trip with a real conflict | scripts/test_cloud_move_e2e.sh, step 6 |
The second move reuses the cloud checkout, the return reports conflicts and names the conflicting file, the local file is byte for byte unchanged, and the cloud work is reachable at refs/jcode-cloud/session_abc/cloud |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-20 | A real turn on each side of the handoff | scripts/test_cloud_move_agent_e2e.sh, with the fake OpenAI-compatible server in scripts/fake_openai_server.py |
A real local turn runs, the session moves, the local copy is then refused with a message that names the cloud host, the cloud model sees the migration notice and the full earlier conversation, the return reports the merge as applied, the cloud file is present locally, and the final local turn sees the laptop turn, the cloud turn, the return notice, and the new prompt, with the blocked prompt absent from the transcript |
| TC-21 | The interactive TUITerminal User Interface handoff over SSH | scripts/test_cloud_move_tui_e2e.sh, with a user-level sshd as the cloud host and the TUITerminal User Interface in tmux |
The local turn is answered, /cloud reattaches over SSH and the agent auto-continues on the cloud and sees the migration notice, the laptop lease names the cloud host, the cloud checkout holds the uncommitted laptop edit, /local brings the session back with the cloud edit merged into the laptop checkout, the laptop lease names no away host, and the final local context holds the whole history including the return notice |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-22 | Neither --host nor JCODE_CLOUD_HOST is set |
The move fails and the message names both sources |
| TC-23 | The cloud host runs a jcode that does not know cloud receive |
The move fails in the preflight, before any state changes, and the message names the host and the remedy |
| TC-24 | The session already lives on another host | The move is refused and the message says to run jcode cloud return first. Proven by TC-17, which checks that a second move is refused |
| TC-25 | A turn is in flight and --allow-active is absent |
The move is refused and the message says the session is mid-turn |
| TC-26 | A dry run | The cloud copy is staged and verified, no lease is written locally, and the working tree and the index are unchanged. Proven by TC-17 |
| TC-27 | The cloud host stages the move but fails to activate | The local lease is restored to its previous value, or removed when there was none, and the session stays local |
| TC-28 | The cloud checkout holds work jcode did not place there | The receive is refused, the message names the path, and the existing files are left alone |
| TC-29 | The incoming transfer format version is not supported | The receive is refused and the expected format version is named |
| TC-30 | The old machine tries to run the session after the move | The turn is refused with a message that names the new host. Proven by TC-20 |
| TC-31 | The return merges conflicting edits | The local working tree is untouched, no conflict markers are written, the cloud work stays reachable at refs/jcode-cloud/session_abc/cloud, and the transcript names the conflicting files. Proven by TC-19 |
| TC-32 | A stale in-memory copy tries to save after the session came back | The save is skipped, the on-disk transcript is unchanged, and the block reason says the copy is stale. Partly proven by TC-6 |
| TC-33 | The export is asked for an epoch that is not newer than the host epoch | The export is refused and both epochs are reported |
| TC-34 | The export fails after the host stopped owning the session | The host takes ownership back, so the session stays usable there |
| TC-35 | A turn is in flight on the cloud host when the export runs | The export is refused and the host keeps ownership |
| TC-36 | The repository has no commits yet | The move fails in the prepare stage and asks for one commit first |
| TC-37 | A session id contains a path separator or starts with a dot | The lease write fails and nothing is written outside the lease directory. Proven by TC-4 |
Test Infrastructure
- The three shell scripts take the binary under test through the
JCODE_BINenvironment variable, and they run the binary with--no-update --no-selfdevso no daemon is restarted. scripts/test_cloud_move_e2e.shandscripts/test_cloud_move_agent_e2e.shbuild a fake cloud host withbubblewrap, giving it its ownHOME, its ownJCODE_HOME, and its own private copy of the repository at the same absolute path. They needbwrapandpython3on the machine.scripts/test_cloud_move_e2e.shandscripts/test_cloud_move_agent_e2e.shstand in forssh cloud-e2ewith a transport script, driven byJCODE_CLOUD_TRANSPORT, and point the remote binary at a copy of the binary under test.scripts/test_cloud_move_agent_e2e.shandscripts/test_cloud_move_tui_e2e.shuse the fake OpenAI-compatible server inscripts/fake_openai_server.py, which logs every request so the test can assert what the model actually saw.scripts/test_cloud_move_tui_e2e.shneeds a user-levelsshd,ssh-keygen, andtmux, and it drives the TUITerminal User Interface by sending keys and capturing panes.- The lease tests redirect
JCODE_HOMEto a temporary directory and take the shared test-home lock fromcrates/jcode-storage/src/lib.rs, so they never touch the real~/.jcode. - The Jade command tests take the shared environment lock and a temporary
JCODE_HOME, and they use a helper script that exits non-zero to prove the helper is never invoked. - The three shell scripts are not referenced by any workflow in
.github/workflows/, so they are not part of the CIContinuous Integration run today and have to be started by hand. - The edge cases TC-22, TC-23, TC-25, TC-27, TC-28, TC-29, TC-33, TC-34, TC-35, and TC-36 record required behavior that no automated test proves today. In the coverage matrix they are listed as the expected-behavior reference rather than as an automated proof.
- The handoff has no Rust test module of its own, so every function in
src/cli/cloud_move.rsdepends on the shell scripts for coverage.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall stage the session transcript, the todo list, the project memory, and the repository state, transfer them to the target host, and verify the cloud copy before ownership changes. | TC-17, TC-18, TC-19, TC-20, TC-21 |
| FR-2MustThe system shall refuse to move a session whose lease names an away host, and shall tell the operator to run `jcode cloud return` first. | TC-17, TC-24 |
| FR-3MustThe system shall refuse to move a session that is mid-turn unless `--allow-active` is passed. | none, see TC-25 and TC-35 for the required behavior |
| FR-4Must`jcode cloud move --dry-run` shall stage and verify the cloud copy without writing a lease, without changing the working tree, and without changing the index. | TC-17, TC-26 |
| FR-5MustThe system shall increment a monotonic migration epoch on every move and return, and shall stamp the shipped transcript with that epoch. | TC-17, TC-18, TC-20, TC-33 |
| FR-6MustThe system shall check before staging that the cloud host's jcode supports the move protocol, and shall name the host and the remedy when it does not. | none, see TC-23 for the required behavior |
| FR-7MustThe system shall capture the repository as a git bundle plus a snapshot commit that includes the staged, unstaged, and untracked non-ignored work, without modifying the user's index or working tree. | TC-17, TC-36 |
| FR-8MustThe system shall restore the repository on the cloud host at the same absolute path, on the same branch, with the same uncommitted work, and with the git identity when the cloud checkout has none. | TC-17 |
| FR-9MustThe system shall carry only allowlisted environment variables, and shall copy only allowlisted ignored files that are git-ignored and at most 256 KiB each, so that no machine-local, display, secret, or build-output state travels. | TC-17 |
| FR-10MustThe system shall append an agent-facing migration notice to the transcript that covers the source and target hosts, the epoch, the repository path, branch, and uncommitted state, the build caches that did not travel, the toolchain hints, the local MCP servers, and the local background tasks that did not travel. | TC-17, TC-20 |
| FR-11MustThe system shall close any unanswered tool use in the last assistant message with a tool result, so that the shipped transcript stays valid for the provider. | TC-17 |
| FR-12MustThe system shall hand ownership to the cloud host only after the cloud copy is verified, and shall restore the previous local lease when the activation fails. | TC-17, TC-27, TC-34, TC-35 |
| FR-13MustThe system shall refuse to overwrite a cloud checkout that holds work jcode did not place there, and shall name the path in the refusal. | none, see TC-28 for the required behavior |
| FR-14Must`jcode cloud return` shall install the cloud transcript locally, replacing the local snapshot and removing the old journal. | TC-18, TC-20 |
| FR-15MustThe system shall merge the cloud repository work into the local checkout as a 3-way merge whose base is the snapshot both sides agreed on at move time. | TC-18, TC-20 |
| FR-16MustThe system shall report the merge outcome as no repository, unchanged, refs only, applied, or conflicts, and shall name the conflicting files. | TC-18, TC-19, TC-20 |
| FR-17MustOn a conflict the system shall leave the local working tree untouched, shall keep the cloud work reachable at `refs/jcode-cloud/session_abc/cloud`, and shall tell the operator how to resolve it. | TC-19, TC-31 |
| FR-18Must`jcode cloud return --refs-only` shall fetch the cloud work into refs without touching the working tree. | none, see TC-19 for the ref that the same merge path writes |
| FR-19MustThe system shall append a return notice to the transcript that names the cloud host, the local machine, the time, the merge outcome, and the fact that the cloud processes did not come back. | TC-18, TC-20, TC-21 |
| FR-20MustThe system shall restore local ownership and bump the epoch when a session comes back. | TC-18, TC-21 |
| FR-21MustThe system shall refuse to return a session that was never moved, and shall refuse to return a session that already lives on this machine. | none, see TC-24 for the parallel move refusal |
| FR-22Must`jcode cloud where` shall report, for every moved session, the session id, the location, the epoch, the repository root, and the number of commits the local checkout is ahead of the last synced head. | TC-17 |
| FR-23Must`jcode cloud attach` shall attach this terminal to the host that owns the session and resume the same session id there. | TC-21 |
| FR-24MustThe system shall resolve the target host from `--host` or `JCODE_CLOUD_HOST`, and the remote binary from `--remote-binary` or `JCODE_CLOUD_REMOTE_BINARY`, and shall name both in the error when they are missing. | TC-20, TC-21, TC-22 |
| FR-25MustThe system shall keep one lease file per session under `~/.jcode/session_leases`, named after the session id, recording the epoch, the away host, the repository root, the last agreed snapshot and head, and the update time. | TC-2, TC-3, TC-4, TC-17, TC-18, TC-21 |
| FR-26MustA session copy on a machine whose lease says the session moved away shall neither start a turn nor persist. | TC-2, TC-20, TC-30 |
| FR-27MustA session copy whose epoch is older than the lease epoch shall neither start a turn nor persist. | TC-3, TC-6, TC-32 |
| FR-28MustA session that never migrated shall run and persist normally. | TC-1, TC-6 |
| FR-29ShouldThe TUITerminal User Interface shall offer `/cloud [host]`, `/cloud back`, `/cloud return`, `/cloud status`, and `/local`, shall run the matching CLI command between turns, and shall reattach at the new location. | TC-5, TC-21 |
| FR-30ShouldThe TUITerminal User Interface shall refuse a move or a return while the agent is mid-turn, and shall leave everything where it was. | none, see TC-5 for the parser and TC-21 for the TUITerminal User Interface round trip |
| FR-31Should`jcode cloud sessions` shall upload, upload the latest, sync, list, verify, render a dashboard for, and view session transcripts through the private Jade helper, and shall pass the API token in the helper environment rather than on the command line. | TC-7, TC-8, TC-13, TC-14, TC-15, TC-16 |
| FR-32Should`jcode cloud sessions configure` shall persist the Jade defaults with owner-only file permissions, `jcode cloud sessions status` shall report them without printing the token, and `--clear` shall remove the config file. | TC-8, TC-16 |
| FR-33Should`jcode cloud sessions sync` shall skip unchanged sessions, shall honor `--since-days`, `--max`, `--min-interval-mins`, `--force`, and `--dry-run`, and shall not record sync state during a dry run. | TC-9, TC-10, TC-11, TC-12 |
| NFR-1MustThe system shall not lose a transcript message across a move or a return: the cloud copy shall be verified to hold the same session id, the same epoch, and the same message count as the local copy before ownership changes. | TC-17, TC-18, TC-20 |
| NFR-2MustAt most one machine shall run turns for a given session at a time, enforced by the lease check before every turn, before every turn-loop iteration, and before every save. | TC-2, TC-3, TC-6, TC-20, TC-30 |
| NFR-3MustA return shall merge the cloud tree into the local tree with a real 3-way merge, so that edits made on either side during the migration survive, and a merge that cannot complete shall not modify the working tree. | TC-18, TC-19, TC-31 |
| NFR-4MustThe lease file shall be written to a temporary file and then renamed, so that a crash during the write cannot leave a corrupt lease. | none, see TC-17 and TC-18 for the lease reads that depend on it |
| NFR-5MustThe system shall not persist secrets into the lease, the manifest, or the transcript, and shall not copy machine-local or secret environment variables. | TC-8, TC-9, TC-17 |
| NFR-6MustA session id used as a lease file name shall be restricted to ASCII alphanumerics, underscore, dash, and dot, and shall not start with a dot, so that a session id cannot escape the lease directory. | TC-4, TC-37 |
| NFR-7MustA failed move shall leave the local session usable: the previous lease shall be restored, the local transcript shall be untouched, and the failure shall name the stage that failed. | TC-17, TC-27 |
| NFR-8ShouldThe transfer size shall stay proportional to the tracked source, because build output, dependency trees, and other ignored directories are never copied. | TC-17 |
| NFR-9ShouldA cloud host whose jcode predates the move protocol shall be detected before any state changes, and the error shall name the host. | none, see TC-23 for the required behavior |
| NFR-10ShouldThe transfer format shall carry a version number, and a host that does not support the incoming format shall refuse the move and name the version it expects. | none, see TC-29 for the required behavior |
| NFR-11ShouldThe move and the return shall emit one progress line per stage, and shall emit none when `JCODE_CLOUD_QUIET` is set. | none, the stage lines are visible in the shell script output but not asserted |
| NFR-12ShouldThe `where` report shall show how far the local checkout has diverged from the last synchronized head, so the operator can tell whether local work is pending. | none, the divergence count is printed by jcode cloud where in TC-17 but not asserted |
requirements
- Should the cloud host lease the session for a fixed period, so that a host that dies mid-session releases the session automatically?
Today the operator runs
jcode cloud returnby hand. - Should the ignored-file allowlist be configurable, and should the operator be warned that
.envfiles are copied to the cloud host? Today the allowlist is a fixed constant insrc/cli/cloud_move.rs. - Should a mid-turn move wait for the turn to finish instead of requiring
--allow-active? Today the agent itself passes--allow-activewhen the operator types/cloudfrom inside a turn. - Should the managed AWS control plane in
docs/JCODE_CLOUD_AWS.mdreplace the SSH transport for the move and return path? The document is a design direction and the control plane is not deployed.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Hosted Account and Plans
Overview
The first-party Jcode account is the user's identity for everything the Jcode service hosts.
Signing in is a browser-based device authorization: the user approves the request on https://jcode.sh/account, and Jcode exchanges a single-use device code for an account key that is stored on the machine with owner-only permissions.
The account carries a metered plan rather than a fixed subscription fee.
The user picks a monthly spending limit in the browser, usage is billed in progressively larger tranches starting at $20, and the account service enforces that limit server-side.
Jcode surfaces the canonical account, the plan tier, the spend against the limit, and the daily feature allowances so the user always knows what the account is spending.
This feature documents already-implemented functionality that was reverse-engineered from the existing codebase during an SDLC sync.
Stakeholders
| Stakeholder | Interest |
|---|---|
| CLI user | One command to sign in, one command to see the plan and the spend, and one command to leave |
| TUITerminal User Interface user | A hosted-model entry point, a status surface, and a visible spending balance while the session runs |
| Desktop user | The same account and plan surfaces through the shared account login library |
| Account API owner | A single device-authorization contract that the CLI, the TUITerminal User Interface and Desktop all speak |
| Finance | A monthly limit the user controls, a predictable tranche schedule, and a server-side enforcement point |
| Support | A way to tell whether a credential is present, revoked, or offline without reading the user's credential file |
| Maintainer | A catalog and a route policy that the server, not a stale client-side tier, decides |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall sign a user in with a browser-based device authorization flow that requests a device code with the `jcode-cli` client name, opens the public approval URL, and polls the token endpoint with bounded backoff until the browser approves, the user denies, the device code expires, or the flow times out, and a Ctrl-C during the wait shall cancel the flow without saving a credential. | Must | The system shall sign a user in with a browser-based device authorization flow that requests a device code with the jcode-cli client name, opens the public approval URL, and polls the token endpoint with bounded backoff until the browser approves, the user denies, the device code expires, or the flow times out, and a Ctrl-C during the wait shall cancel the flow without saving a credential. |
| FR-2MustThe system shall wait for plan activation after the browser approval by polling `/v1/me` until the account reports an active plan with a spending limit, a canceled checkout, a revoked or denied key, or the activation timeout elapses. | Must | The system shall wait for plan activation after the browser approval by polling /v1/me until the account reports an active plan with a spending limit, a canceled checkout, a revoked or denied key, or the activation timeout elapses. |
| FR-3MustThe system shall persist the approved account key together with the non-secret account id, email and tier in the owner-only hosted-account file, and shall not write any credential before the browser approval is confirmed. | Must | The system shall persist the approved account key together with the non-secret account id, email and tier in the owner-only hosted-account file, and shall not write any credential before the browser approval is confirmed. |
| FR-4MustThe system shall keep the valid account key and print recovery actions when activation is canceled or times out, and shall clear the local credentials when the key is revoked or the account server denies the activation check. | Must | The system shall keep the valid account key and print recovery actions when activation is canceled or times out, and shall clear the local credentials when the key is revoked or the account server denies the activation check. |
| FR-5MustThe system shall report the canonical account email, the plan tier and status, and the monthly spending usage from `/v1/me` on `jcode account status`, and shall offer a `--json` form of the same account payload. | Must | The system shall report the canonical account email, the plan tier and status, and the monthly spending usage from /v1/me on jcode account status, and shall offer a --json form of the same account payload. |
| FR-6MustThe system shall tell the user to run `jcode account login` when no account credential is configured, and shall clear the local credentials and report a revoked or expired key when `/v1/me` answers unauthorized. | Must | The system shall tell the user to run jcode account login when no account credential is configured, and shall clear the local credentials and report a revoked or expired key when /v1/me answers unauthorized. |
| FR-7MustThe system shall open the public Jcode account management page from `jcode account manage`, and shall print the URL instead of launching a browser when browser launch is suppressed. | Must | The system shall open the public Jcode account management page from jcode account manage, and shall print the URL instead of launching a browser when browser launch is suppressed. |
| FR-8MustThe system shall always clear the local account credential, the cached account identity and the cached tier on `jcode account logout`, and shall revoke the key remotely when the account API is reachable. | Must | The system shall always clear the local account credential, the cached account identity and the cached tier on jcode account logout, and shall revoke the key remotely when the account API is reachable. |
| FR-9MustThe system shall report the outcome of each logout step, distinguishing no local credential, a revoked key, an already revoked key, an offline account API, and a remote revocation that could not be confirmed. | Must | The system shall report the outcome of each logout step, distinguishing no local credential, a revoked key, an already revoked key, an offline account API, and a remote revocation that could not be confirmed. |
| FR-10MustThe system shall write the hosted-account credential file with owner-only permissions and shall re-harden and re-verify the permission mode after every credential mutation. | Must | The system shall write the hosted-account credential file with owner-only permissions and shall re-harden and re-verify the permission mode after every credential mutation. |
| FR-11MustThe system shall offer exactly the curated hosted models, shall offer every curated model at the base plan, and shall pin every hosted model to the managed Jcode router route so a hosted model id never falls through to a direct provider credential. | Must | The system shall offer exactly the curated hosted models, shall offer every curated model at the base plan, and shall pin every hosted model to the managed Jcode router route so a hosted model id never falls through to a direct provider credential. |
| FR-12MustThe system shall expose `/hosted` and its `/subscribe` alias for the hosted-model pitch, and `/hosted status` with its `/subscription` and `/subscription status` aliases for the hosted account status. | Must | The system shall expose /hosted and its /subscribe alias for the hosted-model pitch, and /hosted status with its /subscription and /subscription status aliases for the hosted account status. |
| FR-13MustThe system shall show the credential state, the router base, the billing model, the runtime mode, the curated catalog and the billing rules including the tranche schedule on the hosted account status surface, and shall fetch `/v1/me` in the background to publish the account email, the billing status, the spend against the monthly limit, the amount already billed, the next tranche amount and the reset time. | Must | The system shall show the credential state, the router base, the billing model, the runtime mode, the curated catalog and the billing rules including the tranche schedule on the hosted account status surface, and shall fetch /v1/me in the background to publish the account email, the billing status, the spend against the monthly limit, the amount already billed, the next tranche amount and the reset time. |
| FR-14MustThe system shall clear the local credentials and tell the user to sign in again when the hosted account status surface finds that the account key was revoked. | Must | The system shall clear the local credentials and tell the user to sign in again when the hosted account status surface finds that the account key was revoked. |
| FR-15MustThe system shall report the Jcode inference spending balance, the remaining amount against the monthly limit, the daily feature allowances and the reset time on the usage surface, shall mark the hard limit as reached when the monthly spend reaches the monthly limit, shall not mark it reached when the limit is unknown, and shall suggest an upgrade when a daily allowance passes 80 percent of its limit and an upgrade target is offered. | Must | The system shall report the Jcode inference spending balance, the remaining amount against the monthly limit, the daily feature allowances and the reset time on the usage surface, shall mark the hard limit as reached when the monthly spend reaches the monthly limit, shall not mark it reached when the limit is unknown, and shall suggest an upgrade when a daily allowance passes 80 percent of its limit and an upgrade target is offered. |
| FR-16MustThe system shall produce a subscription notice when a plan or allowance changes that names the exhausted feature, the current plan and the upgrade target with a link, and shall deliver the notice once per occurrence. | Must | The system shall produce a subscription notice when a plan or allowance changes that names the exhausted feature, the current plan and the upgrade target with a link, and shall deliver the notice once per occurrence. |
| FR-17MustThe system shall expose the hosted account in the TUITerminal User Interface through `/login jcode` and `/account jcode login`, and shall expose the account status, the management page and the logout as `/account jcode status`, `/account jcode manage` and `/account jcode logout`. | Must | The system shall expose the hosted account in the TUITerminal User Interface through /login jcode and /account jcode login, and shall expose the account status, the management page and the logout as /account jcode status, /account jcode manage and /account jcode logout. |
| FR-18MustThe system shall enable the hosted runtime mode when the hosted account is activated, and shall clear the hosted runtime mode when the credentials are cleared or the user selects another provider. | Must | The system shall enable the hosted runtime mode when the hosted account is activated, and shall clear the hosted runtime mode when the credentials are cleared or the user selects another provider. |
| FR-19ShouldThe system shall offer an email-code sign-in that sends a code to the address, keeps the code token in memory only, and reports the remaining attempts when the typed code is wrong. | Should | The system shall offer an email-code sign-in that sends a code to the address, keeps the code token in memory only, and reports the remaining attempts when the typed code is wrong. |
| FR-20ShouldThe system shall surface a hosted-model nudge when a provider rate-limits the user and after a long fully completed task, at most once per session and at most once per week, and never for a user who already holds account credentials. | Should | The system shall surface a hosted-model nudge when a provider rate-limits the user and after a long fully completed task, at most once per session and at most once per week, and never for a user who already holds account credentials. |
| FR-21MayThe system shall accept a monthly hard cap, a billing portal session, a subscription checkout and a plan change from the account API, and shall accept only an https billing portal URL and only a Stripe Checkout URL. | May | The system shall accept a monthly hard cap, a billing portal session, a subscription checkout and a plan change from the account API, and shall accept only an https billing portal URL and only a Stripe Checkout URL. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustThe account key shall never appear in a URL, in a debug rendering, in a log line or in an error message, and shall be sent only in an authorization header. | Must | Security | The account key shall never appear in a URL, in a debug rendering, in a log line or in an error message, and shall be sent only in an authorization header. |
| NFR-2MustThe browser approval URL shall be restricted to the allowlisted public https origins with the account path and a single flow query parameter, and the account management URL shall be restricted to the same origins, so a URL carrying credentials, a non-default port, an unexpected path or extra query parameters is rejected. | Must | Security | The browser approval URL shall be restricted to the allowlisted public https origins with the account path and a single flow query parameter, and the account management URL shall be restricted to the same origins, so a URL carrying credentials, a non-default port, an unexpected path or extra query parameters is rejected. |
| NFR-3MustThe monthly spending limit and the model policy shall be enforced server-side by the Jcode router, and the client shall not decide from a cached tier which models an account may use or how much it may spend. | Must | Security | The monthly spending limit and the model policy shall be enforced server-side by the Jcode router, and the client shall not decide from a cached tier which models an account may use or how much it may spend. |
| NFR-4MustThe account key shall be revoked on the server when the user logs out and the account API is reachable, and the local credential shall be cleared even when the revocation cannot be confirmed. | Must | Security | The account key shall be revoked on the server when the user logs out and the account API is reachable, and the local credential shall be cleared even when the revocation cannot be confirmed. |
| NFR-5MustThe account email, the account id and the spending limit shall not be sent to the telemetry service, and the only telemetry emitted for this feature shall be the coarse authentication success event. | Must | Privacy | The account email, the account id and the spending limit shall not be sent to the telemetry service, and the only telemetry emitted for this feature shall be the coarse authentication success event. |
| NFR-6MustA failed `/v1/me` fetch shall keep the local credential and shall degrade to a quiet message rather than failing the session, and an unreachable account API during the device poll shall be retried with backoff rather than aborting the flow. | Must | Availability | A failed /v1/me fetch shall keep the local credential and shall degrade to a quiet message rather than failing the session, and an unreachable account API during the device poll shall be retried with backoff rather than aborting the flow. |
| NFR-7MustThe account status fetch shall use a 5 second timeout, the device authorization request shall use a 15 second timeout, and the polling backoff shall stay deterministic and bounded. | Must | Performance | The account status fetch shall use a 5 second timeout, the device authorization request shall use a 15 second timeout, and the polling backoff shall stay deterministic and bounded. |
| NFR-8ShouldThe activation wait shall be bounded to 10 minutes, and a polling request that is already in flight shall be allowed to finish so a single-use device code is not stranded. | Should | Availability | The activation wait shall be bounded to 10 minutes, and a polling request that is already in flight shall be allowed to finish so a single-use device code is not stranded. |
| NFR-9ShouldA user who has not signed in shall be pointed at `/login jcode`, and the hosted account status shall state plainly that hosted usage is not enabled until a spending limit exists. | Should | Usability | A user who has not signed in shall be pointed at /login jcode, and the hosted account status shall state plainly that hosted usage is not enabled until a spending limit exists. |
| NFR-10ShouldThe browser approval URL and the account management URL shall be the only links the client opens, and the client shall never open a URL returned by the account API without checking its scheme and origin. | Should | Privacy | The browser approval URL and the account management URL shall be the only links the client opens, and the client shall never open a URL returned by the account API without checking its scheme and origin. |
| NFR-11ShouldThe account service contract shall be versioned by endpoint, and a legacy backend that only offers the old email-based login shall produce a specific compatibility error rather than a generic failure. | Should | Compatibility | The account service contract shall be versioned by endpoint, and a legacy backend that only offers the old email-based login shall produce a specific compatibility error rather than a generic failure. |
Constraints
- The account API is a remote service at
https://api.jcode.sh/v1by default, overridable withJCODE_API_BASE. - The account key lives in
jcode-subscription.envunder the jcode config directory, with the API base kept separately because it is endpoint configuration and not a credential. - The hosted models are served by the Jcode router over the OpenRouter transport, pinned to the
jcode-subscriptiontransport state. - The spending limit is set by the user in the browser at
https://jcode.sh/account, not in the terminal. - The terminal never asks for an account key, and the browser never receives the account key.
- Tranche billing starts at $20 of usage and then uses progressively larger tranches, with any remaining usage billed at the limit or at month end.
- The user can change the spending limit at any time from the account page.
Acceptance Criteria
Every FR and NFR shall have at least one acceptance criterion.
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
Acceptance criteria verify how a requirement is proven done, they do not restate it.
Write concrete, scenario-based criteria (happy path, edge cases and error states where applicable).
Write each criterion as a fenced gherkin block with a tag matching its requirement ID, so the criteria are parseable and later executable via BDD tooling (pytest-bdd, cucumber).
Multiple scenarios per requirement are allowed; tag each with the requirement ID.
-
FR-1MustThe system shall sign a user in with a browser-based device authorization flow that requests a device code with the `jcode-cli` client name, opens the public approval URL, and polls the token endpoint with bounded backoff until the browser approves, the user denies, the device code expires, or the flow times out, and a Ctrl-C during the wait shall cancel the flow without saving a credential.
gherkin @FR-1MustThe system shall sign a user in with a browser-based device authorization flow that requests a device code with the `jcode-cli` client name, opens the public approval URL, and polls the token endpoint with bounded backoff until the browser approves, the user denies, the device code expires, or the flow times out, and a Ctrl-C during the wait shall cancel the flow without saving a credential. Scenario: Browser approval completes the device flow Given a running account API that returns a device authorization When the user runs `jcode account login` and approves the request in the browser Then the client sends `POST /v1/auth/device` with the client name `jcode-cli` And the client sends `POST /v1/auth/token` with the device code And no further request is sent before the approval -
FR-2MustThe system shall wait for plan activation after the browser approval by polling `/v1/me` until the account reports an active plan with a spending limit, a canceled checkout, a revoked or denied key, or the activation timeout elapses.
gherkin @FR-2MustThe system shall wait for plan activation after the browser approval by polling `/v1/me` until the account reports an active plan with a spending limit, a canceled checkout, a revoked or denied key, or the activation timeout elapses. Scenario: Activation is confirmed from the account payload Given an approved account key When the client polls `/v1/me` Then the client stops polling when the payload reports an active status with a spending limit And the client reports the monthly spending limit to the user -
FR-2MustThe system shall wait for plan activation after the browser approval by polling `/v1/me` until the account reports an active plan with a spending limit, a canceled checkout, a revoked or denied key, or the activation timeout elapses.
gherkin @FR-2MustThe system shall wait for plan activation after the browser approval by polling `/v1/me` until the account reports an active plan with a spending limit, a canceled checkout, a revoked or denied key, or the activation timeout elapses. Scenario: Canceled checkout stops the activation wait Given an approved account key When `/v1/me` reports a canceled status Then the client stops polling and reports that hosted usage is not enabled -
FR-3MustThe system shall persist the approved account key together with the non-secret account id, email and tier in the owner-only hosted-account file, and shall not write any credential before the browser approval is confirmed.
gherkin @FR-3MustThe system shall persist the approved account key together with the non-secret account id, email and tier in the owner-only hosted-account file, and shall not write any credential before the browser approval is confirmed. Scenario: The credential is written only after approval Given a device flow that is waiting for the browser When the user has not approved yet Then no account credential exists on the machine When the user approves and the client saves the credential Then the hosted-account file holds the account key, the account id, the email and the tier -
FR-4MustThe system shall keep the valid account key and print recovery actions when activation is canceled or times out, and shall clear the local credentials when the key is revoked or the account server denies the activation check.
gherkin @FR-4MustThe system shall keep the valid account key and print recovery actions when activation is canceled or times out, and shall clear the local credentials when the key is revoked or the account server denies the activation check. Scenario: A revoked key clears the local credentials Given a saved account credential When the activation check reports an unauthorized key Then the local credentials are cleared And the user is told to run `jcode account login` again -
FR-4MustThe system shall keep the valid account key and print recovery actions when activation is canceled or times out, and shall clear the local credentials when the key is revoked or the account server denies the activation check.
gherkin @FR-4MustThe system shall keep the valid account key and print recovery actions when activation is canceled or times out, and shall clear the local credentials when the key is revoked or the account server denies the activation check. Scenario: A timed-out activation keeps the key Given a saved account credential When the activation wait times out without an active plan Then the account key remains saved And the client prints the status, manage and logout recovery commands -
FR-5MustThe system shall report the canonical account email, the plan tier and status, and the monthly spending usage from `/v1/me` on `jcode account status`, and shall offer a `--json` form of the same account payload.
gherkin @FR-5MustThe system shall report the canonical account email, the plan tier and status, and the monthly spending usage from `/v1/me` on `jcode account status`, and shall offer a `--json` form of the same account payload. Scenario: Status shows the account, the plan and the spend Given a configured account credential When the user runs `jcode account status` Then the output shows the account email And the output shows the plan display name with the account status And the output shows the used amount and the monthly limit -
FR-5MustThe system shall report the canonical account email, the plan tier and status, and the monthly spending usage from `/v1/me` on `jcode account status`, and shall offer a `--json` form of the same account payload.
gherkin @FR-5MustThe system shall report the canonical account email, the plan tier and status, and the monthly spending usage from `/v1/me` on `jcode account status`, and shall offer a `--json` form of the same account payload. Scenario: Status can emit the raw account payload Given a configured account credential When the user runs `jcode account status --json` Then the output is the parsed account payload as JSON -
FR-6MustThe system shall tell the user to run `jcode account login` when no account credential is configured, and shall clear the local credentials and report a revoked or expired key when `/v1/me` answers unauthorized.
gherkin @FR-6MustThe system shall tell the user to run `jcode account login` when no account credential is configured, and shall clear the local credentials and report a revoked or expired key when `/v1/me` answers unauthorized. Scenario: Status without a credential points at the login command Given no configured account credential When the user runs `jcode account status` Then the command fails with a message telling the user to run `jcode account login` -
FR-6MustThe system shall tell the user to run `jcode account login` when no account credential is configured, and shall clear the local credentials and report a revoked or expired key when `/v1/me` answers unauthorized.
gherkin @FR-6MustThe system shall tell the user to run `jcode account login` when no account credential is configured, and shall clear the local credentials and report a revoked or expired key when `/v1/me` answers unauthorized. Scenario: Status detects a revoked key Given a configured account credential When `/v1/me` answers unauthorized Then the local credentials are cleared And the command fails with a message that the key was revoked or expired -
FR-7MustThe system shall open the public Jcode account management page from `jcode account manage`, and shall print the URL instead of launching a browser when browser launch is suppressed.
gherkin @FR-7MustThe system shall open the public Jcode account management page from `jcode account manage`, and shall print the URL instead of launching a browser when browser launch is suppressed. Scenario: Manage opens the public account page Given browser launch is allowed When the user runs `jcode account manage` Then the client opens `https://jcode.sh/account` -
FR-7MustThe system shall open the public Jcode account management page from `jcode account manage`, and shall print the URL instead of launching a browser when browser launch is suppressed.
gherkin @FR-7MustThe system shall open the public Jcode account management page from `jcode account manage`, and shall print the URL instead of launching a browser when browser launch is suppressed. Scenario: Manage prints the URL when the browser is suppressed Given browser launch is suppressed When the user runs `jcode account manage` Then the client prints the account page URL and does not launch a browser -
FR-8MustThe system shall always clear the local account credential, the cached account identity and the cached tier on `jcode account logout`, and shall revoke the key remotely when the account API is reachable.
gherkin @FR-8MustThe system shall always clear the local account credential, the cached account identity and the cached tier on `jcode account logout`, and shall revoke the key remotely when the account API is reachable. Scenario: Logout clears local state and revokes the key Given a configured account credential When the user runs `jcode account logout` and the account API is reachable Then the key is revoked on the server And the local credential, account id, email and tier are cleared -
FR-8MustThe system shall always clear the local account credential, the cached account identity and the cached tier on `jcode account logout`, and shall revoke the key remotely when the account API is reachable.
gherkin @FR-8MustThe system shall always clear the local account credential, the cached account identity and the cached tier on `jcode account logout`, and shall revoke the key remotely when the account API is reachable. Scenario: Logout clears local state when the account API is offline Given a configured account credential and an unreachable account API When the user runs `jcode account logout` Then the local credential is still cleared And the client states that remote revocation could not be confirmed -
FR-9MustThe system shall report the outcome of each logout step, distinguishing no local credential, a revoked key, an already revoked key, an offline account API, and a remote revocation that could not be confirmed.
gherkin @FR-9MustThe system shall report the outcome of each logout step, distinguishing no local credential, a revoked key, an already revoked key, an offline account API, and a remote revocation that could not be confirmed. Scenario: Logout reports the outcome of each step Given a machine with no account credential When the user runs `jcode account logout` Then the client reports that no local credential was present And the client reports that the local account cache is clear -
FR-10MustThe system shall write the hosted-account credential file with owner-only permissions and shall re-harden and re-verify the permission mode after every credential mutation.
gherkin @FR-10MustThe system shall write the hosted-account credential file with owner-only permissions and shall re-harden and re-verify the permission mode after every credential mutation. Scenario: The credential file stays owner-only Given a saved account credential When the credential file is inspected Then the file mode is owner-read and owner-write only And the same mode holds after a credential mutation -
FR-11MustThe system shall offer exactly the curated hosted models, shall offer every curated model at the base plan, and shall pin every hosted model to the managed Jcode router route so a hosted model id never falls through to a direct provider credential.
gherkin @FR-11MustThe system shall offer exactly the curated hosted models, shall offer every curated model at the base plan, and shall pin every hosted model to the managed Jcode router route so a hosted model id never falls through to a direct provider credential. Scenario: Only the curated hosted models are offered Given the hosted model catalog When the model list is enumerated Then the list holds exactly the curated hosted models And every curated model is available at the base plan -
FR-11MustThe system shall offer exactly the curated hosted models, shall offer every curated model at the base plan, and shall pin every hosted model to the managed Jcode router route so a hosted model id never falls through to a direct provider credential.
gherkin @FR-11MustThe system shall offer exactly the curated hosted models, shall offer every curated model at the base plan, and shall pin every hosted model to the managed Jcode router route so a hosted model id never falls through to a direct provider credential. Scenario: Hosted models stay on the managed route Given a hosted model id When the route is built for that model Then the route provider is the Jcode Subscription display name And the route api method is `jcode-subscription` And the route is marked available -
FR-12MustThe system shall expose `/hosted` and its `/subscribe` alias for the hosted-model pitch, and `/hosted status` with its `/subscription` and `/subscription status` aliases for the hosted account status.
gherkin @FR-12MustThe system shall expose `/hosted` and its `/subscribe` alias for the hosted-model pitch, and `/hosted status` with its `/subscription` and `/subscription status` aliases for the hosted account status. Scenario: The hosted commands and their aliases resolve Given a running TUITerminal User Interface When the user types `/hosted` Then the hosted-model pitch is shown When the user types `/subscribe` Then the hosted-model pitch is shown When the user types `/hosted status`, `/subscription` or `/subscription status` Then the hosted account status surface is shown -
FR-13MustThe system shall show the credential state, the router base, the billing model, the runtime mode, the curated catalog and the billing rules including the tranche schedule on the hosted account status surface, and shall fetch `/v1/me` in the background to publish the account email, the billing status, the spend against the monthly limit, the amount already billed, the next tranche amount and the reset time.
gherkin @FR-13MustThe system shall show the credential state, the router base, the billing model, the runtime mode, the curated catalog and the billing rules including the tranche schedule on the hosted account status surface, and shall fetch `/v1/me` in the background to publish the account email, the billing status, the spend against the monthly limit, the amount already billed, the next tranche amount and the reset time. Scenario: The status surface explains the billing model Given a configured account credential When the hosted account status is shown Then the surface shows the credential state, the router base and the runtime mode And the surface shows the curated catalog And the surface states that charges begin at $20 and then use progressively larger tranches -
FR-13MustThe system shall show the credential state, the router base, the billing model, the runtime mode, the curated catalog and the billing rules including the tranche schedule on the hosted account status surface, and shall fetch `/v1/me` in the background to publish the account email, the billing status, the spend against the monthly limit, the amount already billed, the next tranche amount and the reset time.
gherkin @FR-13MustThe system shall show the credential state, the router base, the billing model, the runtime mode, the curated catalog and the billing rules including the tranche schedule on the hosted account status surface, and shall fetch `/v1/me` in the background to publish the account email, the billing status, the spend against the monthly limit, the amount already billed, the next tranche amount and the reset time. Scenario: The status surface publishes the live spend Given a configured account credential When `/v1/me` returns an account with a used amount, a monthly limit, a billed amount, a next tranche amount and a reset time Then the background activity shows the account email and the billing status And the background activity shows the spend against the monthly limit And the background activity shows the amount already billed and the next tranche amount -
FR-14MustThe system shall clear the local credentials and tell the user to sign in again when the hosted account status surface finds that the account key was revoked.
gherkin @FR-14MustThe system shall clear the local credentials and tell the user to sign in again when the hosted account status surface finds that the account key was revoked. Scenario: The status surface reacts to a revoked key Given a configured account credential When `/v1/me` answers unauthorized Then the local credentials are cleared And the activity says the key was revoked or expired and to sign in again -
FR-15MustThe system shall report the Jcode inference spending balance, the remaining amount against the monthly limit, the daily feature allowances and the reset time on the usage surface, shall mark the hard limit as reached when the monthly spend reaches the monthly limit, shall not mark it reached when the limit is unknown, and shall suggest an upgrade when a daily allowance passes 80 percent of its limit and an upgrade target is offered.
gherkin @FR-15MustThe system shall report the Jcode inference spending balance, the remaining amount against the monthly limit, the daily feature allowances and the reset time on the usage surface, shall mark the hard limit as reached when the monthly spend reaches the monthly limit, shall not mark it reached when the limit is unknown, and shall suggest an upgrade when a daily allowance passes 80 percent of its limit and an upgrade target is offered. Scenario: The usage surface shows the inference balance Given an account with a used amount of 12.50 and a monthly limit of 50.00 When the usage report is built Then the report has an inference spending limit row at 25 percent And the report shows the remaining amount as $37.50 And the report shows the spend as $12.50 / $50.00 -
FR-15MustThe system shall report the Jcode inference spending balance, the remaining amount against the monthly limit, the daily feature allowances and the reset time on the usage surface, shall mark the hard limit as reached when the monthly spend reaches the monthly limit, shall not mark it reached when the limit is unknown, and shall suggest an upgrade when a daily allowance passes 80 percent of its limit and an upgrade target is offered.
gherkin @FR-15MustThe system shall report the Jcode inference spending balance, the remaining amount against the monthly limit, the daily feature allowances and the reset time on the usage surface, shall mark the hard limit as reached when the monthly spend reaches the monthly limit, shall not mark it reached when the limit is unknown, and shall suggest an upgrade when a daily allowance passes 80 percent of its limit and an upgrade target is offered. Scenario: An unknown monthly limit is not exhaustion Given an account whose monthly limit is zero, negative, or not a finite number When the usage report is built Then the report does not mark the hard limit as reached And the report omits the remaining amount row -
FR-15MustThe system shall report the Jcode inference spending balance, the remaining amount against the monthly limit, the daily feature allowances and the reset time on the usage surface, shall mark the hard limit as reached when the monthly spend reaches the monthly limit, shall not mark it reached when the limit is unknown, and shall suggest an upgrade when a daily allowance passes 80 percent of its limit and an upgrade target is offered.
gherkin @FR-15MustThe system shall report the Jcode inference spending balance, the remaining amount against the monthly limit, the daily feature allowances and the reset time on the usage surface, shall mark the hard limit as reached when the monthly spend reaches the monthly limit, shall not mark it reached when the limit is unknown, and shall suggest an upgrade when a daily allowance passes 80 percent of its limit and an upgrade target is offered. Scenario: An upgrade is suggested near a daily allowance limit Given a daily memory allowance used at 850 of 1000 with an upgrade tier and an upgrade link When the usage report is built Then the report carries an upgrade row naming the tier and the link And the report does not mark the hard limit as reached -
FR-16MustThe system shall produce a subscription notice when a plan or allowance changes that names the exhausted feature, the current plan and the upgrade target with a link, and shall deliver the notice once per occurrence.
gherkin @FR-16MustThe system shall produce a subscription notice when a plan or allowance changes that names the exhausted feature, the current plan and the upgrade target with a link, and shall deliver the notice once per occurrence. Scenario: A plan limit notice names the feature and the upgrade Given a memory allowance on the Plus plan with a Pro upgrade target When the notice is rendered Then the notice names the memory recall feature and the Plus plan And the notice names the Pro upgrade target with its link And the notice is taken exactly once -
FR-17MustThe system shall expose the hosted account in the TUITerminal User Interface through `/login jcode` and `/account jcode login`, and shall expose the account status, the management page and the logout as `/account jcode status`, `/account jcode manage` and `/account jcode logout`.
gherkin @FR-17MustThe system shall expose the hosted account in the TUITerminal User Interface through `/login jcode` and `/account jcode login`, and shall expose the account status, the management page and the logout as `/account jcode status`, `/account jcode manage` and `/account jcode logout`. Scenario: The TUITerminal User Interface account commands parse to the hosted account actions Given a running TUITerminal User Interface When the user types `/account jcode login` Then the hosted account login starts When the user types `/account jcode status` Then the hosted account status is shown When the user types `/account jcode manage` Then the account management page is opened When the user types `/account jcode logout` Then the hosted account logout starts -
FR-18MustThe system shall enable the hosted runtime mode when the hosted account is activated, and shall clear the hosted runtime mode when the credentials are cleared or the user selects another provider.
gherkin @FR-18MustThe system shall enable the hosted runtime mode when the hosted account is activated, and shall clear the hosted runtime mode when the credentials are cleared or the user selects another provider. Scenario: The runtime mode follows the account state Given no hosted account When the runtime mode is read Then the hosted runtime mode is inactive When the hosted account is activated Then the hosted runtime mode is active When the credentials are cleared Then the hosted runtime mode is inactive -
FR-19ShouldThe system shall offer an email-code sign-in that sends a code to the address, keeps the code token in memory only, and reports the remaining attempts when the typed code is wrong.
gherkin @FR-19ShouldThe system shall offer an email-code sign-in that sends a code to the address, keeps the code token in memory only, and reports the remaining attempts when the typed code is wrong. Scenario: A wrong emailed code reports the remaining attempts Given a started email sign-in for an address When the user types a wrong code Then the client reports that the code is incorrect with the remaining attempt count And the client persists nothing -
FR-20ShouldThe system shall surface a hosted-model nudge when a provider rate-limits the user and after a long fully completed task, at most once per session and at most once per week, and never for a user who already holds account credentials.
gherkin @FR-20ShouldThe system shall surface a hosted-model nudge when a provider rate-limits the user and after a long fully completed task, at most once per session and at most once per week, and never for a user who already holds account credentials. Scenario: The nudge is rate limited Given the nudge was already shown this session When a rate limit happens Then no nudge line is added -
FR-21MayThe system shall accept a monthly hard cap, a billing portal session, a subscription checkout and a plan change from the account API, and shall accept only an https billing portal URL and only a Stripe Checkout URL.
gherkin @FR-21MayThe system shall accept a monthly hard cap, a billing portal session, a subscription checkout and a plan change from the account API, and shall accept only an https billing portal URL and only a Stripe Checkout URL. Scenario: Unsafe payment URLs are rejected Given the account API returns a billing portal URL that is not https When the client reads the portal URL Then the client refuses the reply Given the account API returns a checkout URL that is not a Stripe Checkout URL When the client reads the checkout URL Then the client refuses the reply -
NFR-1MustThe account key shall never appear in a URL, in a debug rendering, in a log line or in an error message, and shall be sent only in an authorization header.
gherkin @NFR-1MustThe account key shall never appear in a URL, in a debug rendering, in a log line or in an error message, and shall be sent only in an authorization header. Scenario: The account key never leaks Given a device flow and an approved login When the flow, the approval and the error renderings are formatted Then the device code, the account key and the login token do not appear And the account API request carries the key in an authorization header -
NFR-2MustThe browser approval URL shall be restricted to the allowlisted public https origins with the account path and a single flow query parameter, and the account management URL shall be restricted to the same origins, so a URL carrying credentials, a non-default port, an unexpected path or extra query parameters is rejected.
gherkin @NFR-2MustThe browser approval URL shall be restricted to the allowlisted public https origins with the account path and a single flow query parameter, and the account management URL shall be restricted to the same origins, so a URL carrying credentials, a non-default port, an unexpected path or extra query parameters is rejected. Scenario: Unsafe browser URLs are refused Given browser URLs over plain http, on a foreign host, with credentials, with a port, on a non-account path, with extra query parameters, with a fragment, and with a malformed flow value When the client validates each URL Then every one of them is refused as an invalid response -
NFR-3MustThe monthly spending limit and the model policy shall be enforced server-side by the Jcode router, and the client shall not decide from a cached tier which models an account may use or how much it may spend.
gherkin @NFR-3MustThe monthly spending limit and the model policy shall be enforced server-side by the Jcode router, and the client shall not decide from a cached tier which models an account may use or how much it may spend. Scenario: A cached tier cannot widen the hosted catalog Given a stale cached tier of Ultra on the machine When the hosted catalog is consulted Then the available hosted models are unchanged -
NFR-4MustThe account key shall be revoked on the server when the user logs out and the account API is reachable, and the local credential shall be cleared even when the revocation cannot be confirmed.
gherkin @NFR-4MustThe account key shall be revoked on the server when the user logs out and the account API is reachable, and the local credential shall be cleared even when the revocation cannot be confirmed. Scenario: Local state is cleared even when revocation fails Given a configured account credential and an account API that cannot be reached When the user logs out Then the local credential is cleared -
NFR-5MustThe account email, the account id and the spending limit shall not be sent to the telemetry service, and the only telemetry emitted for this feature shall be the coarse authentication success event.
gherkin @NFR-5MustThe account email, the account id and the spending limit shall not be sent to the telemetry service, and the only telemetry emitted for this feature shall be the coarse authentication success event. Scenario: The telemetry event carries no account data Given a completed hosted account sign-in When the telemetry event is recorded Then the event names the hosted account provider and the device-code browser method And the event carries no email, no account id and no spending limit -
NFR-6MustA failed `/v1/me` fetch shall keep the local credential and shall degrade to a quiet message rather than failing the session, and an unreachable account API during the device poll shall be retried with backoff rather than aborting the flow.
gherkin @NFR-6MustA failed `/v1/me` fetch shall keep the local credential and shall degrade to a quiet message rather than failing the session, and an unreachable account API during the device poll shall be retried with backoff rather than aborting the flow. Scenario: An unreachable account API does not lose the credential Given a configured account credential When the account status fetch fails Then the local credential is retained And the user sees a quiet message that the status could not be loaded -
NFR-7MustThe account status fetch shall use a 5 second timeout, the device authorization request shall use a 15 second timeout, and the polling backoff shall stay deterministic and bounded.
gherkin @NFR-7MustThe account status fetch shall use a 5 second timeout, the device authorization request shall use a 15 second timeout, and the polling backoff shall stay deterministic and bounded. Scenario: The polling backoff stays bounded Given a poll that returns pending, then a slow-down, then an offline error When the delay is read after each response Then the delay grows to a bounded maximum and returns to the base delay after a pending response -
NFR-8ShouldThe activation wait shall be bounded to 10 minutes, and a polling request that is already in flight shall be allowed to finish so a single-use device code is not stranded.
gherkin @NFR-8ShouldThe activation wait shall be bounded to 10 minutes, and a polling request that is already in flight shall be allowed to finish so a single-use device code is not stranded. Scenario: An in-flight exchange is allowed to finish Given a token exchange that is already in flight When the user cancels the login Then the exchange still completes and the approved key is returned -
NFR-9ShouldA user who has not signed in shall be pointed at `/login jcode`, and the hosted account status shall state plainly that hosted usage is not enabled until a spending limit exists.
gherkin @NFR-9ShouldA user who has not signed in shall be pointed at `/login jcode`, and the hosted account status shall state plainly that hosted usage is not enabled until a spending limit exists. Scenario: A signed-out user is told how to sign in Given no configured account credential When the hosted account status is shown Then the surface tells the user to sign in with `/login jcode` to set a spending limit -
NFR-10ShouldThe browser approval URL and the account management URL shall be the only links the client opens, and the client shall never open a URL returned by the account API without checking its scheme and origin.
gherkin @NFR-10ShouldThe browser approval URL and the account management URL shall be the only links the client opens, and the client shall never open a URL returned by the account API without checking its scheme and origin. Scenario: Only allowlisted origins are opened Given an account payload whose management URL points at a foreign origin or carries credentials When the client picks the management URL Then the client falls back to the public Jcode account page -
NFR-11ShouldThe account service contract shall be versioned by endpoint, and a legacy backend that only offers the old email-based login shall produce a specific compatibility error rather than a generic failure.
gherkin @NFR-11ShouldThe account service contract shall be versioned by endpoint, and a legacy backend that only offers the old email-based login shall produce a specific compatibility error rather than a generic failure. Scenario: A legacy backend gets a specific error Given the account API answers the device request with the old email-based contract When the client starts the device flow Then the client reports that the configured account API uses the legacy login contract And the response body is not echoed
Conflicts
None identified yet.
Open Questions
- The metered plan and the legacy
JcodeTierladder (Plus, Pro, Max, Ultra, Solo) both exist in the code, but only the metered plan is used for the hosted catalog and the spending limit. Should the tier ladder be retired, or kept as a separate cloud entitlement ladder asdocs/JCODE_CLOUD_AWS.mddescribes? - The
SubscriptionUsagefieldbudget_usdis the canonical name on the wire, withspend_limit_usdandlimit_usdaccepted as aliases for older servers. Should the canonical name becomespend_limit_usdso the wire field matches the user-facing "spending limit" wording? - The account API exposes
PUT /v1/billing/hard-cap,POST /v1/billing/portal,POST /v1/billing/subscribeandPOST /v1/billing/plan, but the current user flow sets the limit in the browser and never calls them from the client. Should the terminal expose a limit-setting command, or keep the browser as the only place the limit changes?
Specification: Hosted Account and Plans
Overview
The hosted account is implemented in three layers.
crates/jcode-base owns the protocol and the state: subscription_api.rs is the typed client for the account and billing API, subscription_catalog.rs owns the credential file, the plan tiers, the curated model catalog and the runtime environment, subscription_notice.rs turns a plan-allowance hit into a user-facing notice, and account_login.rs is a reusable device-authorization and email-code login that never chooses a provider and never activates billing on its own.
src/cli owns the terminal surface: src/cli/args.rs defines the jcode account subcommands, src/cli/account.rs implements status, manage and logout, and src/cli/login/jcode_device.rs orchestrates the browser-first device flow and the plan-activation wait.
crates/jcode-tui owns the interactive surface: auth_account_commands.rs parses /hosted, /subscription and /account jcode ..., auth_subscription_status.rs renders the hosted account status and the live spend, and subscribe_nudge.rs delivers the rate-limited invitation to try hosted models.
The hosted route itself is a provider in crates/jcode-base/src/provider/jcode.rs, which pins every curated model to the managed Jcode router transport, and the spending balance is reported by crates/jcode-base/src/usage/provider_fetch.rs.
This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
CLI user TUITerminal User Interface / Desktop user
| |
v v
+-------------------------------------+ +-----------------------------------+
| jcode account login|status|manage| | | /hosted /subscribe |
| logout | | /hosted status |
| src/cli/args.rs (subcommands) | | /login jcode |
| src/cli/account.rs (status, | | /account jcode status|manage| |
| manage, logout)| | logout |
| src/cli/login/jcode_device.rs | | crates/jcode-tui/.../app/ |
| (device flow + activation wait) | | auth_account_commands.rs |
| src/cli/login/jcode_device/ | | auth_subscription_status.rs |
| tests.rs | | auth.rs (jcode login/logout) |
+-------------------------------------+ | subscribe_nudge.rs |
| +-----------------------------------+
| |
+-------------------+--------------------------+
v
+---------------------------------------------------------------+
| crates/jcode-base |
| account_login.rs device flow, email code, save/current |
| subscription_api.rs typed client, /v1/me, billing, revoke |
| subscription_catalog.rs tier, catalog, credentials, env |
| subscription_notice.rs plan-limit notice, upgrade card |
| provider/jcode.rs JcodeProvider, curated route |
| usage/provider_fetch.rs inference spending balance |
+---------------------------------------------------------------+
| Authorization: Bearer <account key>
v
+---------------------------------------------------------------+
| Jcode account API https://api.jcode.sh/v1 (JCODE_API_BASE) |
| POST /v1/auth/device start the device flow |
| POST /v1/auth/token exchange the device code |
| POST /v1/auth/email/start send a sign-in code |
| POST /v1/auth/email/verify check the sign-in code |
| GET /v1/me canonical account and usage |
| DELETE /v1/keys/current revoke the account key |
| GET /v1/billing billing state |
| PUT /v1/billing/hard-cap set the monthly hard cap |
| POST /v1/billing/portal Stripe billing portal session |
| POST /v1/billing/subscribe Stripe Checkout session |
| POST /v1/billing/plan change the plan |
+---------------------------------------------------------------+
| enforces the spending limit, picks the upstream, bills
v
+---------------------------------------------------------------+
| Jcode router (server side) |
| monthly hard cap model policy tranche billing |
+---------------------------------------------------------------+
^
| curated model ids pinned to openrouter:<model>
+---------------------------------------------------------------+
| Hosted provider transport (OpenRouter runtime, |
| transport state "jcode-subscription") |
+---------------------------------------------------------------+
The credential file is the only piece of state the client owns.
jcode-subscription.env holds JCODE_API_KEY, JCODE_ACCOUNT_ID, JCODE_ACCOUNT_EMAIL and JCODE_TIER, and it is separate from JCODE_API_BASE because the base is endpoint configuration rather than a credential.
The client never enforces the spending limit and never picks an upstream.
The router does both, which is why the curated catalog is a single flat list with no client-side tier gate.
Data Models
Subscription profile
The canonical account record returned by GET /v1/me.
| Field | Type | Constraints | Description |
|---|---|---|---|
| account_id | String | not null | Stable account identifier. |
| String | not null | The account email address. | |
| tier | String | not null | Wire tier value: none, plus, pro, max, ultra or flagship. none is the metered account. |
| status | String | not null | Account status, for example active, inactive, canceled. |
| usage | SubscriptionUsage | defaults to zero | The spend against the monthly limit and the tranche state. |
| manage_url | Option\<String> | Optional, https, allowlisted origins only | The public account-management page. Never carries a secret. |
| capabilities | SubscriptionCapabilities | defaults to false | Server-verified entitlements such as voice_transcription and remote_compile. |
| jev_usage | Option\<JevUsage> | Optional | Daily allowances for the included features, memory recall and browser automation. |
Derived helpers on the profile:
| Helper | Rule |
|---|---|
parsed_tier() |
Parses tier into JcodeTier, case-insensitively. none and an unknown value both yield None. |
has_active_paid_plan() |
True when status is active and either the spending limit is above zero or a tier is present. |
checkout_was_canceled() |
True when status is canceled or cancelled. |
Subscription usage
The spending limit and the tranche state.
| Field | Type | Constraints | Description |
|---|---|---|---|
| used_usd | f64 | Default 0 | Inference spend so far in the current period. |
| budget_usd | f64 | Default 0, aliases spend_limit_usd and limit_usd |
The user-selected monthly spending limit. |
| billed_usd | f64 | Default 0 | The amount already collected in billing tranches this month. |
| next_charge_at_usd | Option\<f64> | Optional | The usage amount at which the next tranche is collected. |
| resets_at | Option\<String> | Optional, RFC 3339 | When the usage window resets. |
Account status
The rendered account state, in two shapes.
| Shape | Field | Description |
|---|---|---|
| CLI text | The account email. | |
| CLI text | Plan | The tier display name, falling back to the raw wire tier, followed by the account status. |
| CLI text | Usage | The used amount and the monthly limit, formatted as dollars. |
| CLI text | Resets | The reset timestamp, when the account reports one. |
| CLI text | Manage | The allowlisted management URL, falling back to https://jcode.sh/account. |
| CLI json | SubscriptionMe | The parsed account payload, pretty-printed. |
| TUITerminal User Interface activity | Email, Billing, Spend, Billed, Next tranche, Resets | The live account read from /v1/me on a background task. |
| TUITerminal User Interface scaffold | Credentials, Router base, Billing, Runtime mode, Catalog, Billing rules | The static status block shown before the live read completes. |
Hosted account credential
What the client persists in jcode-subscription.env.
| Field | Type | Constraints | Description |
|---|---|---|---|
| JCODE_API_KEY | String | not null, never empty, owner-only file | The account key. Sent only as a bearer token. |
| JCODE_ACCOUNT_ID | String | Optional, cleared on logout | Non-secret account identity. |
| JCODE_ACCOUNT_EMAIL | String | Optional, cleared on logout | Non-secret account identity. |
| JCODE_TIER | String | Optional, cleared on logout | The last tier the backend reported. |
| JCODE_API_BASE | String | Optional, retained on logout | The account API base URL. Endpoint configuration, not a credential. |
Plan tier
The legacy tier ladder, kept for compatibility with account servers that still answer with a tier shape.
| Field | Type | Constraints | Description |
|---|---|---|---|
| value | JcodeTier | One of Plus, Pro, Max, Ultra, Flagship | The tier. Flagship displays as Solo. |
| retail_price_usd | u32 | 10, 20, 100, 200, 1000 | The list price of the tier. |
| usable_budget_usd | f64 | Twice the retail price | The inference allowance the tier buys. |
| min_tier | JcodeTier | Plus for every curated model today |
The minimum tier that may use a curated model. |
Curated hosted model
The hosted catalog.
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | &'static str | One of claude-opus-5-5, claude-sonnet-5-5, claude-haiku-5-5, gpt-6.1-sol |
The canonical model id. |
| display_name | &'static str | not null | The name shown in the TUITerminal User Interface. |
| aliases | &'static [&'static str] | not null | The names that resolve to the id, including spaced and short forms. |
| default_enabled | bool | true only for the flagship |
The fallback when no flagship can be ranked. |
| routing_policy | UpstreamRoutingPolicy | ServerManaged |
The routing is decided server-side by the Jcode router. |
| min_tier | JcodeTier | Plus |
The minimum tier, retained for compatibility. |
| note | &'static str | not null | The one-line description shown in the status surface. |
Plan-limit notice
The notice produced when an included daily allowance is exhausted.
| Field | Type | Constraints | Description |
|---|---|---|---|
| feature | String | memory or browser in practice |
Which included feature hit its limit. |
| tier | Option\<String> | Optional | The current plan. |
| upgrade_tier | Option\<String> | Optional | The plan that raises the limit. |
| upgrade_url | Option\<String> | Optional, https and restricted to jcode.sh | Where to upgrade. |
| resets_at | Option\<String> | Optional | When the daily allowance resets. |
API Contracts
The client does not own an HTTP surface for this feature.
The contract is a set of CLI and TUITerminal User Interface commands plus the remote account API this repository consumes, so the tables below describe the callable surfaces and the remote endpoints rather than local routes.
The account API is owned by the Jcode service, and the client-side contract is the typed wrapper in crates/jcode-base/src/subscription_api.rs.
CLI surface
| Command | Purpose |
|---|---|
jcode account login [--no-browser] |
Run the browser device authorization, then wait for plan activation. --no-browser prints the public approval URL instead of opening a browser. |
jcode account status [--json] |
Report the canonical account, the plan and the usage from /v1/me. |
jcode account manage |
Open https://jcode.sh/account in the browser, or print the URL when browser launch is suppressed. |
jcode account logout |
Revoke the key when reachable, then always clear the local credential and cache. |
TUITerminal User Interface surface
| Command | Purpose |
|---|---|
/hosted |
Show the hosted-model pitch: no subscription, a user-controlled monthly limit, milestone warnings, and the curated catalog. |
/subscribe |
Alias for /hosted. |
/hosted status |
Show the hosted account status, the router configuration and the billing rules. |
/subscription, /subscription status |
Aliases for /hosted status. |
/login jcode, /account jcode login |
Start the hosted account login in the TUITerminal User Interface. |
/account jcode status |
Show the hosted account status. |
/account jcode manage |
Open the account management page. |
/account jcode logout |
Revoke the key when reachable and clear the local credential. |
/usage |
Show the inference spending balance and the daily feature allowances. |
Account API
| Method | Path | Purpose |
|---|---|---|
| POST | /v1/auth/device | Start a device authorization. Body: {"client_name":"jcode-cli"}. |
| POST | /v1/auth/token | Exchange the device code. Body: {"device_code":"..."}. |
| POST | /v1/auth/email/start | Send a sign-in code. Body: {"client_name":"jcode-cli","email":"..."}. |
| POST | /v1/auth/email/verify | Check the sign-in code. Body: {"login_token":"...","code":"..."}. |
| GET | /v1/me | The canonical account, the usage and the plan. Bearer auth. |
| DELETE | /v1/keys/current | Revoke the account key. Bearer auth. |
| GET | /v1/billing | The billing state, the monthly hard cap and the period spend. Bearer auth. |
| PUT | /v1/billing/hard-cap | Set the monthly hard cap in whole cents. Bearer auth. |
| POST | /v1/billing/portal | Create a Stripe billing portal session. Bearer auth. |
| POST | /v1/billing/subscribe | Create a Stripe Checkout session for a monthly plan. Bearer auth. |
| POST | /v1/billing/plan | Change the plan of an active subscription. Bearer auth. |
Error codes shared across endpoints:
| Status | Code | Description |
|---|---|---|
| 400 | authorization_pending, pending |
The browser approval has not happened yet. The client keeps polling. |
| 400 | slow_down |
The client is polling too fast. The client backs off. |
| 400 | expired_token, expired, expired_device_code |
The device code is gone. The client starts a new flow. |
| 400 | access_denied, denied |
The user denied the request in the browser. |
| 400 | invalid_code |
The emailed sign-in code is wrong. The response may carry attempts_remaining. |
| 401 | - | The account key is revoked or expired. The client clears the local credential. |
| 403 | - | The account request was denied. |
| 404 | - | The configured account API uses the legacy email-based contract. |
| 428 | - | The device flow is still pending approval. |
| 429 | - | The client is polling too fast. The Retry-After header sets the next delay. |
| 5xx | - | The account service is temporarily unavailable. The client retries with backoff. |
Sequences
Sign in
sequenceDiagram
autonumber
participant U as User
participant C as jcode account login
participant A as Jcode account API
participant S as jcode-subscription.env
U->>C: jcode account login
C->>A: POST /v1/auth/device {"client_name":"jcode-cli"}
A-->>C: device_code, verification_uri_complete, expires_in, interval
C->>U: open the approval URL in the browser
loop every interval, with backoff
C->>A: POST /v1/auth/token {"device_code":"..."}
A-->>C: pending, slow_down, denied, expired, or approved
end
C->>S: write JCODE_API_KEY, JCODE_ACCOUNT_ID, JCODE_ACCOUNT_EMAIL, JCODE_TIER
S-->>C: owner-only file
C->>U: account approved, credential saved
Activate the plan
sequenceDiagram
autonumber
participant U as User
participant C as jcode account login
participant A as Jcode account API
U->>C: set a monthly spending limit in the browser
loop every interval, bounded by the activation timeout
C->>A: GET /v1/me (bearer)
A-->>C: status active with a spending limit, canceled, or no plan yet
end
alt active plan
C->>U: hosted models are ready with the monthly limit
else canceled
C->>U: billing setup was canceled, the key stays saved
else timeout
C->>U: no spending limit detected, the key stays saved
else revoked or denied
C->>C: clear the local credentials
C->>U: sign in again
end
Switch to hosted models
sequenceDiagram
autonumber
participant U as User
participant T as TUITerminal User Interface
participant P as JcodeProvider
participant R as Jcode router
U->>T: /hosted status
T->>T: show the scaffold and fetch /v1/me in the background
T-->>U: email, billing status, spend against the limit, next tranche
U->>T: /model claude-opus-5-5
T->>P: set_model
P->>P: pin the model to openrouter:claude-opus-5-5
P->>R: inference request with the account bearer key
R->>R: enforce the monthly hard cap and the model policy
R-->>P: the completion
Log out
sequenceDiagram
autonumber
participant U as User
participant C as jcode account logout
participant A as Jcode account API
participant S as jcode-subscription.env
U->>C: jcode account logout
C->>A: DELETE /v1/keys/current (bearer)
A-->>C: revoked, already revoked, or unreachable
C->>S: clear the key, the account id, the email and the tier
C->>C: clear the hosted runtime environment
C-->>U: report the outcome of each step
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Sign-in protocol | Browser device authorization | No secret is typed in the terminal and no email is sent, so the terminal never handles a credential the user could paste somewhere unsafe. |
| Client name on the device request | Always jcode-cli |
The deployed API rejects jcode-desktop with HTTP 400, so Desktop reuses the shared contract rather than an unrecognized name. |
| Where the spending limit is set | The browser at https://jcode.sh/account |
The limit is a billing decision, and the account page already holds the payment method. The terminal stays a reader of the limit, not a writer. |
| Where the limit is enforced | Server-side in the Jcode router | A client-enforced limit can be bypassed by a modified client. The client therefore only reports the limit, never gates on it. |
| Client-side model gating | Flat curated catalog, no tier gate | A stale cached tier must never hide a router-supported model, so the tier ladder is kept for compatibility but does not filter the catalog. |
| Route pinning | Every hosted model becomes openrouter:<model> |
Hosted model ids overlap with direct provider ids, so a bare id would let the family heuristic escape to the user's own Anthropic or OpenAI credentials. |
| Runtime mode | An environment flag set when the hosted provider is constructed | The flag is what tells the rest of the runtime that the managed transport is live, and clearing it is what makes the opt-out immediate. |
| Credential storage | One owner-only env file next to the other provider keys | The account key then reuses the existing secret writer, permission hardening and clearing paths rather than introducing a second store. |
| API base retention on logout | Retained | The API base is endpoint configuration, not an authorization credential, so clearing it would break a self-hosted account setup for no security gain. |
| Local cleanup on logout | Unconditional and first-class | The CLI can always enforce the local security boundary, even offline, so remote revocation is treated as best effort. |
| URL validation | Allowlist of public origins plus a shape check | A URL returned by the account service is untrusted input, so the client checks the scheme, the host, the port, the path, the query and the fragment before opening it. |
| Plan-limit notices | A single remembered notice, taken once | A busy background feature must not spam the transcript, and one card per session keeps the surface readable. |
| Upgrade path | Always the browser | Nothing is purchased in-app, so the upgrade card opens the pricing page rather than embedding a payment flow. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Only the coarse auth_success event |
The account email and the spending limit are personal and financial data, so they never leave the machine. |
Risks and Unknowns
- The metered plan and the legacy
JcodeTierladder are both live in the code, and only the metered plan drives the catalog and the limit. The ladder is currently only exercised by compatibility tests. budget_usdis the canonical wire name for the spending limit while the user-facing wording is "spending limit", and the older namesspend_limit_usdandlimit_usdare still accepted as aliases.- The account API exposes a full billing surface (hard cap, portal, checkout, plan change) that the current user flow never calls, because the browser owns the limit. Those endpoints are tested but not reachable from a command.
- The hosted model catalog is a static list in the client. Adding a model is a client release, and the router may support models the client cannot name.
- The activation wait depends on the account service reporting an active plan within 10 minutes. A slow checkout leaves the user with a saved key and no hosted routing until they retry.
- A single-use device code can be consumed by a canceled exchange, so a canceled login requires a new flow rather than a resume.
- The email-code sign-in path exists in the shared library but is not wired to a TUITerminal User Interface or CLI command, so it is exercised only by library tests.
- There are no dedicated
subscription_*telemetry events. The only signal for this feature is the coarseauth_successevent with the hosted provider and the device-code browser method, so plan changes and limit changes are not measurable in aggregate.
Out of Scope
- The Jcode account service itself, its storage, its billing and its router implementation.
- The Jcode Cloud control plane, the host provisioning and the cloud entitlement ladder described in
docs/JCODE_CLOUD_AWS.md. - The Stripe billing portal, checkout and plan-change flows, which the client can call but does not expose.
- The hosted model catalog contents, which the server owns and the client mirrors.
- The Desktop rendering of the hosted account surfaces, which lives outside this repository.
Test Plan: Hosted Account and Plans
Scope
Covers the hosted account and plan surface: the device-authorization and email-code sign-in, the account API client, the account credential store, the curated hosted model catalog and its route, the spending balance and daily allowances, the plan-limit notice, the TUITerminal User Interface account commands and the hosted account status surface, and the CLI jcode account subcommands.
Out of scope: the account service itself, the Jcode router that enforces the spending limit server-side, the Stripe billing portal and checkout flows beyond the client-side URL checks, the Jcode Cloud control plane, and the Desktop rendering of the account surfaces.
Every test listed below exists in the repository today. The table names the file and the test function for each case, so a reader can run one directly.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Curated model alias resolution in crates/jcode-base/src/subscription_catalog.rs (curated_model_aliases_resolve_to_canonical_ids) |
"opus 5.5", "Claude Opus 5.5", "sonnet 5.5", "haiku 5.5", "sol", "GPT 6.1 Sol", "unknown-model" |
Each known alias resolves to its canonical id, and an unknown model resolves to nothing |
| TC-2 | Retired and unsupported model rejection in crates/jcode-base/src/subscription_catalog.rs (retired_models_and_unsupported_generations_are_not_curated) |
A list of 30 retired Claude, GPT and open-weight model ids, each also with an @provider suffix |
None of them is curated and none is allowed for the current tier |
| TC-3 | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). pin suffix handling in crates/jcode-base/src/subscription_catalog.rs (curated_model_lookup_ignores_provider_pin_suffix) |
"claude-opus-5-5@anthropic", "gpt-6.1-sol@openai" |
Both resolve to their canonical curated ids |
| TC-4 | Default hosted model selection in crates/jcode-base/src/subscription_catalog.rs (default_model_is_newest_curated_flagship) |
The curated catalog | The default model is the ranked Claude flagship, claude-opus-5-5 |
| TC-5 | Exact hosted catalog shape in crates/jcode-base/src/subscription_catalog.rs (curated_catalog_has_exact_hosted_set_without_legacy_model_gates) |
The curated catalog | Exactly four models are gated at Plus, none at Ultra, none at Flagship, and unknown models such as magistral-small-1.2 are absent |
| TC-6 | Tier pricing table in crates/jcode-base/src/subscription_catalog.rs (tier_pricing_matches_launched_plans) |
The five tiers | Each tier keeps its wire id, display name, retail price, usable budget, included inference and overage multiplier; Flagship displays as Solo |
| TC-7 | Tier parsing in crates/jcode-base/src/subscription_catalog.rs (tier_parse_round_trips) |
Every tier id in mixed case and with surrounding spaces, plus "solo" and "starter" |
Every tier id round-trips, solo maps to Flagship, and an unknown tier parses to nothing |
| TC-8 | Tier ordering in crates/jcode-base/src/subscription_catalog.rs (tier_gating_follows_catalog_order) |
Every pair of tiers | A tier allows exactly the tiers at or below it in the ladder |
| TC-9 | Base-plan availability in crates/jcode-base/src/subscription_catalog.rs (every_hosted_model_is_available_from_the_base_subscription) |
Every curated model and every tier | Every curated model is gated at Plus and is allowed from every tier |
| TC-10 | Cached tier independence in crates/jcode-base/src/subscription_catalog.rs (hosted_catalog_access_does_not_depend_on_legacy_cached_tier) |
No cached tier, an unreadable cached tier, Pro, Max, Ultra, then a persisted Flagship |
The available hosted models never change, and the cached tier is cleared and restored cleanly |
| TC-11 | Runtime mode flag in crates/jcode-base/src/subscription_catalog.rs (runtime_mode_flag_tracks_subscription_activation) |
Runtime env cleared, then applied, then cleared | The hosted runtime mode is inactive, then active, then inactive again |
| TC-12 | Upgrade card validity in crates/jcode-base/src/subscription_notice.rs (upgrade_card_is_a_valid_applet_with_upgrade_button) |
A browser-allowance notice on the Plus plan with a Pro upgrade target | The card validates against the agent manifest, names the feature and the plan, carries an Upgrade to Pro button that opens the pricing URL, and is mounted inline at the end of the session |
| TC-13 | Top-tier card in crates/jcode-base/src/subscription_notice.rs (top_tier_card_has_no_upgrade_button) |
The same notice without an upgrade target | The card still validates, carries no open-url button, and offers a dismiss button instead |
| TC-14 | Notice wording in crates/jcode-base/src/subscription_notice.rs (upgrade_prompt_names_plan_feature_and_link) |
A notice with an upgrade target | The rendered text names the browser automation feature, the Plus plan, the Pro upgrade, the pricing link and the 24 hour reset |
| TC-15 | Top-tier wording in crates/jcode-base/src/subscription_notice.rs (top_tier_gets_reset_message_without_upsell) |
A notice without an upgrade target | The text mentions the reset and contains no upgrade upsell |
| TC-16 | Notice lifetime in crates/jcode-base/src/subscription_notice.rs (notice_is_recoverable_from_anyhow_chain_and_taken_once) |
A notice wrapped in an anyhow error chain, then recorded |
The notice is found in the chain, is taken once, and is gone on the second take |
| TC-17 | Hosted provider runtime mode in crates/jcode-base/src/provider/jcode.rs (jcode_provider_enables_subscription_runtime_mode) |
A new JcodeProvider |
The hosted runtime mode becomes active and every offered model is a curated model |
| TC-18 | Hosted provider identity in crates/jcode-base/src/provider/jcode.rs (jcode_provider_name_and_default_model_are_curated) |
A new JcodeProvider |
The provider is named Jcode Subscription and its default model is curated |
| TC-19 | Managed transport pinning in crates/jcode-base/src/provider/jcode.rs (jcode_models_are_pinned_to_the_managed_transport) |
claude-opus-5-5, claude-haiku-5-5, gpt-6.1-sol |
Each becomes openrouter:<model>, so the id never reaches a direct provider credential |
| TC-20 | Hosted route table in crates/jcode-base/src/provider/jcode.rs (jcode_provider_exposes_only_explicit_subscription_routes) |
Routes for the Plus and Flagship tiers |
Exactly four routes are exposed, all with provider Jcode Subscription, api method jcode-subscription and available set, and the two tiers produce identical routes |
| TC-21 | Curated model guard in crates/jcode-base/src/provider/tests/catalog_subscription.rs (test_subscription_model_guard_allows_only_curated_models_when_enabled) |
The curated ids and aliases, then 30 retired ids, with the runtime mode active | Every curated id and alias is allowed and every retired id is refused |
| TC-22 | Tier-independent hosted guard in crates/jcode-base/src/provider/tests/catalog_subscription.rs (test_hosted_model_guard_does_not_gate_models_by_legacy_tier) |
A stale cached tier of ultra with the runtime mode active |
The curated models stay available, so a stale tier cannot change client-side availability |
| TC-23 | Display model filtering in crates/jcode-base/src/provider/tests/catalog_subscription.rs (test_filtered_display_models_respects_curated_subscription_catalog) |
A list mixing curated and unknown model ids | The display list holds only the curated models, before and after a stale tier is set |
| TC-24 | Remote route fallback in crates/jcode-base/src/provider/tests/catalog_subscription.rs (test_remote_jcode_subscription_fallback_keeps_managed_route_identity) |
A remote route fallback built for the hosted provider | The four curated models are returned, each with the hosted provider display name, the jcode-subscription api method and available set |
| TC-25 | Saved credential does not activate the filter in crates/jcode-base/src/provider/tests/catalog_subscription.rs (test_subscription_filters_do_not_activate_from_saved_credentials_alone) |
A saved account key with the runtime mode cleared | The model filters stay inactive, so a saved credential alone does not switch routing |
| TC-26 | Inference balance rendering in crates/jcode-base/src/usage/tests.rs (jcode_usage_shows_monthly_inference_spending_and_remaining) |
An account with $12.50 used of a $50.00 limit and a reset time | The report has an Inference spending limit (monthly) row at 25 percent with the reset time, shows $37.50 remaining and $12.50 / $50.00 spent, and does not mark the limit reached |
| TC-27 | Limit exhaustion in crates/jcode-base/src/usage/tests.rs (jcode_usage_monthly_limit_exhaustion_clamps_remaining) |
$50.00 and $60.00 spent against a $50.00 limit | The hard limit is marked reached and the remaining amount is clamped to $0.00 |
| TC-28 | Unknown limit in crates/jcode-base/src/usage/tests.rs (jcode_usage_unknown_monthly_budget_is_not_exhausted) |
A limit of 0, -1, NaN and infinity | The hard limit is never marked reached and the remaining amount row is omitted, while a daily allowance overrun still marks it reached |
| TC-29 | Daily allowances without upsell in crates/jcode-base/src/usage/tests.rs (jcode_usage_shows_daily_allowances_without_upsell_when_low) |
A memory allowance at 100 of 1000 with an upgrade target available | The report is named Jcode subscription, lists the daily allowance at 10 percent, and carries no upgrade row while the allowance is low |
| TC-30 | Upgrade hint near the allowance limit in crates/jcode-base/src/usage/tests.rs (jcode_usage_suggests_upgrade_near_and_at_the_limit) |
A memory allowance at 850 of 1000, then at 1000, then at 1000 on the top plan | The near-limit case carries an upgrade row with the pricing link and is not exhausted, the at-limit case is exhausted, and the top plan carries no upgrade row |
| TC-31 | Older gateway tolerance in crates/jcode-base/src/usage/tests.rs (jcode_usage_tolerates_older_gateways_without_jev_usage) |
An account payload with no jev_usage |
The report has no limit rows and still reports the plan name |
| TC-32 | Management URL allowlist in src/cli/account.rs (manage_url_accepts_only_public_allowlisted_https_origins) |
https://jcode.sh/account, a foreign origin carrying a key, and a URL with embedded credentials |
The allowlisted URL is kept and the other two fall back to the public account page |
| TC-33 | Credential file lifecycle in src/cli/login/jcode_device/tests.rs (approved_key_persistence_is_owner_only_and_clear_is_deterministic) |
An approved key persisted into an isolated JCODE_HOME, then cleared |
The file holds the key with mode 0600, and after clearing it holds neither the key, the account id nor the email |
| TC-34 | Revoked key messaging in crates/jcode-tui/src/tui/app/auth_subscription_status_tests.rs (revoked_account_reports_successful_cleanup) |
A successful local cleanup | The message says the credentials were cleared and points at /account jcode login |
| TC-35 | Failed cleanup messaging in crates/jcode-tui/src/tui/app/auth_subscription_status_tests.rs (revoked_account_does_not_claim_failed_cleanup_succeeded) |
A cleanup that fails with a permission error | The message reports the error, points at /account jcode logout, and does not claim the credentials were cleared |
| TC-36 | Hosted account command parsing in crates/jcode-tui/src/tui/app/auth_account_commands.rs (parse_native_jcode_account_actions) |
/account jcode login, /account jcode status, /account jcode manage, /account jcode logout |
Each parses to the matching hosted account action |
| TC-37 | Nudge weekly gate in crates/jcode-tui/src/tui/app/subscribe_nudge.rs (weekly_gate_blocks_within_a_week_and_allows_after) |
A never-shown state, a state shown a week ago, one shown just under a week ago, and a clock that went backwards | The gate allows the first two, blocks the third, and saturates rather than wrapping on the backwards clock |
| TC-38 | Long-task qualification in crates/jcode-tui/src/tui/app/subscribe_nudge.rs (long_task_qualification_requires_all_completed_and_gated_confidence) |
An empty list, an in-progress item, a low completion confidence, a missing confidence, and a fully completed list | Only the fully completed list with a passing confidence qualifies |
| TC-39 | Long-task message wording in crates/jcode-tui/src/tui/app/subscribe_nudge.rs (long_task_message_reads_support_wording_with_elapsed) |
83 minutes and 1 hour | The message reads jcode just worked 1h 23m for you. Try Jcode hosted models: /hosted and the shorter durations format as 59m and 1h |
| TC-40 | Rate-limit nudge copy in crates/jcode-tui/src/tui/app/subscribe_nudge.rs (rate_limit_copy_leads_with_the_hosted_model_value_prop) |
The shared nudge line | The line leads with the hosted-model value proposition and names /hosted |
| TC-41 | Hosted pitch content in crates/jcode-tui/src/tui/app/subscribe_nudge.rs (pitch_explains_limits_warnings_tranches_and_next_step) |
The rendered pitch | The pitch states that there is no subscription, names the monthly spending limit, the warnings, the $20 start, the progressively larger tranches, the month-end collection, that the software stays open source, and points at /login jcode and /usage, and lists every curated model |
| TC-42 | Elapsed formatting in crates/jcode-tui/src/tui/app/subscribe_nudge.rs (elapsed_formatting_covers_minute_and_hour_shapes) |
61 minutes, 2 hours, 45 minutes | They format as 1h 1m, 2h and 45m |
| TC-43 | TUITerminal User Interface logout credential clearing in crates/jcode-tui/src/tui/app/auth_tests.rs (tui_jcode_subscription_logout_clears_credentials_and_preserves_api_base) |
A saved key, account id, email and API base | The key, account id and email are cleared, the API base is retained, and no credential is left in the environment or in the env file |
| TC-44 | Browser URL validation in crates/jcode-base/src/account_login/tests.rs (rejects_unsafe_browser_urls) |
Eleven URLs: plain http, a foreign host, a userinfo host, embedded credentials, an explicit port, a non-account path, an extra query parameter, a fragment, a percent-encoded newline, a one-character flow value and a missing flow value | Every one of them is refused as an invalid response |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-45 | Device request contract in crates/jcode-base/src/subscription_api.rs (device_request_uses_new_contract_and_parses_public_urls) |
A scripted server that answers the device request | The device code, flow id, verification URI and interval are parsed, and the verification URL does not contain the device secret |
| TC-46 | No tier selection on the device request in crates/jcode-base/src/subscription_api.rs (metered_device_request_does_not_select_a_subscription_tier) |
A server that captures the request body | The body is exactly {"client_name":"jcode-cli"} and carries no requested_tier |
| TC-47 | Legacy backend detection in crates/jcode-base/src/subscription_api.rs (legacy_device_response_is_explained_without_echoing_body) |
A server that answers with the old verify_url shape |
The client reports the legacy login contract and does not echo the device code from the body |
| TC-48 | Token poll outcomes in crates/jcode-base/src/subscription_api.rs (token_poll_handles_pending_slow_down_success_denied_and_replay) |
A server that answers with 428, 429 with Retry-After: 9, an approval, a denial and an expiry |
Each status maps to its own outcome: pending, slow down with the header delay, approved, denied and expired |
| TC-49 | Revoked key classification in crates/jcode-base/src/subscription_api.rs (me_and_revoke_classify_revoked_keys_without_leaking_them) |
A server that answers 401 with a body naming the key | Both the account read and the revocation report an unauthorized key, and neither message contains the key |
| TC-50 | Billing and portal handling in crates/jcode-base/src/subscription_api.rs (billing_cap_and_portal_parse_and_reject_unsafe_urls) |
A server that answers the billing read, the hard-cap write, an https portal URL, a non-https portal URL and a 409 | The cap converts to dollars, the period spend and the promotional credit convert correctly, the cap write returns the new value, the https portal URL is accepted, and the non-https URL and the 409 are refused with their code |
| TC-51 | Checkout and plan change in crates/jcode-base/src/subscription_api.rs (checkout_and_plan_change_only_accept_safe_replies) |
A server that answers with a Stripe Checkout URL, a non-Stripe URL, a plan change and a 409 | The Stripe URL is accepted, the non-Stripe URL is refused as an invalid response, the plan change returns the plan, the limit and the effective moment, and the 409 is surfaced with its code |
| TC-52 | Account payload shape in crates/jcode-base/src/subscription_api.rs (subscription_me_parses_expected_shape) |
A /v1/me payload with a tier, a status, a usage block and a management URL |
The tier parses, the capabilities default to false, the account counts as an active paid plan, and the management URL is read |
| TC-53 | Metered payload shape in crates/jcode-base/src/subscription_api.rs (metered_account_parses_spending_limit_and_tranche_state_without_a_tier) |
A payload with tier: "none", spend_limit_usd, billed_usd and next_charge_at_usd |
The limit is read through the spend_limit_usd alias, the billed and next-charge amounts are read, no tier is parsed, and the account still counts as an active paid plan |
| TC-54 | Polling backoff in crates/jcode-base/src/subscription_api.rs (polling_backoff_is_deterministic_and_bounded) |
A backoff with a 3 second base | The delay goes from 3 to 8 to 12 seconds, then to 24 and 30 seconds on offline errors, and back to 3 seconds after a pending answer |
| TC-55 | Device flow wire contract in crates/jcode-base/src/account_login/tests.rs (account_only_start_and_approval_use_expected_wire_contract) |
A scripted server that answers the device request and the token exchange | The flow exposes the public approval URL, the interval and the expiry, the device request body is exactly {"client_name":"jcode-cli"}, the token body carries the device code, the device secret and the account key never appear in the debug rendering, and exactly two requests are made with no account read, provider selection or checkout |
| TC-56 | Poll result separation in crates/jcode-base/src/account_login/tests.rs (pending_slowdown_denial_and_expiry_are_separate_results) |
A scripted server that answers pending, a Retry-After: 12 slow down, a slow down with no header, a denial and an expiry |
Each answer maps to its own result, the slow down uses the header delay and otherwise falls back to the interval plus 5 seconds, and a locally expired flow makes no HTTP request |
| TC-57 | Redaction of hostile bodies in crates/jcode-base/src/account_login/tests.rs (malicious_error_bodies_and_malformed_responses_are_redacted) |
A server that answers with a 500 whose body embeds the secret, a bare secret body, and a device response pointing at a foreign host | Every error rendering is free of the secret, and an offline error carrying a secret-bearing URL is redacted and reported as temporary |
| TC-58 | Save and account read in an isolated home in crates/jcode-base/src/account_login/tests.rs (explicit_save_and_current_account_are_sandboxed_without_paid_plan) |
An isolated JCODE_HOME, a cleared environment, and a scripted account API |
No credential exists before the approval, the credential exists after the save, the hosted runtime mode stays off, the credential survives the removal of the process variables, the file sits under the isolated home with mode 0600, the account read returns the account and reports no active paid plan, and an unauthorized answer leaves the credential in place |
| TC-59 | Cancellation of an in-flight poll in crates/jcode-base/src/account_login/tests.rs (in_flight_poll_is_cancellable_without_a_detached_worker) |
A server that accepts the token request and never answers | The poll task is aborted without waiting for the request timeout, and no detached worker is left behind |
| TC-60 | Live deployed device flow in crates/jcode-base/src/account_login/tests.rs (deployed_account_start_and_pending_are_compatible) |
The JCODE_ACCOUNT_TEST_API_BASE environment variable, #[ignore]d by default |
The live flow starts with an https approval URL and the first poll is pending |
| TC-61 | Email code sign-in contract in crates/jcode-base/src/account_login/tests.rs (email_code_sign_in_uses_expected_wire_contract) |
A scripted server that answers the code request, a wrong code, an approval and an expiry | The address is normalized, the code length is read, the login token never appears in the debug rendering, the request bodies carry the client name, the email, the code and the token, a wrong code reports the remaining attempts, a code with separators is accepted, and a used code reports an expiry |
| TC-62 | Gmail search link in crates/jcode-base/src/account_login/tests.rs (gmail_link_searches_for_our_sender_including_spam) |
An address with surrounding spaces and mixed case | The link targets the normalized address, the login@solosystems.dev sender, in:anywhere and a one-day window |
| TC-63 | Device poll approval in src/cli/login/jcode_device/tests.rs (polling_pending_slow_down_then_approval) |
A scripted server that answers pending, a slow down with Retry-After: 1, then an approval |
The poll returns the approved account id, email and tier |
| TC-64 | Denial redaction in src/cli/login/jcode_device/tests.rs (polling_denied_has_clear_redacted_error) |
A scripted server that answers a denial whose body carries the device secret | The error says the login was canceled or denied and does not contain the device secret |
| TC-65 | Deterministic timeout in src/cli/login/jcode_device/tests.rs (polling_timeout_is_deterministic_before_first_request) |
An unreachable endpoint with a 1 second expiry and a 2 second interval | The poll fails with a timeout message before making a request |
| TC-66 | Cancellation during a consumed exchange in src/cli/login/jcode_device/tests.rs (cancellation_during_consumed_exchange_finishes_and_returns_the_key) |
A server that answers the token request after 300 ms while the cancel fires after 1100 ms | The exchange still finishes and the approved key is returned, so the single-use device code is not stranded |
| TC-67 | Plan quota upgrade prompt in crates/jcode-base/src/jev/transport_tests.rs (gateway_plan_quota_is_not_retried_and_becomes_upgrade_prompt) |
A mock gateway that answers 429 with a plan quota and an upgrade target | The error carries a typed notice naming the feature, the current tier and the upgrade tier with the pricing link, and the gateway is called once for the preflight and once for the decision, so plan quotas are never retried |
| TC-68 | Upgrade link origin check in crates/jcode-base/src/jev/transport_tests.rs (gateway_quota_rejects_non_jcode_upgrade_links) |
A mock gateway whose quota carries an upgrade URL on a foreign host | The notice drops the upgrade link and the error text does not contain the foreign host |
End-to-End Tests
| ID | Description | Steps | Expected Outcome |
|---|---|---|---|
| TC-69 | The hosted account status surface in crates/jcode-tui/src/tui/app/tests/commands_accounts_01/part_02.rs (test_subscription_command_shows_jcode_status_scaffold) |
With the runtime mode cleared and no credential or API base configured, type /subscription and submit |
A system message is shown that names the hosted model status, states the pay-as-you-go model with no subscription fee, names the monthly spending limit and the progressively larger tranches, points at /login jcode, lists all four curated models, and mentions none of the retired models, the old monthly price wording or the old budget wording |
| TC-70 | The hosted model pitch in crates/jcode-tui/src/tui/app/tests/commands_accounts_01/part_02.rs (test_subscribe_command_shows_hosted_pitch_and_next_step) |
Type /subscribe and submit |
A system message is shown that names the hosted models, states there is no subscription, names the monthly spending limit, the open-source statement, the $20 start and the progressively larger tranches, and points at /login jcode and /usage |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-71 | The approval URL is over plain http, on a foreign host, with a userinfo host, with embedded credentials, with an explicit port, on a non-account path, with an extra query parameter, with a fragment, with a percent-encoded newline in the flow value, with a one-character flow value, or with no flow value at all | Every one of them is refused as an invalid response, so no browser ever opens an untrusted URL (TC-44) |
| TC-72 | The device code expires, the user denies the request, the server asks the client to slow down, or the flow expires locally | Each case maps to its own distinct result, and a locally expired flow makes no HTTP request (TC-48, TC-56) |
| TC-73 | The account API answers with a body that embeds the device secret, the account key or a secret-bearing URL | The secret never appears in the error rendering, and the error is classified as temporary when it is an offline error (TC-47, TC-49, TC-57) |
| TC-74 | The user cancels the login while the token exchange is already in flight | The exchange is allowed to finish and the approved key is returned, because the device code is single use (TC-59, TC-66) |
| TC-75 | The account API cannot be reached during the device poll | The poll retries with a bounded backoff, and the flow fails with a timeout message rather than an unhandled network error (TC-54, TC-65) |
| TC-76 | The account key was revoked or expired | The local credentials are cleared, the user is told to sign in again, and a failed local cleanup is reported as a failure rather than a success (TC-34, TC-35, TC-49) |
| TC-77 | The account API is unreachable during the logout | The local credential, account id, email and tier are still cleared, and the API base is retained (TC-33, TC-43) |
| TC-78 | The monthly limit is zero, negative, NaN or infinite | The hard limit is never marked reached and the remaining amount row is omitted, so an unknown limit never reads as an exhausted one (TC-28) |
| TC-79 | The account payload carries a management URL on a foreign origin or with embedded credentials | The client falls back to the public Jcode account page (TC-32) |
| TC-80 | The account API returns a billing portal URL that is not https, or a checkout URL that is not a Stripe Checkout URL | The reply is refused as an invalid response, so the client never opens a non-Stripe or non-https payment URL (TC-50, TC-51) |
| TC-81 | The configured account API still offers the old email-based login contract | The client reports a specific compatibility error naming the current endpoint, and does not echo the response body (TC-47) |
| TC-82 | The account API is unreachable for the whole activation window | The key stays saved and the recovery commands are printed, so a slow checkout never destroys a valid credential (not covered by a test, see gap G-3) |
| TC-83 | A stale cached tier of ultra or flagship is on the machine |
The available hosted models do not change, because the router owns the model policy (TC-10, TC-22, TC-23) |
| TC-84 | The user already holds account credentials when a hosted-model nudge would fire | The nudge is suppressed, and the weekly gate blocks a second nudge inside the same week (TC-37) |
Test Infrastructure
- Scripted HTTP servers back every network test.
crates/jcode-base/src/account_login/tests.rshas aserverhelper that binds a loopback listener and answers a scripted list of statuses, headers and bodies, capturing each request for assertions.crates/jcode-base/src/subscription_api.rshas aspawn_serverhelper with the same shape.src/cli/login/jcode_device/tests.rshas aspawn_scripted_http_serverhelper.crates/jcode-base/src/jev/transport_tests.rshas amock_serverhelper for the plan-quota cases. - Every client in these tests is built with
reqwest::Client::builder().no_proxy(), so a proxy in the environment cannot intercept the loopback server. - Environment isolation uses
crate::storage::lock_test_env(), an isolatedJCODE_HOMEpointing at atempfile::tempdir(), and anEnvGuardthat saves and restoresJCODE_API_KEY,JCODE_API_BASE,JCODE_ACCOUNT_ID,JCODE_ACCOUNT_EMAIL,JCODE_TIERandJCODE_SUBSCRIPTION_ACTIVEaround the test. - Credential permission assertions run only on Unix, where the file mode is compared against
0o600. - The one live test against the deployed account service,
deployed_account_start_and_pending_are_compatible, is#[ignore]d and only runs whenJCODE_ACCOUNT_TEST_API_BASEis set explicitly. - The TUITerminal User Interface tests build the app with the shared
create_test_app()helper from the TUITerminal User Interface test support and drive it by setting the input and callingsubmit_input(). - The hosted-model nudge code path is disabled in test builds on purpose, so its tests assert the copy and the gate rather than the rendered message.
Coverage Gaps
- The CLI entry points
jcode account status,jcode account manageandjcode account logouthave no test of their own. Only their helpers are covered: the management URL allowlist insrc/cli/account.rsand the credential clearing insrc/cli/login/jcode_device/tests.rsandcrates/jcode-tui/src/tui/app/auth_tests.rs. The text and JSON rendering ofjcode account statusis untested. subscription_api::poll_for_paid_activationhas no test. Its inputs and outcomes are covered only indirectly, throughhas_active_paid_planand the/v1/mefetch, andcheckout_was_canceledis not asserted anywhere.- The CLI device login orchestration in
src/cli/login/jcode_device.rsis covered at the polling level, but the four activation outcomes oflogin_jcode_device_floware not. - The TUITerminal User Interface background read of
/v1/meand theUiActivitypublication incrates/jcode-tui/src/tui/app/auth_subscription_status.rsis not tested, only the revoked-key message helper next to it. usage::provider_fetch::fetch_jcode_usage_reporthas no test of its network path, only the purejcode_usage_reportmapping.- The email-code sign-in is tested in the shared library but is not reachable from any CLI or TUITerminal User Interface command, and it has no test at that level.
- There is no test that a hosted request is refused once the spending limit is reached, because the limit is enforced server-side and the client never sees that decision.
- There is no end-to-end test that drives the browser approval or the spending-limit page, because both live outside the client.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall sign a user in with a browser-based device authorization flow that requests a device code with the `jcode-cli` client name, opens the public approval URL, and polls the token endpoint with bounded backoff until the browser approves, the user denies, the device code expires, or the flow times out, and a Ctrl-C during the wait shall cancel the flow without saving a credential. | TC-44, TC-45, TC-46, TC-47, TC-48, TC-55, TC-56, TC-63, TC-64, TC-65, TC-71, TC-72 |
| FR-2MustThe system shall wait for plan activation after the browser approval by polling `/v1/me` until the account reports an active plan with a spending limit, a canceled checkout, a revoked or denied key, or the activation timeout elapses. | TC-52, TC-53, TC-54 (partial, see gap G-3) |
| FR-3MustThe system shall persist the approved account key together with the non-secret account id, email and tier in the owner-only hosted-account file, and shall not write any credential before the browser approval is confirmed. | TC-33, TC-43, TC-55, TC-58 |
| FR-4MustThe system shall keep the valid account key and print recovery actions when activation is canceled or times out, and shall clear the local credentials when the key is revoked or the account server denies the activation check. | TC-33, TC-49, TC-58 (partial, see gap G-3) |
| FR-5MustThe system shall report the canonical account email, the plan tier and status, and the monthly spending usage from `/v1/me` on `jcode account status`, and shall offer a `--json` form of the same account payload. | TC-52, TC-53 (partial, the CLI rendering is untested, see gap G-1) |
| FR-6MustThe system shall tell the user to run `jcode account login` when no account credential is configured, and shall clear the local credentials and report a revoked or expired key when `/v1/me` answers unauthorized. | TC-49, TC-58, TC-69 (partial, see gap G-1) |
| FR-7MustThe system shall open the public Jcode account management page from `jcode account manage`, and shall print the URL instead of launching a browser when browser launch is suppressed. | TC-32, TC-79 (partial, the browser launch is untested, see gap G-1) |
| FR-8MustThe system shall always clear the local account credential, the cached account identity and the cached tier on `jcode account logout`, and shall revoke the key remotely when the account API is reachable. | TC-33, TC-43, TC-58 |
| FR-9MustThe system shall report the outcome of each logout step, distinguishing no local credential, a revoked key, an already revoked key, an offline account API, and a remote revocation that could not be confirmed. | TC-43, TC-77 (partial, the CLI message wording is untested, see gap G-1) |
| FR-10MustThe system shall write the hosted-account credential file with owner-only permissions and shall re-harden and re-verify the permission mode after every credential mutation. | TC-33, TC-43, TC-58 |
| FR-11MustThe system shall offer exactly the curated hosted models, shall offer every curated model at the base plan, and shall pin every hosted model to the managed Jcode router route so a hosted model id never falls through to a direct provider credential. | TC-1, TC-2, TC-3, TC-5, TC-19, TC-20, TC-21, TC-22, TC-23, TC-24, TC-25, TC-83 |
| FR-12MustThe system shall expose `/hosted` and its `/subscribe` alias for the hosted-model pitch, and `/hosted status` with its `/subscription` and `/subscription status` aliases for the hosted account status. | TC-36, TC-69, TC-70 |
| FR-13MustThe system shall show the credential state, the router base, the billing model, the runtime mode, the curated catalog and the billing rules including the tranche schedule on the hosted account status surface, and shall fetch `/v1/me` in the background to publish the account email, the billing status, the spend against the monthly limit, the amount already billed, the next tranche amount and the reset time. | TC-11, TC-17, TC-41, TC-69 (partial, the background read is untested, see gap G-4) |
| FR-14MustThe system shall clear the local credentials and tell the user to sign in again when the hosted account status surface finds that the account key was revoked. | TC-34, TC-35, TC-76 |
| FR-15MustThe system shall report the Jcode inference spending balance, the remaining amount against the monthly limit, the daily feature allowances and the reset time on the usage surface, shall mark the hard limit as reached when the monthly spend reaches the monthly limit, shall not mark it reached when the limit is unknown, and shall suggest an upgrade when a daily allowance passes 80 percent of its limit and an upgrade target is offered. | TC-26, TC-27, TC-28, TC-29, TC-30, TC-31, TC-78 |
| FR-16MustThe system shall produce a subscription notice when a plan or allowance changes that names the exhausted feature, the current plan and the upgrade target with a link, and shall deliver the notice once per occurrence. | TC-12, TC-13, TC-14, TC-15, TC-16, TC-67, TC-68 |
| FR-17MustThe system shall expose the hosted account in the TUITerminal User Interface through `/login jcode` and `/account jcode login`, and shall expose the account status, the management page and the logout as `/account jcode status`, `/account jcode manage` and `/account jcode logout`. | TC-36, TC-69 |
| FR-18MustThe system shall enable the hosted runtime mode when the hosted account is activated, and shall clear the hosted runtime mode when the credentials are cleared or the user selects another provider. | TC-11, TC-17, TC-25, TC-83 |
| FR-19ShouldThe system shall offer an email-code sign-in that sends a code to the address, keeps the code token in memory only, and reports the remaining attempts when the typed code is wrong. | TC-61, TC-62 |
| FR-20ShouldThe system shall surface a hosted-model nudge when a provider rate-limits the user and after a long fully completed task, at most once per session and at most once per week, and never for a user who already holds account credentials. | TC-37, TC-38, TC-39, TC-40, TC-41, TC-42, TC-84 |
| FR-21MayThe system shall accept a monthly hard cap, a billing portal session, a subscription checkout and a plan change from the account API, and shall accept only an https billing portal URL and only a Stripe Checkout URL. | TC-50, TC-51, TC-80 |
| NFR-1MustThe account key shall never appear in a URL, in a debug rendering, in a log line or in an error message, and shall be sent only in an authorization header. | TC-47, TC-49, TC-55, TC-57, TC-64, TC-73 |
| NFR-2MustThe browser approval URL shall be restricted to the allowlisted public https origins with the account path and a single flow query parameter, and the account management URL shall be restricted to the same origins, so a URL carrying credentials, a non-default port, an unexpected path or extra query parameters is rejected. | TC-32, TC-44, TC-71, TC-79 |
| NFR-3MustThe monthly spending limit and the model policy shall be enforced server-side by the Jcode router, and the client shall not decide from a cached tier which models an account may use or how much it may spend. | TC-10, TC-22, TC-23, TC-83 |
| NFR-4MustThe account key shall be revoked on the server when the user logs out and the account API is reachable, and the local credential shall be cleared even when the revocation cannot be confirmed. | TC-33, TC-43, TC-77 |
| NFR-5MustThe account email, the account id and the spending limit shall not be sent to the telemetry service, and the only telemetry emitted for this feature shall be the coarse authentication success event. | No test. The only telemetry emitted for this feature is the coarse authentication success event, and no test asserts its shape. |
| NFR-6MustA failed `/v1/me` fetch shall keep the local credential and shall degrade to a quiet message rather than failing the session, and an unreachable account API during the device poll shall be retried with backoff rather than aborting the flow. | TC-54, TC-56, TC-58, TC-75 |
| NFR-7MustThe account status fetch shall use a 5 second timeout, the device authorization request shall use a 15 second timeout, and the polling backoff shall stay deterministic and bounded. | TC-54 |
| NFR-8ShouldThe activation wait shall be bounded to 10 minutes, and a polling request that is already in flight shall be allowed to finish so a single-use device code is not stranded. | TC-59, TC-66, TC-74 |
| NFR-9ShouldA user who has not signed in shall be pointed at `/login jcode`, and the hosted account status shall state plainly that hosted usage is not enabled until a spending limit exists. | TC-41, TC-69, TC-70 |
| NFR-10ShouldThe browser approval URL and the account management URL shall be the only links the client opens, and the client shall never open a URL returned by the account API without checking its scheme and origin. | TC-32, TC-44, TC-79 |
| NFR-11ShouldThe account service contract shall be versioned by endpoint, and a legacy backend that only offers the old email-based login shall produce a specific compatibility error rather than a generic failure. | TC-47, TC-81 |
requirements
- The metered plan and the legacy
JcodeTierladder (Plus, Pro, Max, Ultra, Solo) both exist in the code, but only the metered plan is used for the hosted catalog and the spending limit. Should the tier ladder be retired, or kept as a separate cloud entitlement ladder asdocs/JCODE_CLOUD_AWS.mddescribes? - The
SubscriptionUsagefieldbudget_usdis the canonical name on the wire, withspend_limit_usdandlimit_usdaccepted as aliases for older servers. Should the canonical name becomespend_limit_usdso the wire field matches the user-facing "spending limit" wording? - The account API exposes
PUT /v1/billing/hard-cap,POST /v1/billing/portal,POST /v1/billing/subscribeandPOST /v1/billing/plan, but the current user flow sets the limit in the browser and never calls them from the client. Should the terminal expose a limit-setting command, or keep the browser as the only place the limit changes?
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. Multi-Agent Coordination
Overview
SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. coordination lets jcode delegate work across multiple agent instances. A coordinator agent builds a plan DAG of tasks, spawns worker agents (visible, headless, inline, or auto spawn modes), and communicates with them over typed comm channels (direct messages, broadcasts, and plan updates). Members report progress and completion back so the coordinator can revise the plan. This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | Parallel, coordinated multi-agent work on complex tasks with visible progress |
| Maintainer | Reliable task graph execution, persisted swarm state, and debuggable comm flows |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall let a coordinator agent delegate tasks to worker agents within a session. | Must | The system shall let a coordinator agent delegate tasks to worker agents within a session. |
| FR-2MustThe system shall maintain a plan DAG of tasks (up to a bounded number of plan items) that the coordinator can revise as work completes. | Must | The system shall maintain a plan DAG of tasks (up to a bounded number of plan items) that the coordinator can revise as work completes. |
| FR-3MustThe system shall support multiple spawn modes for workers: visible, headless, inline, and auto. | Must | The system shall support multiple spawn modes for workers: visible, headless, inline, and auto. |
| FR-4MustThe system shall provide typed comm channels for messages between the coordinator and members, including direct messages and broadcasts. | Must | The system shall provide typed comm channels for messages between the coordinator and members, including direct messages and broadcasts. |
| FR-5MustThe system shall surface swarm status and plan progress to the UI (swarm status, plan, todo items). | Must | The system shall surface swarm status and plan progress to the UI (swarm status, plan, todo items). |
| FR-6MustThe system shall persist swarm state so it survives reloads. | Must | The system shall persist swarm state so it survives reloads. |
| FR-7ShouldThe system shall validate member reports (including a tldr rule and completion-report marker) before accepting them. | Should | The system shall validate member reports (including a tldr rule and completion-report marker) before accepting them. |
| FR-8MayThe system shall support an inline gallery of swarm members in the UI. | May | The system shall support an inline gallery of swarm members in the UI. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustSwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. state must be durable across server reloads and restarts. | Must | Reliability | SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. state must be durable across server reloads and restarts. |
| NFR-2ShouldComm messages must flow without blocking the main agent turn loop. | Should | Performance | Comm messages must flow without blocking the main agent turn loop. |
| NFR-3ShouldThe user shall be able to see each member's status and the overall plan at a glance. | Should | Usability | The user shall be able to see each member's status and the overall plan at a glance. |
Constraints
- The plan DAG is bounded (
MAX_PLAN_ITEMS = 1024). - SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. behavior is configured under the
[agents]config section (spawn mode, swarm model).
Acceptance Criteria
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FR-1MustThe system shall let a coordinator agent delegate tasks to worker agents within a session.
- Given an active session with swarm enabled
- When the coordinator emits a task delegation
- Then a worker agent runs the task and reports back
- FR-2MustThe system shall maintain a plan DAG of tasks (up to a bounded number of plan items) that the coordinator can revise as work completes.
- Given a multi-task swarm
- When tasks complete
- Then the plan DAG updates and remains bounded
- FR-3MustThe system shall support multiple spawn modes for workers: visible, headless, inline, and auto.
- Given the configured spawn mode
- When a worker spawns
- Then it runs visible, headless, inline, or auto as configured
- FR-4MustThe system shall provide typed comm channels for messages between the coordinator and members, including direct messages and broadcasts.
- Given active swarm members
- When a member sends a message
- Then the message is delivered to the addressed member(s) over the comm channel
- FR-5MustThe system shall surface swarm status and plan progress to the UI (swarm status, plan, todo items).
- Given an active swarm
- When the user views the session
- Then member status and plan progress are visible
- FR-6MustThe system shall persist swarm state so it survives reloads.
- Given an in-flight swarm
- When the server reloads
- Then the swarm resumes with its state intact
- FR-7ShouldThe system shall validate member reports (including a tldr rule and completion-report marker) before accepting them.
- Given a member completion report
- When it lacks the required tldr or marker
- Then the report is rejected or flagged for the coordinator
- FR-8MayThe system shall support an inline gallery of swarm members in the UI.
- Given an active swarm in the TUITerminal User Interface
- When the inline gallery is enabled
- Then members are shown inline in the transcript
- NFR-1MustSwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. state must be durable across server reloads and restarts.
- Given persisted swarm state
- When a reload occurs
- Then no task or member is lost
- NFR-2ShouldComm messages must flow without blocking the main agent turn loop.
- Given high-volume comm traffic
- When the main turn loop is running
- Then the turn loop continues without being blocked by comm delivery
- NFR-3ShouldThe user shall be able to see each member's status and the overall plan at a glance.
- Given a running swarm
- When the UI renders the swarm panel
- Then member statuses and plan state are shown clearly
Conflicts
None identified yet.
Open Questions
- What is the default worker limit and how are tasks balanced across members? Config exposes a swarm model and spawn mode but the scheduling heuristics are inferred from code.
Specification: SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. Multi-Agent Coordination
Overview
SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. coordination spans crates/jcode-swarm-core (message/report validation), crates/jcode-plan (plan DAG and mermaid/bridge helpers), crates/jcode-task-types, and the server-side swarm implementation in crates/jcode-app-core/src/server/ (swarm*.rs and comm_*.rs). The coordinator agent runs in the main session; workers run as subagents. This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
coordinator agent (main session)
│
plan DAG (jcode-plan, PlanItem, VersionedPlan)
│
┌────────────────────┼─────────────────────┐
▼ ▼ ▼
worker agent worker agent worker agent
(visible/headless/inline/auto spawn modes)
│ │ │
└──────────── typed comm channels (comm_graph, comm_plan, comm_session,
comm_control, comm_sync, comm_await) ────────────┘
│
swarm status / plan events ──► UI (TUITerminal User Interface / protocol)
Data Models
PlanItem / VersionedPlan (crates/jcode-plan)
| Field | Type | Constraints | Description |
|---|---|---|---|
| item | PlanItem | bounded by MAX_PLAN_ITEMS = 1024 | A single task node in the plan. |
| version | int | not null | Version of the plan graph. |
| status | enum | pending/in-progress/done/failed | Progress of the item. |
SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. Status / Todo / Member
Shared types include SwarmMemberStatus, SwarmTodoItem, and PlanGraphStatus in jcode-protocol.
API Contracts
Protocol (internal)
RunSubagentrequest — spawn a worker from the coordinator.Comm*requests — swarm message operations (send DM, broadcast, plan update).ServerEventswarm variants —swarm_status,swarm_plan, member status snapshots.
Sequences
Delegate and complete a task
Coordinator → RunSubagent(task) → worker spawns in configured mode
Worker runs task → completion report (tldr + marker)
Server validates report (jcode-swarm-core) → sends Comm message to coordinator
Coordinator updates plan DAG → plan status events stream to UI
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Plan as versioned DAG | VersionedPlan in jcode-plan |
Supports revision as tasks complete and replay/history. |
| Typed comm channels | comm_*.rs modules with graph/plan/session/control separation |
Keeps message flows auditable and testable. |
| Report validation | tldr rule + completion marker | Prevents malformed member output from corrupting the plan. |
| Spawn modes | visible/headless/inline/auto | Lets users trade visibility against parallelism. |
| Persistence | swarm state in durable server state | Survives reloads (NFR-1MustSwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. state must be durable across server reloads and restarts.). |
Risks and Unknowns
- Scheduling and parallelism heuristics are not fully documented in the code; inferred from module structure.
- Plan-item limits and tldr rules may need tuning as worker counts grow.
Out of Scope
- Cross-machine (distributed) swarm execution; workers run within one server process.
- Persistent worker identity across sessions.
Test Plan: SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. Multi-Agent Coordination
Scope
Covers swarm persistence, comm channels, plan graph handling, and member report validation. Out of scope: live multi-agent behavior against paid providers (covered by scripted e2e suites).
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. state persistence | crates/jcode-app-core/src/server/swarm_persistence_tests.rs |
SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. survives reload/restart |
| TC-2 | Comm channelA message channel between swarm members (direct message, broadcast). behavior | crates/jcode-app-core/src/server/client_comm_tests.rs, comm_control_tests.rs |
Messages delivered to the right members |
| TC-3 | Comm plan graph handling | crates/jcode-app-core/src/server/comm_plan_tests.rs |
Plan updates propagate |
| TC-4 | Comm session handling | crates/jcode-app-core/src/server/comm_session_tests.rs |
SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status.-level comm works |
| TC-5 | Plan DAG invariants | crates/jcode-plan tests |
Plan stays bounded and versioned |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-6 | SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. e2e scenarios | scripts/test_swarm.py, scripts/test_swarm_debug.py |
Coordinator + workers complete a delegated task |
| TC-7 | SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. performance benchmark | scripts/benchmark_swarm.py |
Throughput/latency within expectations |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-8 | Malformed member completion report | Rejected or flagged per tldr/marker rules |
| TC-9 | Plan exceeds item limit | Plan bounded at MAX_PLAN_ITEMS without corruption |
| TC-10 | ReloadHot-reloading the server into a new binary without dropping clients or sessions. mid-task | SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. state restored; task not lost |
Test Infrastructure
- Script-based swarm suites (
test_swarm.py,test_swarm_debug.py,benchmark_swarm.py). - Durable-state fixtures for reload tests.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-2MustThe system shall maintain a plan DAG of tasks (up to a bounded number of plan items) that the coordinator can revise as work completes. | TC-3, TC-5, TC-9 |
| FR-4MustThe system shall provide typed comm channels for messages between the coordinator and members, including direct messages and broadcasts. | TC-2, TC-4 |
| FR-6MustThe system shall persist swarm state so it survives reloads. | TC-1, TC-10 |
| FR-7ShouldThe system shall validate member reports (including a tldr rule and completion-report marker) before accepting them. | TC-8 |
| NFR-1MustSwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. state must be durable across server reloads and restarts. | TC-1, TC-10 |
requirements
- What is the default worker limit and how are tasks balanced across members? Config exposes a swarm model and spawn mode but the scheduling heuristics are inferred from code.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Terminal UI
Overview
The terminal UI is jcode's primary interface: a fast, memory-efficient TUITerminal User Interface built with ratatui that renders streaming agent output, session pickers, info widgets, side panels, inline images, and MermaidDiagram rendering inside the terminal. diagrams. It also powers the offline jcode replay video export of past sessions. The TUITerminal User Interface is the presentation layer and shares a backend-neutral render model with the desktop app. This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | Low-latency, readable streaming output, discoverable keybindings, and useful side panels |
| Maintainer | Performant rendering under heavy streams, themeable output, and testable UI logic |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall render streaming agent output in a terminal UI with low input latency. | Must | The system shall render streaming agent output in a terminal UI with low input latency. |
| FR-2MustThe system shall provide a session picker to browse and resume past sessions. | Must | The system shall provide a session picker to browse and resume past sessions. |
| FR-3MustThe system shall display info widgets (session info, model, provider, usage) in the UI. | Must | The system shall display info widgets (session info, model, provider, usage) in the UI. |
| FR-4MustThe system shall support configurable keybindings and display options (e.g. centered mode, message timestamps, theme detection). | Must | The system shall support configurable keybindings and display options (e.g. centered mode, message timestamps, theme detection). |
| FR-5ShouldThe system shall render side panels such as the session list and usage overlay. | Should | The system shall render side panels such as the session list and usage overlay. |
| FR-6ShouldThe system shall render MermaidDiagram rendering inside the terminal. diagrams and inline images in the transcript where the terminal supports it. | Should | The system shall render MermaidDiagram rendering inside the terminal. diagrams and inline images in the transcript where the terminal supports it. |
| FR-7ShouldThe system shall support offline replay of sessions, including video export. | Should | The system shall support offline replay of sessions, including video export. |
| FR-8ShouldThe system shall run an onboarding walkthrough for first-time users. | Should | The system shall run an onboarding walkthrough for first-time users. |
| FR-9MayThe system shall show idle animations (e.g. a donut) that stay CPU-light. | May | The system shall show idle animations (e.g. a donut) that stay CPU-light. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustThe TUITerminal User Interface shall keep full-frame render time low while streaming (render stack pinned to optimized profiles). | Must | Performance | The TUITerminal User Interface shall keep full-frame render time low while streaming (render stack pinned to optimized profiles). |
| NFR-2MustRAM usage shall stay low; additional clients shall scale memory gracefully. | Must | Performance | RAM usage shall stay low; additional clients shall scale memory gracefully. |
| NFR-3ShouldKeybindings must be discoverable and configurable without editing source. | Should | Usability | Keybindings must be discoverable and configurable without editing source. |
| NFR-4ShouldTUITerminal User Interface state must be testable without a live terminal (headless test harness). | Should | Reliability | TUITerminal User Interface state must be testable without a live terminal (headless test harness). |
Constraints
- Terminal-first: the TUITerminal User Interface must degrade gracefully across terminals without kitty/iterm2 image support.
- Config via
[keybindings]and[display]sections in~/.jcode/config.toml.
Acceptance Criteria
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FR-1MustThe system shall render streaming agent output in a terminal UI with low input latency.
- Given a streaming session
- When output arrives rapidly
- Then the UI keeps the input line responsive (no visible input lag)
- FR-2MustThe system shall provide a session picker to browse and resume past sessions.
- Given past sessions
- When the user opens the session picker
- Then sessions are listed and selectable for resume
- FR-3MustThe system shall display info widgets (session info, model, provider, usage) in the UI.
- Given an active session
- When info widgets are enabled
- Then session, model, provider, and usage information is visible
- FR-4MustThe system shall support configurable keybindings and display options (e.g. centered mode, message timestamps, theme detection).
- Given a customized keybinding or display setting
- When jcode starts
- Then the UI honors the configuration
- FR-5ShouldThe system shall render side panels such as the session list and usage overlay.
- Given an active session
- When the session list or usage side panel is toggled
- Then the panel renders the expected content
- FR-6ShouldThe system shall render MermaidDiagram rendering inside the terminal. diagrams and inline images in the transcript where the terminal supports it.
- Given a transcript containing a MermaidDiagram rendering inside the terminal. diagram or an inline image
- When the terminal supports the rendering path
- Then the diagram/image renders inline
- FR-7ShouldThe system shall support offline replay of sessions, including video export.
- Given a recorded session
- When the user runs
jcode replay --video - Then an offline video export is produced
- FR-8ShouldThe system shall run an onboarding walkthrough for first-time users.
- Given a first-time user
- When onboarding is enabled
- Then a guided walkthrough is shown
- FR-9MayThe system shall show idle animations (e.g. a donut) that stay CPU-light.
- Given idle time in the UI
- When the idle animation is enabled
- Then CPU usage stays low during animation
- NFR-1MustThe TUITerminal User Interface shall keep full-frame render time low while streaming (render stack pinned to optimized profiles).
- Given a streaming session
- When frames are rendered
- Then p50/p95 frame time stays within the performance budget
- NFR-2MustRAM usage shall stay low; additional clients shall scale memory gracefully.
- Given multiple clients on the same server
- When memory is measured
- Then incremental memory per additional client stays low
- NFR-3ShouldKeybindings must be discoverable and configurable without editing source.
- Given the default keybinding set
- When a user presses
?or consults help - Then bindings are shown and overridable via config
- NFR-4ShouldTUITerminal User Interface state must be testable without a live terminal (headless test harness).
- Given the TUITerminal User Interface test harness
- When UI logic tests run in CIContinuous Integration
- Then they pass without a real terminal
Conflicts
None identified yet.
Open Questions
- What is the exact frame-time budget enforced for the TUITerminal User Interface render stack? Profile comments reference ~12 ms p50 / ~21 ms p95 for full frames, but a formal number is not documented.
Specification: Terminal UI
Overview
The TUITerminal User Interface lives in crates/jcode-tui (the presentation layer of the crate spine: base → app-core → tui → root) with rendering helpers in jcode-tui-mermaid, jcode-tui-anim, jcode-fuzzy, jcode-math, and a shared render model in jcode-render-core. It subscribes to server events over the protocol socket and renders streaming messages, panels, and diagrams. Offline replay/video export lives in jcode-tui's video export module and is reachable via jcode replay. This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
jcode-tui (ratatui + crossterm)
├── tui/app/ — main app state machine, keybindings, input handling
├── tui/ui_* — widget implementations (info widgets, side panels)
├── tui/session_picker — session browse/resume
├── tui/mermaid — MermaidDiagram rendering inside the terminal. rendering (PNG via ratatui-image, kitty/sixel/iTerm2/halfblock)
├── tui/video_export — offline replay + video export (jcode replay)
├── tui/keybind — configurable keybindings
└── jcode-render-core — backend-neutral document/render model shared with desktop
│
▼
jcode-protocol (ServerEvent stream over socket)
Data Models
UI State
TUITerminal User Interface state is decomposed into widgets via the TUISTATE trait (see docs/TUISTATE_TRAIT_DECOMPOSITION.md), which keeps rendering logic testable headlessly.
Config Surface
| Section | Keys | Description |
|---|---|---|
[display] |
display modes, centered mode, timestamps, message timestamps | Rendering preferences. |
[keybindings] |
per-action bindings | User-overridable keymaps. |
[features] |
mermaid, idle animation, etc. | Feature toggles. |
API Contracts
CLI: jcode replay [session]
Flags: --swarm, --export, --video, --auto-edit, --timeline, --speed, --fps.
Behavior | Description
|---|---|
| --video | Exports an offline video of the session replay. |
Sequences
Render a streaming turn
Server sends ServerEvent (TextDelta, ToolUseStart/End, ...) over socket
TUITerminal User Interface app receives event → updates document model (jcode-render-core)
Redraw triggered → widgets render cells → crossterm frame flush
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| ratatui + crossterm | Industry-standard terminal rendering | Mature, fast, cross-platform. |
| Render stack pinned to opt-level 3 | ratatui/unicode/image/etc. pinned in profiles | Prevents ~12 ms→21 ms full-frame slowdowns in dev builds. |
| Backend-neutral render model | jcode-render-core |
Shares document rendering with the desktop GPU app. |
| Offline video export | video_export module + jcode replay --video |
Reproducible session review without a live terminal. |
| TUISTATE decomposition | trait-based widget state | Headless testability (NFR-4ShouldTUITerminal User Interface state must be testable without a live terminal (headless test harness).). |
Risks and Unknowns
- Image/MermaidDiagram rendering inside the terminal. rendering depends on terminal protocol support; fallbacks degrade to text or halfblock rendering.
- Idle animations must stay CPU-light (math kernels pinned to
opt-level = 3to bound CPU use).
Out of Scope
- The desktop GPU UI (a separate feature; shares
jcode-render-coreonly). - Terminal-agnostic rendering of exotic diagrams beyond MermaidDiagram rendering inside the terminal..
Test Plan: Terminal UI
Scope
Covers session picker, info widgets, pinned UI state, mermaid rendering, and TUITerminal User Interface serial/test harness behavior. Out of scope: live terminal interaction and image-protocol rendering on physical terminals.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. picker behavior | crates/jcode-tui/src/tui/session_picker_tests.rs |
Sessions listed and selected correctly |
| TC-2 | Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. rendering | crates/jcode-tui/src/tui/info_widget_*_tests.rs |
Widgets render expected content |
| TC-3 | Pinned UI state | crates/jcode-tui/src/tui/ui_pinned_tests.rs |
Pinned elements behave as configured |
| TC-4 | Auth/account pickers | crates/jcode-tui/src/tui/auth*_tests.rs |
Account pickers render and select correctly |
| TC-5 | TUITerminal User Interface frame timing | src/bin/tui_bench.rs |
Frame timing within budget |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-6 | Serial TUITerminal User Interface lib tests in CIContinuous Integration | Linux/macOS build matrix | TUITerminal User Interface state tests pass headlessly |
| TC-7 | Desktop2 frame-budget parity | crates/jcode-desktop2 profile tests |
Shared render model stays within budget |
| TC-8 | MermaidDiagram rendering inside the terminal. rendering acceptance | docs/RENDER_PARITY_ACCEPTANCE_CRITERIA.md checks |
Diagram output matches acceptance criteria |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-9 | Terminal without kitty/sixel support | Image/MermaidDiagram rendering inside the terminal. degrades to fallback rendering |
| TC-10 | Rapid streaming with many frames | Input line stays responsive (no visible lag) |
| TC-11 | Empty session list | Picker shows empty state without error |
Test Infrastructure
- Headless TUITerminal User Interface test harness via TUISTATE trait decomposition.
- Benchmark binaries (
tui_bench,mermaid_side_panel_probe). - CIContinuous Integration serial TUITerminal User Interface test cohort to avoid terminal flakiness.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-2MustThe system shall provide a session picker to browse and resume past sessions. | TC-1, TC-11 |
| FR-3MustThe system shall display info widgets (session info, model, provider, usage) in the UI. | TC-2 |
| FR-6ShouldThe system shall render MermaidDiagram rendering inside the terminal. diagrams and inline images in the transcript where the terminal supports it. | TC-8, TC-9 |
| NFR-1MustThe TUITerminal User Interface shall keep full-frame render time low while streaming (render stack pinned to optimized profiles). | TC-5, TC-10 |
| NFR-4ShouldTUITerminal User Interface state must be testable without a live terminal (headless test harness). | TC-6 |
requirements
- What is the exact frame-time budget enforced for the TUI render stack? Profile comments reference ~12 ms p50 / ~21 ms p95 for full frames, but a formal number is not documented.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. Persistence, Resume and Replay
Overview
Sessions are jcode's durable unit of work. Every session is persisted to disk (a snapshot JSON plus an append-only JSONL journal), so sessions survive crashes, reloads, and reboots. Users can resume sessions by memorable short name, replay past sessions in the TUITerminal User Interface, export them, and even resume sessions started in other tools (Claude Code, Codex, Pi, OpenCode, Cursor). This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | Never lose a session; resume context across restarts and terminals |
| Maintainer | Crash-safe persistence, reliable reload recovery, and clean replay/export |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall persist each session as a snapshot file plus an append-only journal of messages and events. | Must | The system shall persist each session as a snapshot file plus an append-only journal of messages and events. |
| FR-2MustThe system shall resume a session by id or memorable short name (`--resume`, session picker). | Must | The system shall resume a session by id or memorable short name (--resume, session picker). |
| FR-3MustThe system shall record session status (active, closed, crashed, reloaded, compacted, rate-limited, error) and survive server reloads and restarts. | Must | The system shall record session status (active, closed, crashed, reloaded, compacted, rate-limited, error) and survive server reloads and restarts. |
| FR-4MustThe system shall import sessions from external tools (Claude Code, Codex, Pi, OpenCode, Cursor) as resume targets. | Must | The system shall import sessions from external tools (Claude Code, Codex, Pi, OpenCode, Cursor) as resume targets. |
| FR-5MustThe system shall capture an environment snapshot (git state, provider, model) per session. | Must | The system shall capture an environment snapshot (git state, provider, model) per session. |
| FR-6ShouldThe system shall support TUITerminal User Interface replay of a session, including swarm status and plan events, with export options. | Should | The system shall support TUITerminal User Interface replay of a session, including swarm status and plan events, with export options. |
| FR-7ShouldThe system shall support a restart snapshot to resume sessions after a reboot. | Should | The system shall support a restart snapshot to resume sessions after a reboot. |
| FR-8ShouldThe system shall record crash and reload recovery so interrupted sessions can be restored. | Should | The system shall record crash and reload recovery so interrupted sessions can be restored. |
| FR-9MayThe system shall support session search across persisted sessions. | May | The system shall support session search across persisted sessions. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustJournal appends shall be crash-safe; a partial journal must not corrupt the session. | Must | Reliability | Journal appends shall be crash-safe; a partial journal must not corrupt the session. |
| NFR-2MustSessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. files can grow large; persistence and search must not degrade the agent loop. | Must | Performance | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. files can grow large; persistence and search must not degrade the agent loop. |
| NFR-3ShouldResuming should feel instant via memorable names and a picker. | Should | Usability | Resuming should feel instant via memorable names and a picker. |
Constraints
- Storage layout:
~/.jcode/sessions/<id>.jsonsnapshot plus<id>.journal.jsonl. - Imported sessions keep their provenance (ResumeTarget enum).
Acceptance Criteria
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FR-1MustThe system shall persist each session as a snapshot file plus an append-only journal of messages and events.
- Given an active session
- When a message is exchanged
- Then it is appended to the journal and reflected in the snapshot
- FR-2MustThe system shall resume a session by id or memorable short name (`--resume`, session picker).
- Given a persisted session
- When the user resumes by name or id
- Then the conversation and context are restored
- FR-3MustThe system shall record session status (active, closed, crashed, reloaded, compacted, rate-limited, error) and survive server reloads and restarts.
- Given a server reload mid-session
- When the server restarts
- Then the session status is recorded and the session is recoverable
- FR-4MustThe system shall import sessions from external tools (Claude Code, Codex, Pi, OpenCode, Cursor) as resume targets.
- Given an external tool session (e.g. Codex)
- When the user resumes it
- Then it imports and continues in jcode
- FR-5MustThe system shall capture an environment snapshot (git state, provider, model) per session.
- Given a new session
- When it is created
- Then the environment snapshot (git, provider, model) is captured
- FR-6ShouldThe system shall support TUITerminal User Interface replay of a session, including swarm status and plan events, with export options.
- Given a persisted session
- When the user runs
jcode replay --export - Then the session replays and exports correctly
- FR-7ShouldThe system shall support a restart snapshot to resume sessions after a reboot.
- Given saved sessions
- When a reboot occurs and restart restore runs
- Then sessions resume from the restart snapshot
- FR-8ShouldThe system shall record crash and reload recovery so interrupted sessions can be restored.
- Given a crashed session
- When recovery runs
- Then the session is restored with its crash status recorded
- FR-9MayThe system shall support session search across persisted sessions.
- Given persisted sessions
- When the user searches
- Then matching sessions are returned
- NFR-1MustJournal appends shall be crash-safe; a partial journal must not corrupt the session.
- Given an interrupted journal write
- When the session is reopened
- Then the journal is repaired or rejected without corrupting the snapshot
- NFR-2MustSessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. files can grow large; persistence and search must not degrade the agent loop.
- Given a large session
- When it is loaded or searched
- Then the agent loop remains responsive
- NFR-3ShouldResuming should feel instant via memorable names and a picker.
- Given memorable session names
- When the user types the name
- Then the session resumes immediately
Conflicts
None identified yet.
Open Questions
- What is the exact journal compaction/truncation policy for very long sessions? CompactionReducing accumulated context (and the KV cache) when a session grows too large. interacts with this feature and the exact boundary is inferred from code.
Specification: SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. Persistence, Resume and Replay
Overview
SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. persistence lives in crates/jcode-base/src/session/ (persistence, journal, render, crash) with shared models in crates/jcode-session-types. External-session import is implemented in crates/jcode-import-core. Replay and video export live in the TUITerminal User Interface layer (jcode-tui/src/video_export.rs), reachable via jcode replay. This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
jcode server (app-core)
│ writes
▼
~/.jcode/sessions/<id>.json (snapshot)
~/.jcode/sessions/<id>.journal.jsonl (append-only journal)
│
├── session/ (persistence, journal, render, crash)
├── import-core (ResumeTarget: jcode/claude-code/codex/pi/opencode/cursor)
└── TUITerminal User Interface video_export (jcode replay --video/--export)
Data Models
StoredMessage (jcode-session-types)
| Field | Type | Constraints | Description |
|---|---|---|---|
| id | string | PK | MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. id. |
| role | enum | not null | User or Assistant. |
| content | list | not null | Content blocks of the message. |
| token_usage | object | nullable | Token accounting. |
| timestamp | timestamp | not null | When the message was stored. |
SessionJournalMeta
Captures parent id, title, status, compaction state, provider session id, model, reasoning effort, working dir, last pid, timestamps, and flags (canary, debug, saved).
StoredReplayEvent
Kinds: display_message, swarm_status, swarm_plan; appended to the journal for replay.
API Contracts
CLI: jcode replay [session]
Flags: --swarm, --export, --video, --auto-edit, --timeline, --speed, --fps.
CLI: jcode session rename
Rename a session's title (stored in journal meta).
Sequences
Resume a session
jcode --resume <name|id> → connect to server → load journal → replay events
→ client state rebuilt → stream continues from where it left off
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Snapshot + append journal | <id>.json + <id>.journal.jsonl |
Crash-safe appends; snapshot for fast load. |
| Journal replay events | StoredReplayEvent |
Reconstructs UI state and swarm plans on resume. |
| Import from external tools | ResumeTarget enum + jcode-import-core |
Users migrate context from other agents. |
| Memorable short names | whimsical names (e.g. fox) |
Fast resume by name (NFR-3ShouldResuming should feel instant via memorable names and a picker.). |
Risks and Unknowns
- Very long journals interact with compaction; the truncation policy is inferred from code.
- Import fidelity depends on external tool formats, which change upstream.
Out of Scope
- Cloud-backed session sync (a separate Jade cloud integration).
- Editing/deleting persisted history beyond rename and standard lifecycle.
Test Plan: SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. Persistence, Resume and Replay
Scope
Covers session persistence, journaling, resume, import, replay, and reload recovery. Out of scope: live provider round-trips.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. store behavior | crates/jcode-base/src/session_tests/ |
Sessions persist, load, and resume correctly |
| TC-2 | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. search scoring | crates/jcode-session-types/src/session_search_tests.rs |
Search results ranked correctly |
| TC-3 | External session import | crates/jcode-base/src/import_tests.rs |
Imported sessions parse and convert correctly |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-4 | End-to-end session flow | tests/e2e/session_flow.rs |
Create, stream, persist, resume works end to end |
| TC-5 | ReloadHot-reloading the server into a new binary without dropping clients or sessions. multi-client recovery | tests/e2e/reload_multiclient.rs |
Clients reconnect and sessions survive reload |
| TC-6 | ReloadHot-reloading the server into a new binary without dropping clients or sessions. recovery audit | scripts/test_reload.py, scripts/reload_recovery_audit.py |
Crashed/reloaded sessions recover cleanly |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-7 | Corrupted or partial journal | Journal repaired or rejected without corrupting the snapshot |
| TC-8 | Very large session files | Load and search stay responsive |
| TC-9 | Crash mid-write | SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. marked crashed and recoverable on next start |
Test Infrastructure
- SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. fixtures under
tests/fixtures/. - Multi-client e2e harness (
tests/e2e/test_support/). - Python reload-recovery audit scripts.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall persist each session as a snapshot file plus an append-only journal of messages and events. | TC-1, TC-4 |
| FR-3MustThe system shall record session status (active, closed, crashed, reloaded, compacted, rate-limited, error) and survive server reloads and restarts. | TC-5, TC-9 |
| FR-4MustThe system shall import sessions from external tools (Claude Code, Codex, Pi, OpenCode, Cursor) as resume targets. | TC-3 |
| FR-8ShouldThe system shall record crash and reload recovery so interrupted sessions can be restored. | TC-6, TC-9 |
| FR-9MayThe system shall support session search across persisted sessions. | TC-2 |
| NFR-1MustJournal appends shall be crash-safe; a partial journal must not corrupt the session. | TC-7 |
requirements
- What is the exact journal compaction/truncation policy for very long sessions? Compaction interacts with this feature and the exact boundary is inferred from code.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Ambient Mode
Overview
Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. is a proactive, OpenClaw-style background agent that works while the user does. A scheduler runs work cycles against configured directives (garden/scout style tasks), executes background tasks, and persists its state. A safety system gates ambient actions, and overnight processing handles long-running consolidation. This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | A background assistant that makes progress without interrupting the main session |
| Maintainer | Safe, configurable, observable ambient behavior with strong permissioning |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall run a background ambient scheduler on the server that executes work cycles. | Must | The system shall run a background ambient scheduler on the server that executes work cycles. |
| FR-2MustThe system shall execute directives (ambient instructions) and run tasks such as garden/scout activities. | Must | The system shall execute directives (ambient instructions) and run tasks such as garden/scout activities. |
| FR-3MustThe system shall persist ambient state (status, log, directives) so it survives reloads. | Must | The system shall persist ambient state (status, log, directives) so it survives reloads. |
| FR-4MustThe system shall gate ambient actions through a safety and permissions system. | Must | The system shall gate ambient actions through a safety and permissions system. |
| FR-5MustThe system shall expose ambient status and control via the CLI (`jcode ambient status`, `trigger`, `stop`, `log`). | Must | The system shall expose ambient status and control via the CLI (jcode ambient status, trigger, stop, log). |
| FR-6ShouldThe system shall support overnight processing for long-running consolidation jobs. | Should | The system shall support overnight processing for long-running consolidation jobs. |
| FR-7ShouldThe system shall render ambient status in the TUITerminal User Interface (e.g. via a side panel / badge). | Should | The system shall render ambient status in the TUITerminal User Interface (e.g. via a side panel / badge). |
| FR-8MayThe system shall trigger ambient activity on configurable schedules. | May | The system shall trigger ambient activity on configurable schedules. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustAmbient actions shall be subject to the same permission/safety gates as interactive actions. | Must | Safety | Ambient actions shall be subject to the same permission/safety gates as interactive actions. |
| NFR-2ShouldAmbient work shall not starve interactive turns on the same server. | Should | Performance | Ambient work shall not starve interactive turns on the same server. |
| NFR-3ShouldAmbient state must be durable across restarts. | Should | Reliability | Ambient state must be durable across restarts. |
Constraints
- Ambient behavior is configured under the
[ambient]config section. - Ambient runs inside the same server process (not a separate daemon).
Acceptance Criteria
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FR-1MustThe system shall run a background ambient scheduler on the server that executes work cycles.
- Given ambient mode enabled
- When the scheduler runs
- Then a work cycle executes on schedule
- FR-2MustThe system shall execute directives (ambient instructions) and run tasks such as garden/scout activities.
- Given configured directives
- When a work cycle runs
- Then the directive's tasks execute
- FR-3MustThe system shall persist ambient state (status, log, directives) so it survives reloads.
- Given an active ambient session
- When the server reloads
- Then ambient state and status are restored
- FR-4MustThe system shall gate ambient actions through a safety and permissions system.
- Given an ambient action requiring permission
- When the action is attempted
- Then it is gated by the safety system before executing
- FR-5MustThe system shall expose ambient status and control via the CLI (`jcode ambient status`, `trigger`, `stop`, `log`).
- Given ambient mode running
- When the user runs
jcode ambient statusorjcode ambient log - Then status and recent activity are shown
- FR-6ShouldThe system shall support overnight processing for long-running consolidation jobs.
- Given overnight enabled
- When the overnight window arrives
- Then consolidation jobs run
- FR-7ShouldThe system shall render ambient status in the TUITerminal User Interface (e.g. via a side panel / badge).
- Given an active ambient session
- When the TUITerminal User Interface renders
- Then ambient status is visible
- FR-8MayThe system shall trigger ambient activity on configurable schedules.
- Given a configured schedule
- When the trigger time arrives
- Then ambient activity starts
- NFR-1MustAmbient actions shall be subject to the same permission/safety gates as interactive actions.
- Given an ambient task that would run a risky command
- When the command is executed
- Then it passes through the same risk/permission gates as interactive commands
- NFR-2ShouldAmbient work shall not starve interactive turns on the same server.
- Given simultaneous interactive and ambient work
- When both are active
- Then interactive turns are not starved
- NFR-3ShouldAmbient state must be durable across restarts.
- Given a restart
- When ambient is enabled
- Then persisted ambient state is recovered
Conflicts
None identified yet.
Open Questions
- What is the default work-cycle cadence and task budget for ambient mode? Config exposes knobs; defaults are inferred from code.
Specification: Ambient Mode
Overview
Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. is implemented in crates/jcode-app-core/src/ (ambient.rs, ambient_runner.rs, ambient_scheduler.rs, and the ambient/ module) with shared types in crates/jcode-ambient-types. The scheduler drives work cycles; the runner executes tasks; directives and safety gates control what ambient may do. CLI control lives in src/cli/ (jcode ambient). This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
jcode server
└── ambient_scheduler.rs ──► work cycles
│
▼
ambient_runner.rs ──► tasks (garden/scout), directives
│
├── [ambient] config (directives, schedules)
├── safety / permissions gates (SAFETY_SYSTEM)
└── persistence (ambient status + log, durable)
│
▼
CLI: jcode ambient status|log|trigger|stop
TUITerminal User Interface: ambient status side panel / badge
Data Models
Ambient State (jcode-ambient-types)
| Field | Type | Constraints | Description |
|---|---|---|---|
| status | enum | not null | Running / idle / stopped. |
| directives | list | not null | Ambient instructions to execute. |
| log | list | append-only | Recent ambient activity. |
| schedule | config | nullable | Trigger schedule for cycles. |
API Contracts
CLI: jcode ambient
status— show ambient mode state.log— show recent ambient activity.trigger— run a work cycle now.stop— stop ambient mode.run-visible(hidden) — run a cycle visibly for debugging.
Sequences
Work cycle
Scheduler ticks (or trigger) → read directives → pick tasks (garden/scout)
Runner executes task through safety/permission gates
Results logged → state persisted → status events published to UI
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Same-process scheduler | ambient_scheduler.rs in app-core |
No separate daemon; shares server lifecycle. |
| Safety-gated runner | permissions + command-risk gates | Ambient autonomy must not bypass interactive safety (NFR-1MustAmbient actions shall be subject to the same permission/safety gates as interactive actions.). |
| Durable ambient state | persisted status/log | Survives reloads (NFR-3ShouldAmbient state must be durable across restarts.). |
| OvernightScheduled background processing performed while the user is away. hook | overnight processing module | Long-running consolidation fits idle windows. |
Risks and Unknowns
- Default cycle cadence and per-cycle budgets are inferred from code; they may need operator tuning.
- Ambient autonomy against live repositories carries inherent risk; safety coverage is critical.
Out of Scope
- A separate ambient daemon or distributed ambient workers.
- Ambient actions on behalf of other machines or cloud services.
Test Plan: Ambient Mode
Scope
Covers ambient scheduler, runner, state persistence, and safety gating. Out of scope: real overnight schedules and long-running cycle behavior in CIContinuous Integration.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Ambient state and lifecycle | crates/jcode-app-core/src/ambient_tests.rs |
Ambient starts, runs, stops, and persists correctly |
| TC-2 | Ambient runner behavior | crates/jcode-app-core/src/ambient_runner.rs tests |
Tasks execute through the runner |
| TC-3 | Scheduler behavior | crates/jcode-app-core/src/ambient_scheduler.rs tests |
Cycles trigger on schedule |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-4 | Ambient e2e | tests/e2e/ambient.rs |
Ambient work cycle runs end to end |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-5 | Ambient task requires permission | Action gated by safety system, no bypass |
| TC-6 | Server reload during ambient cycle | Ambient state recovered; cycle resumes |
| TC-7 | Risky command in ambient task | Passed through command-risk gate before execution |
Test Infrastructure
- E2E harness under
tests/e2e/with test support modules. - Durable-state fixtures for reload scenarios.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall run a background ambient scheduler on the server that executes work cycles. | TC-3, TC-4 |
| FR-2MustThe system shall execute directives (ambient instructions) and run tasks such as garden/scout activities. | TC-2 |
| FR-3MustThe system shall persist ambient state (status, log, directives) so it survives reloads. | TC-1, TC-6 |
| FR-4MustThe system shall gate ambient actions through a safety and permissions system. | TC-5, TC-7 |
| NFR-1MustAmbient actions shall be subject to the same permission/safety gates as interactive actions. | TC-5, TC-7 |
| NFR-3ShouldAmbient state must be durable across restarts. | TC-6 |
requirements
- What is the default work-cycle cadence and task budget for ambient mode? Config exposes knobs; defaults are inferred from code.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Harness API and SDKs
Overview
The harness API exposes jcode's agent runtime to external programs through a stable, versioned client API. A Unix-socket bridge (jcode api-bridge) translates versioned API requests onto the internal protocol, and Rust and TypeScript SDKs let applications launch jcode, drive sessions, and stream events. This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Application developers | A stable API to embed or script the jcode agent runtime |
| Maintainer | A versioned API surface that can evolve without breaking SDKSoftware Development Kit clients |
| Desktop/iOS app teams | Consume sessions and events through the harness API |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall expose a stable, versioned harness API for launching jcode, driving sessions, and streaming events. | Must | The system shall expose a stable, versioned harness API for launching jcode, driving sessions, and streaming events. |
| FR-2MustThe system shall serve the API through a Unix-socket bridge (`jcode api-bridge`) built into the released binary. | Must | The system shall serve the API through a Unix-socket bridge (jcode api-bridge) built into the released binary. |
| FR-3MustThe system shall provide a Rust SDKSoftware Development Kit (`jcode-sdk`) for the harness API. | Must | The system shall provide a Rust SDKSoftware Development Kit (jcode-sdk) for the harness API. |
| FR-4MustThe system shall provide a TypeScript SDKSoftware Development Kit (`@1jehuang/jcode-sdk`) published to npm. | Must | The system shall provide a TypeScript SDKSoftware Development Kit (@1jehuang/jcode-sdk) published to npm. |
| FR-5MustThe system shall ship platform launcher packages that let SDKSoftware Development Kit clients launch jcode without a Rust toolchain. | Must | The system shall ship platform launcher packages that let SDKSoftware Development Kit clients launch jcode without a Rust toolchain. |
| FR-6ShouldThe system shall keep SDKSoftware Development Kit and API behavior consistent (schema parity) between Rust and TypeScript clients. | Should | The system shall keep SDKSoftware Development Kit and API behavior consistent (schema parity) between Rust and TypeScript clients. |
| FR-7ShouldThe system shall expose session control (start, send message, cancel) and structured events. | Should | The system shall expose session control (start, send message, cancel) and structured events. |
| FR-8MayThe system shall expose capability coverage and schema snapshots for client-server negotiation. | May | The system shall expose capability coverage and schema snapshots for client-server negotiation. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustThe API shall be versioned so breaking changes do not silently break existing clients. | Must | Compatibility | The API shall be versioned so breaking changes do not silently break existing clients. |
| NFR-2MustSDKSoftware Development Kit clients must not need a Rust toolchain to use the API. | Must | Usability | SDKSoftware Development Kit clients must not need a Rust toolchain to use the API. |
| NFR-3ShouldEvent streaming over the bridge shall be low-overhead (Unix socket framing). | Should | Performance | Event streaming over the bridge shall be low-overhead (Unix socket framing). |
Constraints
- The bridge is Unix-only (listens on a Unix socket); Windows uses the pipe transport behind the same API.
- The bridge ships inside the released binary as
jcode api-bridge.
Acceptance Criteria
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FR-1MustThe system shall expose a stable, versioned harness API for launching jcode, driving sessions, and streaming events.
- Given a running
jcode api-bridge - When a client opens a session and sends a message
- Then events stream back to the client
- Given a running
- FR-2MustThe system shall serve the API through a Unix-socket bridge (`jcode api-bridge`) built into the released binary.
- Given the released binary
- When the user runs
jcode api-bridge - Then the bridge listens and serves versioned API clients
- FR-3MustThe system shall provide a Rust SDKSoftware Development Kit (`jcode-sdk`) for the harness API.
- Given the Rust SDKSoftware Development Kit
- When a client drives a session
- Then it connects and receives events
- FR-4MustThe system shall provide a TypeScript SDKSoftware Development Kit (`@1jehuang/jcode-sdk`) published to npm.
- Given the TypeScript SDKSoftware Development Kit package
- When installed from npm and used
- Then it drives sessions against a live bridge
- FR-5MustThe system shall ship platform launcher packages that let SDKSoftware Development Kit clients launch jcode without a Rust toolchain.
- Given an SDKSoftware Development Kit client on a supported platform
- When it launches jcode
- Then the platform launcher binary is used, no toolchain required
- FR-6ShouldThe system shall keep SDKSoftware Development Kit and API behavior consistent (schema parity) between Rust and TypeScript clients.
- Given Rust and TypeScript SDKs
- When schema parity tests run
- Then both clients agree on types and behaviors
- FR-7ShouldThe system shall expose session control (start, send message, cancel) and structured events.
- Given an active session via the API
- When the client cancels
- Then the cancel is honored
- FR-8MayThe system shall expose capability coverage and schema snapshots for client-server negotiation.
- Given a client and server
- When they negotiate capabilities
- Then incompatible surfaces are detected via schema snapshots
- NFR-1MustThe API shall be versioned so breaking changes do not silently break existing clients.
- Given a versioned API
- When a breaking change is introduced
- Then the version is bumped and old clients are not silently broken
- NFR-2MustSDKSoftware Development Kit clients must not need a Rust toolchain to use the API.
- Given a machine without a Rust toolchain
- When an SDKSoftware Development Kit client runs
- Then it works using the released binary bridge
- NFR-3ShouldEvent streaming over the bridge shall be low-overhead (Unix socket framing).
- Given a streaming session
- When events flow over the socket
- Then latency stays low with framed messages
Conflicts
None identified yet.
Open Questions
- Which API version is currently current, and what is the deprecation policy for older versions? Versioning exists but the policy is inferred from code.
Specification: Harness API and SDKs
Overview
The harness API is defined in crates/jcode-harness-api (client API, requests, events, capability coverage, schema snapshots) and served by crates/jcode-harness-api-server (the jcode api-bridge binary). The Rust SDKSoftware Development Kit (crates/jcode-sdk) and the TypeScript SDKSoftware Development Kit (sdk/typescript, published as @1jehuang/jcode-sdk) consume the bridge; platform launcher packages live under sdk/npm/. This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
SDKSoftware Development Kit clients (Rust: jcode-sdk, TypeScript: @1jehuang/jcode-sdk)
│
▼
jcode api-bridge (jcode-harness-api-server, Unix socket)
│ framing + translation
▼
jcode internal protocol (jcode-protocol)
│
▼
jcode server (agent runtime, sessions, events)
Data Models
Harness API client crate
requests.rs— versioned request types.events.rs— streamed event types.capability_coverage.rs— capability negotiation.schema_snapshot.rs— schema snapshots for parity.
API Contracts
CLI: jcode api-bridge (alias jcode api, Unix only)
Serves the versioned harness API on a Unix socket for SDKSoftware Development Kit clients.
SDKSoftware Development Kit launch
SDKSoftware Development Kit clients can launch jcode directly; platform launcher packages in sdk/npm/ provide the executable per platform (darwin-arm64, darwin-x64, linux-arm64, linux-x64, win32-arm64, win32-x64).
Sequences
Drive a session from an SDKSoftware Development Kit
SDKSoftware Development Kit → api-bridge (connect, negotiate version) → open session
SDKSoftware Development Kit → send message → server turn loop → events stream back to SDKSoftware Development Kit
SDKSoftware Development Kit → cancel/close session
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Versioned client crate | jcode-harness-api |
Stable surface independent of internal protocol evolution. |
| Bridge in released binary | jcode api-bridge |
SDKSoftware Development Kit users need no Rust toolchain (NFR-2MustSDKSoftware Development Kit clients must not need a Rust toolchain to use the API.). |
| Unix socket bridge | jcode-harness-api-server |
Low-overhead local IPCInter-Process Communication, versioned framing. |
| Schema parity testing | schema-parity.test.ts, capability_coverage.rs |
Keeps Rust and TS SDKs consistent (FR-6ShouldThe system shall keep SDKSoftware Development Kit and API behavior consistent (schema parity) between Rust and TypeScript clients.). |
| Platform launcher packages | sdk/npm/* |
One install story per platform. |
Risks and Unknowns
- The bridge is Unix-only by design; Windows support relies on the named-pipe transport behind the same API.
- Capability negotiation and version deprecation policy are only partially documented.
Out of Scope
- A network-exposed API (bridge is local IPCInter-Process Communication only).
- Full parity for every internal protocol feature; the API surface is intentionally smaller.
Test Plan: Harness API and SDKs
Scope
Covers harness API framing, translation, Rust SDKSoftware Development Kit behavior, TypeScript SDKSoftware Development Kit behavior, and schema parity. Out of scope: live long-running sessions in CIContinuous Integration (covered by scripted e2e suites).
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Bridge framing | crates/jcode-harness-api-server/src/framing_tests.rs |
Requests/events frame and unframe correctly |
| TC-2 | Bridge translation | crates/jcode-harness-api-server/src/translate_tests.rs |
Internal protocol translates to API types |
| TC-3 | Background progress | crates/jcode-harness-api-server/src/background_progress_tests.rs |
Progress events surface correctly |
| TC-4 | Rust SDKSoftware Development Kit behavior | crates/jcode-sdk/src/sdk_tests/ |
SDKSoftware Development Kit connects, drives sessions, streams events |
| TC-5 | Capability coverage | crates/jcode-harness-api/src/capability_coverage.rs tests |
Capability negotiation works |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-6 | TypeScript SDKSoftware Development Kit client tests | sdk/typescript/test/client.test.ts, structured.test.ts, launch.test.ts |
TS client drives sessions against the bridge |
| TC-7 | SDKSoftware Development Kit schema parity | sdk/typescript/test/schema-parity.test.ts |
Rust and TS SDKSoftware Development Kit types agree |
| TC-8 | SDKSoftware Development Kit e2e | scripts/test_sdk_e2e.sh |
End-to-end launch + session flow works |
| TC-9 | SDKSoftware Development Kit package test | scripts/test_sdk_package.sh |
Published npm tarball imports and works |
| TC-10 | SDKSoftware Development Kit parity in CIContinuous Integration | ci.yml SDKSoftware Development Kit parity job |
Rust/TS parity gates pass |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-11 | Bridge not running | SDKSoftware Development Kit reports a clear connection error |
| TC-12 | Version mismatch between client and server | Negotiation detects incompatible surfaces |
| TC-13 | Cancel mid-turn | Cancel honored, stream stops cleanly |
Test Infrastructure
- Mock harness for TS tests (
sdk/typescript/test/mock-harness.ts). - Live TS test scripts (
live-*.mjs) against a real bridge. scripts/test_sdk_e2e.sh,scripts/test_sdk_package.sh.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall expose a stable, versioned harness API for launching jcode, driving sessions, and streaming events. | TC-1, TC-2, TC-4 |
| FR-3MustThe system shall provide a Rust SDKSoftware Development Kit (`jcode-sdk`) for the harness API. | TC-4 |
| FR-4MustThe system shall provide a TypeScript SDKSoftware Development Kit (`@1jehuang/jcode-sdk`) published to npm. | TC-6 |
| FR-6ShouldThe system shall keep SDKSoftware Development Kit and API behavior consistent (schema parity) between Rust and TypeScript clients. | TC-7, TC-10 |
| FR-7ShouldThe system shall expose session control (start, send message, cancel) and structured events. | TC-13 |
| FR-8MayThe system shall expose capability coverage and schema snapshots for client-server negotiation. | TC-5, TC-12 |
requirements
- Which API version is currently current, and what is the deprecation policy for older versions? Versioning exists but the policy is inferred from code.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads.
Overview
jcode collects opt-out telemetry to understand product health: installation and upgrade funnels, auth success, onboarding progress, session start/end/crash, and turn-end usage. Events are queued client-side in jcode-telemetry-core, sent to https://telemetry.jcode.sh/v1/event, and ingested by a Cloudflare Worker into D1Cloudflare D1 SQLite database for dashboards and analysis. The full disclosure and opt-out model is documented in TELEMETRY.md. This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| Maintainer | Product-health metrics (DAUDaily Active Users, install funnel, token value) without violating user trust |
| End users | Clear disclosure of what is and is not collected, and an easy opt-out |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall emit structured telemetry events for install, upgrade, auth success, onboarding step, feedback, sponsored discovery, session lifecycle, and turn end. | Must | The system shall emit structured telemetry events for install, upgrade, auth success, onboarding step, feedback, sponsored discovery, session lifecycle, and turn end. |
| FR-2MustThe system shall queue and flush events asynchronously without blocking the agent. | Must | The system shall queue and flush events asynchronously without blocking the agent. |
| FR-3MustThe system shall respect opt-out via `JCODE_NO_TELEMETRY=1`, `DO_NOT_TRACK=1`, or a file marker. | Must | The system shall respect opt-out via JCODE_NO_TELEMETRY=1, DO_NOT_TRACK=1, or a file marker. |
| FR-4MustThe system shall never collect message content, prompts, or responses. | Must | The system shall never collect message content, prompts, or responses. |
| FR-5MustThe system shall ingest events server-side into a Cloudflare Worker backed by D1Cloudflare D1 SQLite database. | Must | The system shall ingest events server-side into a Cloudflare Worker backed by D1Cloudflare D1 SQLite database. |
| FR-6ShouldThe system shall provide analytics views (DAUDaily Active Users, install conversion funnel, token value, geography). | Should | The system shall provide analytics views (DAUDaily Active Users, install conversion funnel, token value, geography). |
| FR-7ShouldThe system shall support schema versioning for events so changes are trackable. | Should | The system shall support schema versioning for events so changes are trackable. |
| FR-8ShouldThe system shall capture session end reasons (including crashes) for reliability analysis. | Should | The system shall capture session end reasons (including crashes) for reliability analysis. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustEvent payloads must not contain session content or identifying message text. | Must | Privacy | Event payloads must not contain session content or identifying message text. |
| NFR-2ShouldFailed telemetry sends must not fail the client workflow. | Should | Reliability | Failed telemetry sends must not fail the client workflow. |
| NFR-3ShouldThe background queue must be bounded and non-blocking. | Should | Performance | The background queue must be bounded and non-blocking. |
| NFR-4ShouldServer-side ingestion must tolerate bursts (bounded D1Cloudflare D1 SQLite database usage). | Should | Availability | Server-side ingestion must tolerate bursts (bounded D1Cloudflare D1 SQLite database usage). |
Constraints
- Opt-out must be discoverable and documented (
TELEMETRY.md). - Schema and D1Cloudflare D1 SQLite database size must be controlled (migrations, size self-defense).
Acceptance Criteria
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FR-1MustThe system shall emit structured telemetry events for install, upgrade, auth success, onboarding step, feedback, sponsored discovery, session lifecycle, and turn end.
- Given an install and a session start
- When events fire
- Then install, session_start, and turn_end events are produced with the documented shape
- FR-2MustThe system shall queue and flush events asynchronously without blocking the agent.
- Given an active session
- When the agent is running
- Then telemetry sending does not block the turn loop
- FR-3MustThe system shall respect opt-out via `JCODE_NO_TELEMETRY=1`, `DO_NOT_TRACK=1`, or a file marker.
- Given
JCODE_NO_TELEMETRY=1set - When jcode runs
- Then no telemetry events are emitted
- Given
- FR-4MustThe system shall never collect message content, prompts, or responses.
- Given an active session with message content
- When events are produced
- Then no message content or prompt text is included
- FR-5MustThe system shall ingest events server-side into a Cloudflare Worker backed by D1Cloudflare D1 SQLite database.
- Given emitted events
- When they reach the ingestion endpoint
- Then they are stored in D1Cloudflare D1 SQLite database with the schema applied
- FR-6ShouldThe system shall provide analytics views (DAUDaily Active Users, install conversion funnel, token value, geography).
- Given ingested data
- When dashboards run
- Then DAUDaily Active Users, install funnel, and token-value views render
- FR-7ShouldThe system shall support schema versioning for events so changes are trackable.
- Given a new event shape
- When it is emitted
- Then the schema version is bumped and tracked
- FR-8ShouldThe system shall capture session end reasons (including crashes) for reliability analysis.
- Given a crashed session
- When the session ends
- Then the end reason (crash) is captured in the event
- NFR-1MustEvent payloads must not contain session content or identifying message text.
- Given any telemetry payload
- When inspected
- Then it contains no session content or message text
- NFR-2ShouldFailed telemetry sends must not fail the client workflow.
- Given a failing telemetry endpoint
- When the client continues
- Then the client workflow is unaffected
- NFR-3ShouldThe background queue must be bounded and non-blocking.
- Given high event volume
- When the queue fills
- Then the queue stays bounded (capacity 2048) and does not grow unbounded
- NFR-4ShouldServer-side ingestion must tolerate bursts (bounded D1Cloudflare D1 SQLite database usage).
- Given an event burst
- When the worker ingests it
- Then D1Cloudflare D1 SQLite database usage stays within the self-defense limits
Conflicts
None identified yet.
Open Questions
- What is the retention window for D1Cloudflare D1 SQLite database data and when are aggregates rolled up? Not documented beyond the dashboards.
Specification: TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads.
Overview
Client-side telemetry lives in crates/jcode-telemetry-core (async queue, lifecycle/onboarding trace, state support) with event structs in crates/jcode-usage-types (Install, Upgrade, Auth, SessionStart, TurnEnd, SessionLifecycle with end reasons, ErrorCounts). Server-side ingestion is a Cloudflare Worker in telemetry-worker/ (worker.js, D1Cloudflare D1 SQLite database schema, 24 migrations). This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
client (jcode-telemetry-core, bounded queue cap 2048)
│ HTTPS POST /v1/event
▼
telemetry.jcode.sh (Cloudflare Worker)
│ validation + schema
▼
D1Cloudflare D1 SQLite database database (schema.sql + migrations/0001..0024)
│
▼
dashboards (DAUDaily Active Users, install funnel, token value, geo, health, users, discovery)
Data Models
Event Types (jcode-usage-types)
| Event | Fields | Description |
|---|---|---|
| InstallEvent | platform, version | Install funnel event. |
| UpgradeEvent | from_version, to_version | Upgrade funnel event. |
| AuthEvent | provider, method | Auth success/failure. |
| OnboardingStepEvent | step | Onboarding progress. |
| SessionLifecycleEvent | reason | Includes SessionEndReason (e.g. crash). |
| TurnEndEvent | usage | TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips).-level token usage. |
| ErrorCounts | category | Error aggregates. |
Events are schema-versioned (schema version 6 in jcode-telemetry-core).
API Contracts
Client -> Worker: POST https://telemetry.jcode.sh/v1/event
Body: JSON event object with shared metadata (version, platform, session id, coarse geography added server-side).
Sequences
Event emission
Trigger (install/session start/turn end/...) → build event → push to bounded queue
Background taskServer-side job running independently of the current turn. flushes queue → POST /v1/event → worker validates → D1Cloudflare D1 SQLite database insert
Opt-out env var set → queue disabled → no events emitted
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Bounded background queue | BACKGROUND_QUEUE_CAPACITY: 2048 |
Non-blocking, bounded memory (NFR-3ShouldThe background queue must be bounded and non-blocking.). |
| Cloudflare Worker + D1Cloudflare D1 SQLite database | telemetry-worker/ |
Cheap serverless ingestion with SQL analytics. |
| Explicit opt-out | env vars or file marker | Trust and compliance (FR-3MustThe system shall respect opt-out via `JCODE_NO_TELEMETRY=1`, `DO_NOT_TRACK=1`, or a file marker.). |
| No content collection | event structs exclude messages | Privacy boundary (NFR-1MustEvent payloads must not contain session content or identifying message text.). |
| D1Cloudflare D1 SQLite database size self-defense | migrations + size controls | Keeps cost and availability bounded. |
Risks and Unknowns
- Server-side dashboards depend on D1Cloudflare D1 SQLite database data quality and retention; retention is not documented.
- Opt-out coverage must be re-checked as new event sites are added.
Out of Scope
- Individual-session profiling or user tracking beyond aggregate product metrics.
- Collection of prompts, responses, or message content by design.
Test Plan: TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads.
Scope
Covers client-side event emission, queue behavior, opt-out, lifecycle/onboarding tracing, and server-side worker ingestion. Out of scope: production D1Cloudflare D1 SQLite database data volume behavior.
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Client telemetry core | crates/jcode-telemetry-core/src/tests.rs |
Events queue and flush correctly |
| TC-2 | Lifecycle event tracing | crates/jcode-telemetry-core/src/lifecycle.rs tests |
SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. lifecycle events produced with correct end reasons |
| TC-3 | Onboarding trace | crates/jcode-telemetry-core/src/onboarding_trace.rs tests |
Onboarding steps traced correctly |
| TC-4 | Client-side telemetry app-core | crates/jcode-app-core/src/telemetry_tests.rs |
App-level telemetry integration works |
| TC-5 | Usage accounting | crates/jcode-app-core/src/usage_tests.rs |
Token usageCounting and limits for tokens consumed against provider subscriptions. totals correct |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-6 | Worker ingestion | telemetry-worker/test/worker.test.mjs |
Worker validates and stores events |
| TC-7 | Token-value view | telemetry-worker/test/token-value.test.mjs |
Token-value aggregation works |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-8 | TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. endpoint down | Client workflow unaffected; send fails silently |
| TC-9 | Queue full | Queue bounded, no unbounded growth |
| TC-10 | Opt-out set | No events emitted |
Test Infrastructure
telemetry-worker/test/*.mjsfor worker behavior.- Client queue fixtures for boundedness.
- Opt-out env-var test scenarios.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall emit structured telemetry events for install, upgrade, auth success, onboarding step, feedback, sponsored discovery, session lifecycle, and turn end. | TC-1, TC-2 |
| FR-2MustThe system shall queue and flush events asynchronously without blocking the agent. | TC-1, TC-8 |
| FR-3MustThe system shall respect opt-out via `JCODE_NO_TELEMETRY=1`, `DO_NOT_TRACK=1`, or a file marker. | TC-10 |
| FR-5MustThe system shall ingest events server-side into a Cloudflare Worker backed by D1Cloudflare D1 SQLite database. | TC-6 |
| FR-7ShouldThe system shall support schema versioning for events so changes are trackable. | TC-6 |
| FR-8ShouldThe system shall capture session end reasons (including crashes) for reliability analysis. | TC-2 |
| NFR-2ShouldFailed telemetry sends must not fail the client workflow. | TC-8 |
| NFR-3ShouldThe background queue must be bounded and non-blocking. | TC-9 |
requirements
- What is the retention window for D1 data and when are aggregates rolled up? Not documented beyond the dashboards.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |
Pipeline Progress ?⚪ not started not yet begun✏️ draft initial version🔍 in review under review🚧 in progress actively worked on⛔ blocked waiting on dependency✅ done completed⏭️ skipped not applicable
Requirements: Installation and Auto-Update
Overview
jcode distributes itself through a multi-platform installer plus GitHub Releases, and keeps itself current with an auto-update pipeline that downloads new binaries and hot-reloads the server without dropping sessions. Release automation covers Linux, macOS, and Windows (including signing) and posts release notes to Discord. This feature was reverse-engineered from the existing codebase during an SDLC sync; it documents already-implemented functionality.
Stakeholders
| Stakeholder | Interest |
|---|---|
| End users | Simple one-command install, reliable updates, and painless uninstall on every platform |
| Maintainer | Reproducible releases, versioned immutable binaries, and safe hot-reload updates |
Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Requirement |
|---|---|---|
| FR-1MustThe system shall provide one-command installers on Linux, macOS, and Windows (`https://jcode.sh/install` and `install.ps1`). | Must | The system shall provide one-command installers on Linux, macOS, and Windows (https://jcode.sh/install and install.ps1). |
| FR-2MustThe system shall provide uninstallers for each platform. | Must | The system shall provide uninstallers for each platform. |
| FR-3MustThe system shall check for updates against GitHub Releases and support stable and main update channels. | Must | The system shall check for updates against GitHub Releases and support stable and main update channels. |
| FR-4MustThe system shall download and install new versions into immutable versioned directories (`~/.jcode/builds/versions/<version>/`) and repoint launcher channels. | Must | The system shall download and install new versions into immutable versioned directories (~/.jcode/builds/versions/<version>/) and repoint launcher channels. |
| FR-5MustThe system shall support hot-reloading the server into the new binary without dropping sessions (exec into new binary, clients reconnect). | Must | The system shall support hot-reloading the server into the new binary without dropping sessions (exec into new binary, clients reconnect). |
| FR-6ShouldThe system shall support local quick releases (`quick-release.sh`) and CIContinuous Integration release automation across platforms. | Should | The system shall support local quick releases (quick-release.sh) and CIContinuous Integration release automation across platforms. |
| FR-7ShouldThe system shall handle divergence gracefully when the local clone and remote differ during a git-pull based update. | Should | The system shall handle divergence gracefully when the local clone and remote differ during a git-pull based update. |
| FR-8MayThe system shall post release announcements to Discord. | May | The system shall post release announcements to Discord. |
Non-Functional Requirements
Order rows by priority: Must first, then Should, then May.
| ID | Priority | Category | Requirement |
|---|---|---|---|
| NFR-1MustUpdate must not corrupt the current install if interrupted. | Must | Reliability | Update must not corrupt the current install if interrupted. |
| NFR-2MustHot-reload must preserve active sessions and clients. | Must | Availability | Hot-reload must preserve active sessions and clients. |
| NFR-3ShouldDownloads must be validated (signed/hash-checked) before activation. | Should | Security | Downloads must be validated (signed/hash-checked) before activation. |
| NFR-4ShouldUpdates should be non-intrusive and respect `--no-update`. | Should | Usability | Updates should be non-intrusive and respect --no-update. |
Constraints
- Version layout and launcher symlinks are documented in AGENTS.md install notes.
- Release channels: stable and main.
Acceptance Criteria
Order criteria by FRs first (sorted by ID), then NFRs (sorted by ID).
- FR-1MustThe system shall provide one-command installers on Linux, macOS, and Windows (`https://jcode.sh/install` and `install.ps1`).
- Given a clean machine on any supported OS
- When the install command runs
- Then jcode installs and runs
- FR-2MustThe system shall provide uninstallers for each platform.
- Given an installed jcode
- When the uninstaller runs
- Then jcode and its launcher are removed
- FR-3MustThe system shall check for updates against GitHub Releases and support stable and main update channels.
- Given an update channel configured
- When a new release exists
- Then the update is detected
- FR-4MustThe system shall download and install new versions into immutable versioned directories (`~/.jcode/builds/versions/<version>/`) and repoint launcher channels.
- Given an available update
- When it downloads
- Then the new binary lands in a versioned directory and the channel is repointed
- FR-5MustThe system shall support hot-reloading the server into the new binary without dropping sessions (exec into new binary, clients reconnect).
- Given an active server with clients
- When the server reloads into the new binary
- Then sessions persist and clients reconnect
- FR-6ShouldThe system shall support local quick releases (`quick-release.sh`) and CIContinuous Integration release automation across platforms.
- Given release tooling
- When a release is cut
- Then the quick or CIContinuous Integration flow produces a release
- FR-7ShouldThe system shall handle divergence gracefully when the local clone and remote differ during a git-pull based update.
- Given a divergent local clone
- When a git-pull update runs
- Then divergence is handled without breaking the install
- FR-8MayThe system shall post release announcements to Discord.
- Given a published release
- When announcements are enabled
- Then a Discord post is created
- NFR-1MustUpdate must not corrupt the current install if interrupted.
- Given an interrupted download
- When the update retries
- Then the current install remains usable
- NFR-2MustHot-reload must preserve active sessions and clients.
- Given a reload with open sessions
- When the new binary starts
- Then all sessions are preserved
- NFR-3ShouldDownloads must be validated (signed/hash-checked) before activation.
- Given a downloaded binary
- When it is activated
- Then it is validated before use
- NFR-4ShouldUpdates should be non-intrusive and respect `--no-update`.
- Given
--no-update - When jcode starts
- Then no update check runs
- Given
Conflicts
None identified yet.
Open Questions
- Are release binaries signed for all platforms, or only Windows?
RELEASING.mddocuments Windows signing; macOS/Linux coverage is inferred.
Specification: Installation and Auto-Update
Overview
Installers live in scripts/ (install.sh, install.ps1, install_release.sh, uninstall.*), release automation in .github/workflows/release.yml and scripts/quick-release.sh, and the update engine in crates/jcode-update-core (download from GitHub Releases, git-pull handling, divergence detection). Hot-reload on update execs the server into a new binary, reusing the same PID and socket. This document was reverse-engineered from the existing codebase during an SDLC sync.
Architecture
User machine
├── launcher: ~/.local/bin/jcode (symlink into builds/current or builds/stable)
├── builds/versions/<version>/jcode (immutable binaries)
├── builds/stable/jcode (stable channel)
├── builds/current/jcode (self-dev channel)
└── scripts/install.sh / install.ps1 / install_release.sh / uninstall.*
Release pipeline
├── .github/workflows/release.yml (Linux/macOS/Windows builds, signing)
├── scripts/quick-release.sh (local ~2.5-min release)
├── scripts/generate_release_notes.sh
└── scripts/post_discord_release.py
Data Models
Version layout
| Path | Role |
|---|---|
~/.jcode/builds/versions/<version>/jcode |
Immutable versioned binary. |
~/.jcode/builds/stable/jcode |
Stable channel pointer. |
~/.jcode/builds/current/jcode |
Self-devCanary self-development mode that runs a freshly built binary on a shared server./source-build channel pointer. |
~/.jcode/builds/shared-server/jcode |
Symlink into a version, used by the shared daemon. |
API Contracts
Update check (jcode-update-core)
- Queries GitHub Releases for the configured channel (
stable/main). - Downloads, extracts, and stages the new binary into a versioned directory.
- Handles
git pull-based source updates with divergence detection.
Sequences
Auto-update hot reload
jcode update → check releases → download + extract → stage into builds/versions/<v>
→ server reload → exec new binary (same PID, same socket) → clients reconnect
→ launcher repointed to new version
Technical Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Immutable versioned binaries | builds/versions/<version>/ |
Atomic installs and clean rollback. |
| Exec-based hot reload | reload into new binary | Preserves sessions and socket (NFR-2MustHot-reload must preserve active sessions and clients.). |
| Separate update crate | jcode-update-core |
Isolates download/pull/divergence logic. |
| Install-script funnel | scripts/install.sh + telemetry install events |
Measures conversion and reach. |
| Quick vs CIContinuous Integration release | quick-release.sh vs release.yml |
Fast local iteration vs reproducible artifacts. |
Risks and Unknowns
- Binary signing coverage outside Windows is not fully documented.
- Divergence handling for git-pull updates depends on local clone state.
Out of Scope
- A system package manager integration (Homebrew exists for macOS; others inferred).
- Containerized distribution of the agent runtime.
Test Plan: Installation and Auto-Update
Scope
Covers installer correctness, update conversion, Windows launcher lifecycle, and Discord release posting. Out of scope: live production release flows (verified in CIContinuous Integration release pipeline).
Unit Tests
| ID | Description | Input | Expected Output |
|---|---|---|---|
| TC-1 | Update core logic | crates/jcode-update-core tests |
Update download/stage/activate logic works |
Integration Tests
| ID | Description | Preconditions | Expected Outcome |
|---|---|---|---|
| TC-2 | Install conversion | scripts/test_install_conversion.sh |
Install script converts download to working install |
| TC-3 | Windows launcher install lifecycle | scripts/test_windows_launcher_install.ps1 |
Launcher installs and runs on Windows |
| TC-4 | Release Discord posting | scripts/test_post_discord_release.py |
Discord post generated correctly |
| TC-5 | Windows smoke in CIContinuous Integration | windows-smoke.yml, freebsd-smoke.yml |
Platform smoke tests pass |
Edge Cases and Failure Scenarios
| ID | Scenario | Expected Behavior |
|---|---|---|
| TC-6 | Interrupted download | Current install stays usable; retry safe |
| TC-7 | Divergent local clone during git-pull update | Divergence handled without breaking install |
| TC-8 | ReloadHot-reloading the server into a new binary without dropping clients or sessions. with open sessions | Sessions preserved; clients reconnect |
Test Infrastructure
- CIContinuous Integration release/smoke workflows (
release.yml,windows-smoke.yml,freebsd-smoke.yml). - Python and PowerShell test scripts for install/Discord flows.
Coverage Matrix
| Requirement | Test Cases |
|---|---|
| FR-1MustThe system shall provide one-command installers on Linux, macOS, and Windows (`https://jcode.sh/install` and `install.ps1`). | TC-2 |
| FR-2MustThe system shall provide uninstallers for each platform. | TC-3 |
| FR-5MustThe system shall support hot-reloading the server into the new binary without dropping sessions (exec into new binary, clients reconnect). | TC-8 |
| FR-8MayThe system shall post release announcements to Discord. | TC-4 |
| NFR-1MustUpdate must not corrupt the current install if interrupted. | TC-6 |
| NFR-2MustHot-reload must preserve active sessions and clients. | TC-8 |
requirements
- Are release binaries signed for all platforms, or only Windows?
RELEASING.mddocuments Windows signing; macOS/Linux coverage is inferred.
Vocabulary
Domain Terms
| Term | Definition |
|---|---|
| Account failoverAutomatic retry of a turn on the next pool account when the active one hits a usage limit. | Automatic retry of a turn on the next pool account when the active one hits a usage limit. |
| Account routerThe startup surface that lists saved accounts, cached quotas, and available quota resets. | The startup surface that lists saved accounts, cached quotas, and available quota resets. |
| Ambient modeProactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. | Proactive background agent (OpenClaw-style) with work cycles, garden/scout tasks, and overnight processing. |
| AppletAn agent-mounted UI instance, persisted per session under `~/.jcode/agent_applets/`. | An agent-mounted UI instance, persisted per session under ~/.jcode/agent_applets/. |
| CanaryA session or build used to test new code against real usage. | A session or build used to test new code against real usage. |
| CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. | Opt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. |
| Comm channelA message channel between swarm members (direct message, broadcast). | A message channel between swarm members (direct message, broadcast). |
| CompactionReducing accumulated context (and the KV cache) when a session grows too large. | Reducing accumulated context (and the KV cacheProvider-side key-value cache for repeated prompt prefixes.) when a session grows too large. |
| ConsolidationBackground process that merges and strengthens memories over time. | Background process that merges and strengthens memories over time. |
| Content block / partA typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). | A typed piece of a message (text, reasoning, thinking, tool use, tool result, image, compaction). |
| Custom web searchA user-configured HTTP JSON search engine declared under `[websearch.custom]` in `~/.jcode/config.toml`. | A user-configured HTTP JSON search engine declared under [websearch.custom] in ~/.jcode/config.toml. |
| Effort / reasoningThe configured reasoning depth for a model. | The configured reasoning depth for a model. |
| EmbeddingA numeric vector representing text, computed locally with an ONNX MiniLM model. | A numeric vector representing text, computed locally with an ONNXOpen Neural Network Exchange MiniLM model. |
| Harness API / API bridgeThe stable versioned client API (`jcode api-bridge`) and the SDKs that consume it. | The stable versioned client API (jcode api-bridge) and the SDKs that consume it. |
| HibernationEvicting an idle session from memory, with transparent wake on the next interaction. | Evicting an idle session from memory, with transparent wake on the next interaction. |
| Memory graphThe persistent graph of extracted memories, skills, and relationships. | The persistent graph of extracted memories, skills, and relationships. |
| MessageA single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. | A single exchange in a session, carrying a role (User/Assistant) and a list of content blocks. |
| Pairing / gatewayQR-code pairing of the iOS app to the desktop daemon through a gateway. | QR-code pairing of the iOS app to the desktop daemon through a gateway. |
| Pinned todoA todo pinned in the TUI todo list, kept collapsed with the overall progress display. | A todo pinned in the TUITerminal User Interface todo list, kept collapsed with the overall progress display. |
| Plan DAG / plan itemThe directed acyclic graph of tasks a swarm coordinator builds. | The directed acyclic graph of tasks a swarm coordinator builds. |
| Productivity reportA scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. | A scan of local session transcripts rendered as Markdown plus a shareable PNG dashboard. |
| ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). | A source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). |
| Recall / injectionRetrieving relevant memories and inserting them into the prompt. | Retrieving relevant memories and inserting them into the prompt. |
| ReloadHot-reloading the server into a new binary without dropping clients or sessions. | Hot-reloading the server into a new binary without dropping clients or sessions. |
| Restart snapshotA saved snapshot of sessions and state used to resume after a reboot. | A saved snapshot of sessions and state used to resume after a reboot. |
| Resume targetAn external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). | An external session source that can be resumed (jcode, Claude Code, Codex, Pi, OpenCode, Cursor). |
| Self-devCanary self-development mode that runs a freshly built binary on a shared server. | CanaryA session or build used to test new code against real usage. self-development mode that runs a freshly built binary on a shared server. |
| SessionA unit of interaction with the agent: a persisted conversation with an id, title, and status. | A unit of interaction with the agent: a persisted conversation with an id, title, and status. |
| Soft interruptQueueing a follow-up message mid-run without discarding the in-flight turn. | Queueing a follow-up message mid-run without discarding the in-flight turn. |
| Sponsored discoveryCatalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. | Catalog-based tool discovery that reports privacy-safe funnel telemetry per discover_tools attempt. |
| SwarmMulti-agent coordination where a coordinator delegates tasks to worker agents. | Multi-agent coordination where a coordinator delegates tasks to worker agents. |
| Tool / tool call / tool resultA capability the agent can invoke; the request and its outcome. | A capability the agent can invoke; the request and its outcome. |
| Transcript sharingOptional opt-in program that uploads full session transcripts with secret redaction to a private store. | Optional opt-in program that uploads full session transcripts with secret redaction to a private store. |
| TransportThe connection mode to a provider (HTTPS, WebSocket, or Claude CLI). | The connection mode to a provider (HTTPS, WebSocket, or Claude CLI). |
| TurnOne pass through the agent loop (assistant output, tool execution, provider round-trips). | One pass through the agent loop (assistant output, tool execution, provider round-trips). |
| UltrafastThe OpenAI speed tier above Fast, applied through the speed picker or a hotkey. | The OpenAI speed tier above Fast, applied through the speed picker or a hotkey. |
| user_responseThe tool that returns a Markdown response to a Desktop-capable client. | The tool that returns a Markdown response to a Desktop-capable client. |
Technical Terms
| Term | Definition |
|---|---|
| Background taskServer-side job running independently of the current turn. | Server-side job running independently of the current turn. |
| Budget ratchetCI-enforced limits (warnings, panics, code size, etc.) in `scripts/`. | CIContinuous Integration-enforced limits (warnings, panics, code size, etc.) in scripts/. |
| consent_versionVersion of the explicit transcript-sharing consent carried on transcript uploads. | Version of the explicit transcript-sharing consent carried on transcript uploads. |
| Debug socketA secondary socket that broadcasts TUI state for debugging/automation. | A secondary socket that broadcasts TUITerminal User Interface state for debugging/automation. |
| External credential sourceReusing credentials from other CLIs (e.g. `~/.codex/auth.json`, `~/.claude/.credentials.json`). | Reusing credentials from other CLIs (e.g. ~/.codex/auth.json, ~/.claude/.credentials.json). |
| Failover / fallback / routeProvider selection, fallback on failure, and routing between providers/models. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.). selection, fallback on failure, and routing between providers/models. |
| HooksUser-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). | User-defined scripts fired at lifecycle points (turn start/end, pre-tool gate, session start/end). |
| Info widgetA TUI panel (session info, model, provider, usage) shown in the interface. | A TUITerminal User Interface panel (session info, model, provider, usage) shown in the interface. |
| JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. | Platform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. |
| JCodeMobileSwiftUI iOS app shell built on JCodeKit for pairing, chat, sessions, and settings views. | SwiftUI iOS app shell built on JCodeKitPlatform-free Swift client core for the iOS app owning gateway pairing, transport, and wire codecs. for pairing, chat, sessions, and settings views. |
| JevTyped Decisions transport used for bring-your-own-key memory, browser, and voice calls. | Typed Decisions transport used for bring-your-own-key memory, browser, and voice calls. |
| KV cacheProvider-side key-value cache for repeated prompt prefixes. | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-side key-value cache for repeated prompt prefixes. |
| MermaidDiagram rendering inside the terminal. | Diagram rendering inside the terminal. |
| Mil / BilCompact abbreviations for million and billion token counts shown in usage cards. | Compact abbreviations for million and billion token counts shown in usage cards. |
| NDJSONNewline-Delimited JSON | Newline-delimited JSON used as the client-server wire framing. |
| OAuth / API key / device codeAuthentication methods supported by the login flows. | Authentication methods supported by the login flows. |
| OvernightScheduled background processing performed while the user is away. | Scheduled background processing performed while the user is away. |
| QuickJSThe embedded JavaScript engine that runs the Codemode sandbox. | The embedded JavaScript engine that runs the CodemodeOpt-in mode where the model writes a short JavaScript program that orchestrates tool calls instead of issuing them one turn at a time. sandbox. |
| Service tier / premium modeProvider-specific access tiers (e.g. priority/flex, copilot one/zero). | ProviderA source of model completions (Anthropic, OpenAI, Gemini, Bedrock, OpenRouter, etc.).-specific access tiers (e.g. priority/flex, copilot one/zero). |
| Session journalAppend-only JSONL log of a session plus a snapshot JSON file under `~/.jcode/sessions/`. | Append-only JSONL log of a session plus a snapshot JSON file under ~/.jcode/sessions/. |
| Session reducerPure state-machine function mapping server events plus local intents to transcript and app state. | Pure state-machine function mapping server events plus local intents to transcript and app state. |
| Side panelA collapsible TUI panel (e.g. session list, usage overlay). | A collapsible TUITerminal User Interface panel (e.g. session list, usage overlay). |
| Spawn hookHook that runs when a new session is spawned. | Hook that runs when a new session is spawned. |
| TelemetryAnonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. | Anonymous minimal usage statistics with explicit opt-out plus optional versioned transcript uploads. |
| Token usageCounting and limits for tokens consumed against provider subscriptions. | Counting and limits for tokens consumed against provider subscriptions. |
| TUITerminal User Interface | Terminal user interface. |
| Unix socket / named pipeLocal IPC transport (Unix sockets, or Windows named pipes behind the same API). | Local IPCInter-Process Communication transport (Unix sockets, or Windows named pipes behind the same API). |
Acronyms and Abbreviations
| Abbreviation | Expansion |
|---|---|
| ACPAgent Client Protocol | Agent Client Protocol |
| APNsApple Push Notification service | Apple Push Notification service |
| BYOKBring Your Own Key | Bring Your Own Key |
| CIContinuous Integration | Continuous Integration |
| D1Cloudflare D1 SQLite database | Cloudflare D1Cloudflare D1 SQLite database SQLite database |
| DAUDaily Active Users | Daily Active Users |
| IPCInter-Process Communication | Inter-Process Communication |
| JWTJSON Web Token | JSON Web Token |
| NDJSONNewline-Delimited JSON | Newline-Delimited JSON |
| OAuthOpen Authorization | Open Authorization |
| ONNXOpen Neural Network Exchange | Open Neural Network Exchange |
| R2Cloudflare R2 object storage | Cloudflare R2Cloudflare R2 object storage object storage |
| SDKSoftware Development Kit | Software Development Kit |
| STTSpeech-to-Text | Speech-to-Text |
| TUITerminal User Interface | Terminal User Interface |