Audience: engineers working on the
intentdRust backend (packages/intentd). Companion document: PROTOCOL.md — the wire-protocol reference (transport, JSON-RPC envelope, method catalog, events). This page records the durable architecture and dependency rules; the historical porting spec (IMPLEMENTATION_SPEC.md) has been removed from the tree and remains available in git history.
intentd is a long-lived local daemon that is the single source of truth for
Intent's domain model. Clients (the desktop UI, a mobile app, a CLI, or
another agent acting as an MCP client) connect over a JSON-RPC 2.0 API and
drive everything: workspaces, notes, tasks, comments, agents, git, pull
requests, scripts, terminals, files, and events.
The daemon embeds:
- A JSON-RPC router serving the full method catalog (see the protocol docs), reusing one set of service implementations across every transport.
- An ACP client that spawns provider CLIs (auggie, claude-code, codex, … —
see the
intent-providersregistry for the full set) over piped stdio and multiplexes many concurrent agent sessions. - An MCP server exposed back to the agents so an agent can call the same
workspace API the FE uses (
note.*,task.*,agent.delegate, …) — the agent→BE callback loop. Every agent gets its own bridge address so tool calls are attributable to the calling agent. How the bridge reaches the provider CLI is a per-provider capability in theintent-providersregistry — four delivery mechanisms today: a--mcp-configtemp file (auggie), anOPENCODE_CONFIG_CONTENTenvmcpblock (opencode, and unsloth, which rides the opencode binary — see "Local models" below), ACPsession/newmcpServers(claude-code, codex, droid, grok), and — for pi, which has no native MCP support and whose pi-acp adapter dropssession/newmcpServers— a per-agent wrapper script (set asPI_ACP_PI_COMMAND) that launches pi with a bundled extension (pi -e); the extension connects to the agent's bridge viaINTENTD_MCP_BRIDGE_ADDRfrom the inherited environment and registers the workspace tools throughpi.registerTool.workspace_apiresults are shaped by theworkspaceApi.*settings — TOON encoding of object/array results plus an oversized-output redirect to the workspace folder'stool-outputs/directory (PROTOCOL.md §5.12 / §5.22). - A provider-agnostic source-control client (the
SourceControltrait;GitHubSourceControlvia octocrab) for PR/issue/review/check-run/mergeability. - An optional context engine abstraction whose only current implementation
shells out to
auggie, degrading gracefully when unavailable. - A persistence layer (SQLite + a file tree) that owns all durable state.
- An event bus + append-only event log delivered to subscribers as JSON-RPC notifications.
The overriding invariant, carried over from the original Intent Electron app:
transports are thin; services are shared. Every transport (the local
listener — UDS on Unix, a named pipe on Windows — TCP/TLS, the agent-facing
MCP server) dispatches into the same service layer. The Windows pipe name is
derived from the resolved socket path (\\.\pipe\intentd-<hash16>, first 16
hex chars of SHA-256 over the normalized path — intent-transport's
pipe_name_for_socket_path, mirrored byte-for-byte by cloudlands-fe's
intentd-pipe-name.ts; see PROTOCOL.md §1.1); framing and protocol are
identical on both local transports.
A single Cargo workspace with one binary crate intentd and library crates:
packages/intentd/ # cargo workspace root
├── Cargo.toml # [workspace] members
└── crates/
├── intentd/ # binary: CLI + daemon entrypoint (clap)
├── intent-core/ # domain model, ids, errors, config, events (leaf)
├── intent-store/ # SQLite + file-tree persistence (repositories)
├── intent-services/ # business logic (the shared service surface)
├── intent-acp/ # ACP client, session multiplexing, agent→BE MCP server
├── intent-providers/ # provider registry, launch arg/env assembly
├── intent-sourcecontrol/ # SourceControl trait + GitHubSourceControl (octocrab)
├── intent-git/ # git wrappers + worktree/CoW-checkout create/lock + repo cache
├── intent-context/ # ContextEngine trait + auggie impl
├── intent-pty/ # unified PTY host: terminals + scripts, scrollback, attach
├── intent-search/ # BE-owned search: ripgrep-equivalent content/path search
│ # + adapters over store/session/event/memory/note data
├── intent-js/ # JavaScript execution engine for agent-supplied code
│ # (QuickJS via rquickjs), async host bindings, timeouts
├── intent-linear/ # LinearEngine + DTOs for the linear.* surface
├── intent-sentry/ # SentryEngine + DTOs for the sentry.* surface
└── intent-transport/ # local (UDS / Windows named pipe) + TCP/TLS
# listeners, JSON-RPC router, auth,
# client.hello → clientId mapping
Several cross-cutting features are service modules rather than crates,
wired per the dependency rules below: drafts (services::drafts over a store
table), client identity (a transport concern plus a small client store
table), the Code Changes Review domain (services::file_tracking,
services::diffs, services::accept_changes, services::metrics), the
Agent-Ecosystem modules (services::rules, services::specialists,
services::mcp_servers, services::memories), and the Integrations & Ops
modules (services::token_usage, services::session_stats,
services::setup_scripts, services::repo_config). They depend only on the
lower layers (store, git, sourcecontrol, context, providers) and the event
bus — never on the transport or on each other directly.
| Module / crate | Responsibility | May depend on |
|---|---|---|
| intentd (bin) | CLI parsing (serve/call/status/stop/doctor), daemonization, wiring | every crate |
| intent-core | WorkspaceId/NoteId/AgentId newtypes, Error/Result, Config, event types, traits | (none — leaf) |
| intent-store | SQLite pool, migrations, repositories, file layout, locking | core |
| intent-services | note/task/comment/workspace/agent/git/pr/script/file/event/draft logic plus the Agent-Ecosystem, Code-Changes-Review, and Integrations & Ops service modules | core, store, git, sourcecontrol, acp, context, providers, pty, search, linear, sentry |
| intent-acp | spawn providers over stdio, handshake, session new/load/prompt/cancel, streaming, client-served fs/terminal/permission, agent→BE MCP server | core, providers, pty, js; calls back into services via a trait |
| intent-providers | ProviderConfig registry, arg/env builder, capability/quirks (no static model catalogs — model discovery is dynamic via models.list, and no provider carries a default designation) |
core |
| intent-sourcecontrol | SourceControl trait + GitHubSourceControl (octocrab): PR/issue/review/check-run/mergeability, retry | core |
| intent-git | status/stage/commit/branches, worktree create + lock, CoW reflink probe/clone (macOS clonefile(2) whole-tree fast path with best-effort walk fallback, Linux ioctl(FICLONE)) for cache-hydrated CoW workspace checkouts, hidden repo cache (repo_cache) of read-only GitHub clones backing cache-hydrated workspace creation |
core |
| intent-context | ContextEngine trait + AuggieContextEngine + discovery | core |
| intent-pty | unified portable-pty host for terminals and scripts: scrollback ring buffers (script output is also copied by an output sink to per-run logs under <data_dir>/script-output/, which script.output reads, so it survives restart and archive), multi-client attach, service/command modes, auto-restart, URL/port detection |
core |
| intent-search | BE-owned search.*: ripgrep-equivalent content search (grep + ignore + globset), path/glob search, adapters over persisted sessions/events/memories/notes/codebase; per-request cancellation |
core, store |
| intent-js | QuickJS-based JavaScript engine for agent-supplied code: async host bindings, wall-clock timeouts | (none — leaf) |
| intent-linear | LinearEngine + DTOs for the linear.* surface (typed GraphQL over reqwest) |
core |
| intent-sentry | SentryEngine + DTOs for the sentry.* surface (REST over reqwest) |
core |
| intent-transport | local (UDS on Unix, named pipe on Windows) + TCP listeners, TLS, bearer auth, origin allow-list, JSON-RPC router, heartbeat, lifecycle, client.hello handshake + live-connection→clientId map |
core, services |
The node contract, private node link and checkpoint format define the approved target; they are not implemented at the current pins. Phase 1 includes static remote nodes, the in-process local node, hub durability/recovery and full per-agent CoW retirement. Per-agent CoW retirement does not wait for the local node. Current sandbox behavior is recorded separately below until removal.
Head owns durable orchestration: SQLite, transcripts, permissions, placement, leases, prompts, hub refs, notes/tasks, event delivery and explicit publication. Node owns everything touching a checkout or provider process: ACP and its fs/terminal callbacks, provider CLI, QuickJS workspace API, stdio MCP, scripts, process accounting, idle reap, journal and checkpoint capture. A remote agent never leaves a child handle or ACP connection in head's AgentHandle. Remote PIDs are never sampled by head's ProcessRegistry. The same installed intentd binary has a node composition root; phase 1 installs matching versions manually.
The local node is a service composed in head's process over an in-memory link, without another daemon, listener or token. It implements the same admission, scope, journal, checkpoint and merge semantics. Default local/shared/worktree execution remains available; explicit isolated placement always creates its own checkout. clonefile/FICLONE accelerates that creation, with a standalone repo-cache Git clone fallback on unsupported filesystems. It never inherits the legacy sandbox's shared-checkout fallback. An isolated path on a multi-agent static host does not imply a security boundary; exclusive placement reserves a whole static node when requested.
| Location | Future responsibility and boundary |
|---|---|
| intent-core | Transport-independent AgentRuntime/NodeLink interfaces, lease/placement/checkpoint DTOs and scoped caller envelope; no dependency on services or transport |
| intent-services | Orchestration, placement, hub transactions, interruption/resume; consumes interfaces injected by the binary; never imports transport |
| intent-acp + intent-js | Existing ACP/fs/terminal and QuickJS implementation runs on node; MCP bindings in intent-acp/src/mcp_server/bindings split operation routing through WorkspaceApi implementations, not a services-only proxy |
| intent-git | Non-mutating checkpoint codec extracted from transfer WIP/index representation, local checkout creation, scoped hub refs and Git helper; no orchestration or socket ownership |
| intent-store | Node/lease identities, journal ingestion identity/watermark, checkpoint pointer, stop/resume/publication operation records and idempotency |
| intent-nodes (new) | Static/local provider adapters and node runtime composition helpers using core interfaces and lower-level acp/git/pty/providers; no services or transport import |
| intent-transport | Concrete authenticated WSS multiplexing endpoints implementing core interfaces; persistence occurs through service interfaces, not direct store access |
| intentd binary | Wires head and node composition roots, in-memory or TLS endpoints, local runtime implementation and CLI/helper entry points |
The first extraction wraps today's agent_manager spawn/prompt/cancel/stop/reap
and memory operations behind AgentRuntime without changing local semantics.
Remote implementation uses the injected NodeLink, not transport types. Scope
travels with each operation: a node's agent cannot acquire administrator/daemon
authority by forwarding a call, including a hook. Preserve intent-core::Caller
and shared-host membership checks rather than treating a lease token as a user.
Head's bare hub is keyed by forge host/provider/repo identity and borrows only
head-local cache objects. Node has a separate cache and checkout; no head/node
shared filesystem or remote alternates path exists. Git packs and verified blobs
carry unpublished commits, dirty WIP, original index, submodule repositories and
portable provider session state. Transfer's existing snapshot_wip mutates the
live index/HEAD, so periodic capture must extract its format into a temporary-index
codec with a proven capture barrier. A failed capture retains the last successful
checkpoint and never reports new durability.
Node fsyncs journal records before forwarding; head transactionally commits the dedup identity, transcript/events and contiguous ack watermark. Checkpoint success is separate: immutable Git/blob anchors are durable before the SQLite checkpoint pointer advances. Reconnect fences old connections, replays records, applies stop tombstones and reconciles one resume attempt before delivering any new prompt. Checkpoint advancement also compares a durable assignment epoch/capture revision; late older uploads cannot replace newer recovery state, even at the same journal watermark. Isolated children hydrate the parent's captured dirty contents through an immutable inherited baseline without editing the parent. Merge/publication exclude that baseline from the child's attributable delta; private synthetic ancestry is normalized away before a forge push, or publication is blocked. Loss notices state the successful checkpoint's actual capture time; the periodic five-minute attempt is not a loss bound during an outage or failed capture.
Public hub.publish plus a bound node CLI command provides the explicit head-owned
forge push. Agent state never creates forge branches implicitly. Existing MCP
git helpers remain commit/root operations and PR helpers remain snapshot/monitor;
PR creation uses gh, with a bounded argv/body bridge for node callers. No removed
Git push or PR-create MCP binding is resurrected. Hub merge runs on the target
node, protecting its actual dirty/index state and using the same completion
semantics for local and remote parents.
The closed microVM backend PR #873
and docs PR #5918 used host-driven
guest exec, execution-environment profiles and host/guest filesystem access.
Those runtime/profile assumptions are not the phase 1 foundation. Useful VM
lifecycle/image work may later implement NodeProvider with intentd node in the
guest; head must not launch provider CLIs remotely or mount a guest checkout.
The source proposal's read-only virtio-fs cache exception is also superseded:
base objects come from each node's own cache/forge or hub transport, never shared
head filesystem paths. Cloud adapters, images, Windows qualification, local Mac
microVMs, freeze/fork, automatic sitter upgrades and credential administration
are outside phase 1.
Retirement order is additive docs → backend per-agent CoW deletion and frontend
cleanup → canonical catalog cleanup after automatic pins. Backend node/hub support,
local parity and the replacement frontend follow independently; until the local
node ships, agents that are not placed remotely share the workspace checkout.
Each merge requires human authorization. Keep workspace
checkoutMode: cow, reflink primitives and repo-cache coverage throughout. Remove
per-agent isolation selection and merge/discard routes without aliases. No live
sandboxes exist, so the removal drops the sandbox store rows and session sandbox
fields without a recovery path and never touches files on disk.
This section describes current pinned behavior. Per-agent sandboxes were
removed in protocol 16. Protocol 17 retired the workspace.cowIsolation setting,
workspace.duplicate and the cowSupported capability, so copy-on-write is used only
to hydrate checkouts from the repo cache.
Wire contract: PROTOCOL.md §5.1 (checkoutMode). Architectural split of responsibilities:
- Provisioning (
workspace.create).intent-servicesprovisions a create from a local repository as a linked worktree (intent_git::worktree::provision_worktree) under the per-repository worktree lock. A create that arrives with agithubUrland noclonePathhydrates a standalone checkout from the repo cache instead (below): a CoW reflink probe from the cache into the workspace dir (intent_git::cow_probe) picks a CoW clone (cow) or a plain local clone (direct). The persistedcheckoutModeis immutable per workspace; rows created ascowcopies of a local repository before protocol 17 keep working. - Unified provisioning progress.
intent-services::create_progressowns the per-create progress reporter armed by aworkspace.create { progressId }(PROTOCOL §5.1/§6.5): it echoes the client-minted id on everygit:clone:progress/git:clone:doneframe, normalizes percent across the whole pipeline (network clone, cache ensure/refresh, submodule population, CoW copy / worktree add / branch checkout, finalizing) onto one monotonically non-decreasing 0–100 scale, and dedupes identical consecutive frames. Theworkspace.createwrapper owns the exactly-one terminalgit:clone:doneper create (success and every error path; idempotent replays emit nothing).clone_ops::SubmoduleAwareParserfolds a--recurse-submodulesstderr stream into one aggregatedsubmodulesphase — the create-orchestrated clone recurses submodules (intent-hq/intentd#1069); the standalonegit.cloneRPC does not. Without aprogressIdevery path keeps its legacy framing (the field is additive). - Repo cache & cache-hydrated creation.
intent-git::repo_cacheowns a hidden, daemon-managed cache of read-only GitHub clones at<workspaces_root>/.repo-cache/<owner>/<repo>(dot-prefixed so it stays invisible to users and to recent-repo derivation; the module never reads config — the caller passes the cache root).ensure_cached_repois the single entry point: it serializes callers on a per-repo lock, then clones fresh (miss;--recurse-submodules, so the cache carries populated submodule work trees and their module git dirs) or refreshes (git fetch --prune,remote set-head origin --autoso an upstream default-branch change is re-resolved, hard reset to that branch,submodule sync+submodule update --init --recursive --forceso gitlink bumps, URL changes, and newly added submodules are followed, thengit clean -ffdxplus a per-submodule recursive clean so untracked pollution — including orphaned submodule checkouts — is never byte-copied into hydrated checkouts). Refresh never fails the flow — any anomaly (diverged history, corrupt object store, an interrupted prior clone, a vanishedorigin/HEAD, a mismatchedorigin) deletes the cache dir and re-clones; only a failed clone surfaces as an error.intent-servicesuses the cache to hydrateworkspace.createwhen agithubUrlarrives without aclonePath(PROTOCOL §5.1): the checkout is always standalone — a CoW clone of the cache (cow) or a plain localgit cloneof it (direct) — never a linked worktree against the cache, whose hard-reset/re-clone refresh would corrupt linked worktrees. Both paths populate submodule work trees from the cache's local module git dirs alone (the CoW byte copy carries them;directcopies.git/modulesbefore the update), and the populatingsubmodule updateruns strictly offline (--no-fetch, every clone transport refused): hydration never touches the network — a gitlink the cache does not hold degrades to an unpopulated submodule with a warning, and no submodule anomaly ever failsworkspace.create. Provisioning holds the per-repo cache lock, and afterwardsoriginis retargeted at the real URL (submodule URLs re-synced to their.gitmodulesresolution) so the checkout is fully self-contained and the cache is always safe to delete. Network git here shells out to systemgit(fail-fastGIT_TERMINAL_PROMPT=0, wall-clock deadline kill) with any token offered through the env-backed credential helper, never argv; the helper config propagates to submodule child fetches during cache clone/refresh viaGIT_CONFIG_PARAMETERS, the token only via the inherited env var. - Deletion.
workspace.deletefirst closes data-producer admission for the target workspace, waits for already admitted operations, and stops its runtime writers. Store cleanup removes one session at a time and sweeps histories and other growing dependent data in bounded batches, releasing the SQLite writer between steps. Each batch commits independently: failure or interruption can leave a live workspace row with partially removed data, and a retry finishes the remaining cleanup. Cancellation does not roll back committed batches or guarantee that already-started database work stops. Only the final workspace-row deletion and deleted-ID tombstone share the terminal transaction. Normal immediate-delete success andworkspace:deletedfollow that commit; filesystem cleanup stays asynchronous. See the deletion contract for retry, grace-window and event semantics. The git-metadata phase is checkout-mode aware: a worktree checkout gets registration prune + guarded branch delete + rename to a trash path, while acowordirectcheckout — a standalone clone with no registration in the source repo — goes throughintent_git::worktree::detach_checkout_dir, which only renames the directory to a trash path (filesystem work, never opens a repository). The standalone rename is gated on the daemon-owned<root>/<workspaceId>/<repo-slug>layout: anisNewRepodirect checkout — where the checkout IS the user's chosen repository folder, outside that layout — is never renamed or removed; deletion removes only the workspace row. The recursive removal of the trash directory runs in the background outside the lock in both modes. - Agent sandboxes (removed in protocol 16). Per-agent CoW sandboxes,
their merge-back and the
sandbox.cow.*routes were removed; every agent that is not placed on a remote machine works in the workspace checkout. Store migration0187dropped thesandboxtable and the session sandbox columns.
Wire contract: PROTOCOL.md §5.5 ("Creation-time default-model resolution") and
§5.11 (resolvedModel/resolvedProvider previews). Architecturally:
- One resolver, daemon-side.
agent_ops::resolve_agent_default_modelinintent-servicesis the single resolver behind every agent-creation path (agent.create,agent.delegate,agent.wakeOrCreate,workspace.createinitialAgent) and behind thespecialist.get/specialist.listpreview decoration — so previews match what a no-model create actually pins. Clients are pass-through: they send a model only when the user explicitly picked one and never pre-resolve defaults. - Provider boundaries. The model-tier concept (
fast/balanced/smart) and the static per-provider tier tables are removed (intentd#922): all model discovery is dynamic (models.listprobes, cached per provider), and every resolved candidate — specialist frontmattermodelor a settings default — is provider-guarded against the cached dynamic catalogs, so a model owned by another provider falls through to the next step instead of leaking across providers. The default provider is settings-derived (the provider prefix ofmodel.defaultwhen compound and registry-valid, elseproviders.active), bottoming out at the first registered provider as a neutral positional last resort — no provider carries a hardcoded default designation. - Pinning. The resolved model is persisted to
session.modelat creation time and fixed for the session's lifetime; later settings/specialist changes only affect subsequently created agents (agent.setModelis the explicit mutation path). Bundled specialists carry no frontmattermodeland inherit the user's configured default (or the provider CLI default).
The daemon is the authority for backend-owned settings. Each committed mutation is an
atomic state transition identified by the process-local revision described in protocol
§5.12. A provider/model default selection that crosses providers is therefore one batch:
providers.active and the complete model.providerDefaults map are written together.
Frontend code must not persist those paths independently or treat the map as a patch.
Each client connection maintains a highest-applied settings revision. A numbered
settings.list snapshot, mutation result, or settings:changed event is applied only when
its revision is at least that watermark; lower revisions are stale. Equal revisions are
the response/event views of one commit and must be harmless to apply more than once. This
ordering rule lets optimistic UI survive delayed snapshots while still converging on the
daemon's committed state. A rejected batch leaves both authoritative state and the
watermark unchanged; the client rolls back or rehydrates instead of synthesizing a partial
success.
The watermark belongs to a backend connection generation, not to durable frontend state.
On disconnect, reconnect, or backend/daemon switch, invalidate in-flight work from the old
generation, clear the watermark, and hydrate from a fresh settings.list before accepting
that generation's events. This is required because a restarted daemon begins again at
revision 0. For compatibility with older daemons, an absent revision selects the legacy
arrival-order path; it is never coerced to 0 or compared with a numbered watermark.
The unsloth provider runs Unsloth GGUF models fully locally. It has no agent
CLI of its own — the registry entry rides the opencode binary (opencode acp) as its ACP runtime, pointing it at a daemon-managed local server. Three
pieces:
- Managed server (
services::unsloth_server::UnslothServerManager). The daemon owns a singleton Unsloth server (one loaded model at a time — a llama.cpp constraint): on the first spawn of an unsloth agent it runsunsloth run --model <repo>:<quant> --disable-tools -p <port>(quant auto-picked mirroring the CLI's--gguf-variantdefaults:UD-Q4_K_XLforunsloth/*repos, elseQ4_K_M), waits for the HTTP surface, then probes the authed/v1/modelsendpoint until the model is loaded (the server requires auth even on/v1/models, so a 401/403 during probing is expected warmup — up-but-not-ready — not a credential failure; the model-ready window is generous because first use can mean a multi-GB download, with progress surfaced asagent:stream:statuslaunch-phase events — PROTOCOL §6.5). The server is reused while it serves the requested repo, killed + respawned on model switch or a dead child, and killed on daemon shutdown — a shutdown latch aborts an in-flight startup at its next probe tick, so shutdown never waits out a download. A missingunslothbinary degrades gracefully: the spawn fails with an install hint (InvalidInput, so the message survives the JSON-RPC envelope). - Endpoint injection. The daemon mints the opencode auth material via
unsloth start opencode --no-launch --model <repo>and reads the generatedopencode.json(baseURL, apiKey, per-model token limits);build_provider_env_with_unsloththen injects a custom OpenAI-compatibleprovider.unsloth-studioblock (the id Unsloth itself generates;npm: "@ai-sdk/openai-compatible") plusmodel/small_modeldefaults and an optionalcompactionblock intoOPENCODE_CONFIG_CONTENT— the same env mechanism opencode's MCP block already uses. - Catalog. The
unslothmodel-catalog source is an HTTP fetch of the Hugging Faceunslothorg's GGUF repos — one row per repo (never per quant), ranked by downloads, fit-filtered against ~70% of total system RAM via a parameter-count heuristic, with awarningreporting how many repos were hidden (wire contract: PROTOCOL §5.30).
Wire contract: PROTOCOL.md — system.gitCredential fast-path (§5, v2.5),
github.* auth model (§5.27), source-control settings keys (§5.12), clone
credential injection (§5.6). One token, three consumption paths, one trust
boundary:
- One stored token. The GitHub token lands in the file-backed secrets
store (
~/intent/.secrets.json,0600) under accountsourceControl.github.token, written by the daemon-owned OAuth device flow (github.connect) and deleted bygithub.revoke. Every consumer resolves it through one chain (intent_sourcecontrol::token::resolve, persourceControl.github.tokenSource):auto(the default) tries secrets store →GITHUB_TOKEN/GH_TOKENenv →gh auth token. - Daemon-internal git ops (clone/fetch/pull/push in
intent-git): the resolved token is offered to the spawnedgitas a github.com-scoped credential helper built in-process (intent_git::auth). The helper config entry contains no token bytes — the token travels only in theINTENT_GIT_GITHUB_TOKENenvironment variable of that one child, never on argv. The entry is appended (via-corGIT_CONFIG_PARAMETERS) after any configured helpers, so the user's own helpers still win, andGIT_TERMINAL_PROMPT=0turns a would-be credential prompt into a fast error instead of a hang. - Child spawns (PTY terminals via
services::terminal_ops, agent provider processes viaservices::agent_manager): daemon-backed helper mode — zero token bytes in the child environment. The spawn appends acredential.https://github.com.helper=!<intentd> git-credentialentry to the child'sGIT_CONFIG_PARAMETERS(inherited entries preserved, so ambient user helpers keep winning);<intentd>is the running daemon's own binary (current_exe, sh-quoted). An unresolvable binary path or the gate being off simply yields no injection — a spawn never fails or blocks on it. - The
intentd git-credentialhelper (hidden subcommand,crates/intentd/src/git_credential.rs): speaks the line-oriented git-credential protocol on stdin/stdout and answers onlygetforprotocol=https+host=github.com, fetching the credential from the running daemon over the UDSsystem.gitCredentialRPC on each invocation. The RPC is UDS-only — a remote (TCP/WSS) caller is rejected with-32001, so the credential never crosses the network. Every other case —store/erase, other hosts, daemon not running, gate off, no token — is a silent exit 0, letting git fall through to its remaining helpers/prompt rules. The daemon audit-logs each grant/denial with the helper's self-reported pid; the token value is never logged. - Gating & revocation.
sourceControl.github.exposeGitCredentialToChildren(boolean, defaulttrue) gates both the child-env injection and thesystem.gitCredentialgrant. Children resolve on everygetrather than holding a token snapshot, so toggling the setting off or callinggithub.revoketakes effect immediately — including in already-open terminals. - Security invariants. The token never appears on argv or in logs; the
only environment carrying it is that of the daemon's own short-lived git
subprocesses (
INTENT_GIT_GITHUB_TOKEN) — never a terminal or agent process. It is never exported asGITHUB_TOKEN/GH_TOKEN(those keys stay on the MCP child-env secret denylist,intent_acp::mcp_env, which is unaffected by helper injection). The trust boundary is the Unix-domain socket — same host, same user, filesystem permissions — which is why the credential surface is deliberately absent from WSS: remote clients drive git through thegit.*RPCs instead.
Wire contract: PROTOCOL.md §5.40 (hook.* methods), §6.5 (hook:* events).
A background hook is a small agent-authored JS script the daemon runs on a
fixed interval until it dispatches (wakes its owner), fails (evicted), or is
cancelled — letting an agent watch for a condition without burning turns
polling. The subsystem lives in intent-services
(services::hook_manager):
- Scheduler. Each active hook owns one tokio task that sleeps
delayMsbetween runs; arunNowcontrol frame triggers an immediate run and resets the inter-run timer. Scheduling is MCP-only (ws.hook.schedule— hooks are agent-authored per the PROTOCOL §6.8 principle); the FE wire surface is read/trigger/cancel only (hook.list/hook.runNow/hook.cancel). The first run happens immediately at schedule time as validation: a failing script rejects the call, a dispatching one wakes the owner without persisting a schedule — except for a perpetual hook, which persists and schedules anyway (see below). - Execution. Scripts evaluate in QuickJS (
intent_js::eval) with the exact samews.*prelude + host dispatch theworkspace_apiMCP tool installs — includingws.host.exec— with the hook's workspace/agent pinned as the caller and a 60 s wall-clock budget. The return value is the contract:{ dispatch: true, message }wakes the owning agent and terminates the hook — unless the hook is perpetual, which counts the fire and returns toscheduled;{ dispatch: false }/undefinedsleeps and re-runs; a throw or the 60 s timeout evicts the hook, persistslast_error, and wakes the owner with the reason. - Perpetual hooks (intent-hq/intentd#979).
The optional
perpetualschedule param (defaultfalse— one-shot behavior is unchanged) makes dispatch non-terminal: the run wakes the owner as usual, bumpsdispatch_count, and re-arms the hook toscheduledwith a freshnext_run_at, so it keeps running on its cadence until TTL expiry, cancel, or eviction. The re-armed wake's state note says the hook remains active until itsexpiresAtwith aws.hook.cancelpointer — replacing the one-shot retired-with-reschedule-pointer note — and dispatch wakes carry thehookStillActiveboolean in thehook_wakemessageMetadata (trueonly for the re-armed perpetual branch; absent on non-dispatch wakes) so consumers need not parse the note text (intent-hq/intentd#1027); a dispatch landing at/afterexpiresAtstill wins but terminalizes the hook (dispatch wake, then the expiry notice), and keeps the one-shot phrasing so the two notices cannot contradict each other. Both paths resolve and persist the post-dispatch state before emittinghook:run-completed/hook:dispatched, so those payloads carry the real outcome.perpetualanddispatch_countpersist as defaulted columns (0084_hook_perpetual.sql) and surface onhook.listplus everyhook:*payload asperpetual/dispatchCount; the TTL-expiry notice reports "N runs, M dispatches" for a perpetual hook. - Ownership scoping. Hooks are agent-owned, and
hook_canceltakes the cancelling agent ascaller: Option<AgentId>. The MCP binding passes the calling agent's id (Some) — and, likews.hook.schedule, rejects a call with no agent caller context outright — so an agent can only cancel its own hooks; a non-owner cancel is rejected with an error naming the owning agent, before any state change. The FE wire path (hook.cancel) passesNone: it may cancel any hook in the workspace. Cancels are visible in exactly one direction: an owner's own cancel delivers no self-wake, while aNone-caller cancel wakes the owner with a notice (intent-hq/intentd#953). - Owner wakes go through the automatic-delivery
agent.sendMessagepath — queued behind an in-flight turn, archived-workspace park respected — and are best-effort (a delivery failure is logged, never propagated). - Persistence & rehydration. Schedules persist in the SQLite
hooktable (migrations0075_hook.sql+0076_hook_last_logs.sql+0084_hook_perpetual.sql, rows cascade with their agent session) and rehydrate at boot (Services::rehydrate_hooks):scheduled/runningrows respawn their tasks (running— daemon died mid-run — is healed back toscheduledwith a fresh countdown), rows whose owning agent is gone are cancelled, and terminal rows (dispatched/evicted/cancelled) are kept for inspection. - Limits.
[hooks] maxPerAgent(config.toml, default 5) caps concurrently active (scheduled/running) hooks per agent;delayMshas a 10 s floor and hook names — user-facing, human-readable descriptions of what the hook is waiting for — are capped at 50 characters — all enforced at schedule time.
Wire contract: PROTOCOL.md §5.42 (prMonitor.* methods, the
merge-requirements checklist) and §6.5 (prMonitor:* events). The subsystem
lives in intent-services (services::pr_monitor): agents register monitors
via the MCP ws.pr.monitor binding (registration is MCP-only, like
ws.hook.schedule; the FE wire surface is prMonitor.list / cancel /
flush), and one shared daemon loop (spawn_pr_monitor_loop, wired in
main.rs beside the PR-refresh sweep) ticks on the live
prMonitor.pollSeconds cadence (default 60 seconds) and polls the due monitors —
each distinct PR
becomes due after an effective interval (the minimum time between two polls of
one PR; the actual revisit lands on the first tick at or after it, i.e. rounds
up to the next pollSeconds tick). The workspace idle policy is a floor on
the global interval planned as the larger of two cadences
(effective_pr_monitor_interval_secs / plan_quota_cadence): the
hourly-budget cadence, stretched so the loop is modelled to spend at most the
live prMonitor.hourlyRequestBudget forge calls per hour (default 1500,
minimum 60, maximum 5000; each PR poll costed at PR_MONITOR_REQUESTS_PER_POLL
= 3 calls — a cadence cost model, not a hard ceiling: no request is counted
or blocked against it, and actual spend can differ — the 3-call unit is a
single-page planning constant, so the folded observation spends less and
paginated review lists / degraded-path REST fallbacks more), and the quota
cadence (intentd#1948): due-sweep ticks consult the shared authoritative
quota probe (at most once per 60 seconds, including failed probes) and stretch
the interval so the projected spend to the
window's reset (capped at 2h) stays within the live
prMonitor.quotaSharePercent (default 50, minimum 1, maximum 100) of the
forge's REMAINING quota — allowed = floor(remaining × share / 100) in
integer arithmetic, interval ceil(distinctPRs × 3 × secondsToReset / allowed), rounded up to whole ticks — and defers polling entirely, however
stale or catch-up-marked the monitors, once allowed < 3 (a failed probe or
a host without the signal falls back to the hourly budget alone). Each tick
fetches a capped oldest-first subset of the due PRs
(pr_monitor_fetches_per_tick) so a large monitor set is spread across ticks
instead of burst-fetched; while a stretched interval spaces fetches further
apart than one tick, the cap is zero until that spacing has elapsed since the
newest lastPolledAt, so a stale backlog (restart, outage, quota stretch)
drains within the planned budget — a hold measured from the persisted stamps,
needing no spend counter, and keyed on the final interval alone, so a
budget-derived stretch holds even with unknown or plentiful quota.
workspace_check_cadence adds a workspace floor of 120/300/600/900 seconds
from 15 minutes/1 hour/6 hours/24 hours without meaningful content work.
The default active interval is 60 seconds; explicit pollSeconds remains the
active interval and floor. A bounded store projection reads last_content_activity
(or creation time without content history), while live agent work restores active
cadence. Note/conversation activity counts; polling, metadata and merely opening
views do not. Missing, malformed or future clocks use active cadence. For a shared
PR the fastest interested workspace wins, and the existing shared fetch updates
all siblings. Idle delay never shortens global budget/quota limits or bypasses a
pause. Registration, restart catch-up, explicit checks, debounce and terminal
notification behavior remain unchanged.
The same policy gates automatic pr.refresh calls and background linkage/root
forge checks. automatic_pr_refresh reserves a workspace/root attempt before I/O,
retaining failed and in-flight attempts across repeated callers and connections;
deferred commands return persisted linkage. Provider-scoped discovery caches reuse
results for the admitted interval, including suitable monitor observations.
Explicit refreshes bypass idle admission but retain quota protection. Local git
maintenance retains its independent 180-second active / 1800-second idle cadence.
On GitHub one poll is a single GraphQL pr_observation (PR record,
merge-requirement signals, reviews and review
threads within bounded windows, conversation-comment count; rateLimit.cost
- plus a REST
branch_rulesread — 2 reads where the per-signal sequence cost 6 (intentd#1949); an outgrown window takes the paged per-signal read for that piece only, a failed folded read (other than quota exhaustion) falls back to the per-signal reads, and a fingerprint-unchanged cheap poll reuses the previous full fetch for up to 5 polls / 15 minutes. The loop honours the global forge rate-limit gate (services::rate_limit, monorepo#2961) shared with the PR-refresh and git-root sweeps: a quota-exhausted forge read — the observation or PR read itself or any secondary checklist / branch-rules / comment read, except the branch-rules read nested inside GitHub's per-signalmerge_requirementsprobe, which degrades every failure torulesKnown: falsewithout pausing (monorepo#5281) — pauses all forge-touching sweep work until the forge-reported reset plus a 30s margin (clamped into [60s, 2h]; a fixed 5min without a reported reset), stamping the pause deadline aslastErroron every active monitor across workspaces (Store::annotate_active_pr_monitors_pause), and the gate is re-consulted before every fetch within a sweep so a pause opened by a sibling sweep stops the in-flight sweep too. While paused, each PR-monitor and PR-refresh tick re-probesrate_limitfor free and lifts the pause early onceremaining ≥ max(500, 10% of limit)(maybe_lift_rate_limit_pause, intentd#1945), clearing the annotations (Store::clear_active_pr_monitors_pause) at once —pausedUntilis derived from the in-memory gate and vanishes as soon as it opens, by lift or expiry, while an expired annotation waits for the row's next write-back andlastSnapshotfor the next successful poll; a fetch that hits quota exhaustion after a lift spends its own free reset probe when re-pausing (pause_sweeps_for_rate_limit); the gate transition and its bulk stamp / clear run under the gate's reconcile lock, and thepr_monitorrow is authoritative for the pause — a poll's guarded write-back lands only its genuine error part, composed in SQL with the row's current unexpired annotation (PrMonitorPollUpdate::last_error), never introducing, moving, or resurrecting one; boot rehydration strips annotations left by the previous process. EveryPrMonitorwire projection carries the deadline aspausedUntilon ACTIVE rows while the gate is closed, monitor wakes carry it in their metadata, andws.pr.snapshotsamples it after its awaited forge reads (intentd#1954). Each poll diffs the merge-requirements checklist (checks, reviews, threads, mergeability, branch rules — composed inpr_ops::merge_requirements/merge_requirements_from_observationwith per-signal, never-fatal degradation) against the monitor's persisted emit baseline (the PR state as of the last delivered wake, or registration), and wakes the owning agent with a single consolidated notification once the PR has been quiet forprMonitor.debounceSeconds(with a max-latency bound so a never-quiet PR whose pending set stays continuously non-empty is late, never starved — a full revert empties the set and re-arms the clock, by design). The pending set is a coalesced net diff, recomputed against the emit baseline on every poll rather than accumulated as a log: a field that moved A→B→C reports one initial→final line, a reverted field drops out, and a PR that fully reverts within the debounce window empties the set — anchors reset, no wake sent. Each delivered wake advances the baseline to the delivered snapshot. Monitors persist in the SQLitepr_monitortable (migration0085_pr_monitor.sql, rows cascade with their agent session; the emit baseline column arrived in0089_pr_monitor_baseline.sql, whose backfill pairs with a rehydration path that delivers any pre-coalescing pending log as-is rather than letting the first recomputing poll drop it), survive daemon restarts via boot rehydration with catch-up delivery, and terminalize on merge/close with an immediate final wake (completedrows are retained so merged PRs stay visible). Store writes are guarded compare-and-swap so concurrent flush / cancel / re-register / poll never clobber each other; owner wakes go through the same automatic-delivery path as hook wakes. The agent surface (ws.pr.monitor/ws.pr.unmonitor/ws.pr.monitors) is gated byagentFeatures.prMonitor;ws.pr.snapshotstays un-gated and always carries itsrequirementsblock — the toggle only scrubs the "preferws.pr.monitor" cross-references from the surviving doc entries.
Wire contract: PROTOCOL.md §5.6 ("Multi git root tracking" — the
gitRoot.list method, the gitRootId? param on the git reads, the
WorkspaceGitRoot wire shape) and §6.5 (gitRoot:* events). A workspace can
track secondary git roots — agent-created subtree checkouts, initialized
submodules, or sibling clones anywhere on the host — alongside its implicit
primary worktree. Rows persist in the SQLite workspace_git_root table
(migration 0093_workspace_git_root.sql, intent-store's
workspace_git_root_repo; rows cascade with their workspace), keyed by
canonicalized absolute path and idempotent per (workspaceId, path).
Registration is MCP-only (ws.git.registerRoot / ws.git.unregisterRoot /
ws.git.listRoots in intent-acp's git bindings, per the §6.8 principle) —
the FE reads via gitRoot.list and subscribes to gitRoot:registered /
gitRoot:updated / gitRoot:unregistered. The background PR-refresh loop
additionally sweeps each workspace's roots: it auto-detects the worktree's
initialized submodules as source: "auto" rows, auto-prunes rows whose path
vanished from disk, and runs the same per-branch PR discovery on each root as
on the primary workspace root (the row's PR fields mirror the Workspace PR
fields), fail-soft per root. Six git reads (git.status, git.changes,
git.diffs, git.commits, git.showFile, git.branchStatus) accept an
optional gitRootId that re-points the read at the registered root's path;
an unknown or foreign-workspace id is -32602 with an identical message, so
roots are not probeable across workspaces.
Wire contract: PROTOCOL.md §Completion-watch persistence and the §6.5
agent:idle notes. The settlement machinery lives in intent-services
(deliver_completion_to_watches in lib.rs, the completion-watch registry in
agent_subscriptions.rs): an agent:idle only counts as the agent's
completion — firing its watchers' deliver-once wakes and recording after_all
group settlement — when the agent has genuinely settled. Four deferral
classes gate this, all probed live at delivery time (never from emit-time
event stamps):
- Queue/busy interim — ready-to-send queued messages, or a worker already busy in a new turn. Defers ungrouped watch delivery only; grouped watches are exempt (group accounting must see every completion).
- Hook-waiting — the agent owns active background hooks. Defers both watch delivery and grouped settlement records; TTL-bounded by hook expiry.
- PR-monitor-waiting (unified external-wait; intentd#1002) — the agent
owns active PR monitors (§Centralized PR monitoring). Defers watch delivery
and grouped settlement records exactly like hook-waiting, but has no
TTL of its own (PR monitors don't expire) — it resolves only via the
monitor's own terminal transitions (completion, owner
ws.pr.unmonitor, externalprMonitor.cancel, theworkspace.archivesweep cancel (intentd#1067), or restart rehydration), each of which re-runs the redelivery backstop. - Agent-waiting (monorepo#1468) — the agent itself holds live outgoing completion watches on other, unsettled agents (ungrouped or grouped; a coordinator with an open delegation group is waiting on its children). Defers watch delivery and grouped settlement records, like hook-waiting.
Two interim notions are deliberately split: seal_interim
(queue/busy/hook/PR-monitor) also blocks sealing the agent's own open
after_all group, while agent-waiting does not — an after_all
coordinator always holds grouped outgoing watches on its own children, so
gating the seal on agent-waiting would deadlock every group. The waiting
classification (Services::agent_is_waiting_on_agents /
classify_agent_waiting) bakes in a 2-cycle deadlock guard: a mutual
watch pair whose both sides are idle is not a waiting reason (the pair
delivers as before); deeper cycles (A→B→C→A) are an accepted limitation,
deferring until an external event breaks the cycle. Never deferred by any
class: agent:failed / agent:deleted, the immediate reportToParent
wake, and the attention (blocker/discussion) fan-out.
Deferred idles record an interim-skip marker, and redelivery backstops
re-run the deferred completion when the deferral reason disappears without a
fresh idle: queue retraction/edit (queue interim), terminal hook transitions
(hook-waiting), terminal PR-monitor transitions (PR-monitor-waiting), and —
for agent-waiting — agent.unwatch, agent.cancelSubscriptions, and
after_all group settlement, each of which may remove the agent's last
outgoing watch. Restart paths share the same predicates: the startup watch
reconcile, registration-time reconciliation (re-arming a watch on an
already-idle target), and group rehydration all skip the synthetic
completion for a deferred child — group rehydration via a durable variant
that reads persisted completion_watch rows, since groups rehydrate before
the in-memory watch registry loads.
Wire contract: PROTOCOL.md §5.12 (settings catalog). Booleans under the
[agentFeatures] config.toml table — backgroundHooks, hostExec, scripts,
terminalAccess, browserAutomation, richChatBlocks, structuredQuestions,
attentionRequests, stateSnapshot, prMonitor, taskGraph, peerAgents,
mcpTools. All default true except the opt-in peerAgents (default
false). Each toggle removes
an agent-exposed feature from the agent's system prompt, its MCP tool surface,
or (for stateSnapshot) its per-turn prompt decoration. taskGraph is a
docs/prompt-only gate: it never dispatch-denies tasks or greedy, and its
unblocked-wake teaching uses the value captured when the parent session is
created rather than the live setting at wake delivery. mcpTools gates the
ws.mcp.* namespace (external MCP server tool forwarding,
intentd#1483) and is both
captured at bridge creation like the other toggles AND enforced live
server-side on every forwarded call in the services layer — which also honors
the mcp.enableUserServers master switch and the per-server disabled state
(enabled: false / mcp.disabledServers) — so the bridge-creation capture is
defense in depth for that toggle.
- Three MCP gating layers per feature (defense in depth): (a) the
workspace_apitool description is assembled from per-namespace segments at bridge creation (tools::workspace_api_description), so a disabled feature's docs never reach the agent; (b) the JS prelude omits the gated namespace installers (bindings::prelude_for), so a call fails with a clearTypeErrorinstead of silently dispatching; (c) the dispatch layer denies the method outright (tools::denied_feature) with an explicitdisabled in settings (agentFeatures.<key> = false)error. Parity tests intools.rskeep description ↔ bindings segment-aware. Gating is namespace-level exceptattentionRequestsandprMonitor, which are method-level (ws.agent.reportBlocker/ws.agent.requestDiscussiononly —ws.agent.reportToParentand the rest ofws.agent.*stay un-gated; andws.pr.monitor/ws.pr.unmonitor/ws.pr.monitorsonly —ws.pr.snapshotstays un-gated). - Sub-agent question gate — top-level-only
ws.app.question.ask(intentd#1063). The same three layers also enforce a caller-identity gate (not a settings toggle):WorkspaceMcpServercarries anis_sub_agentflag (with_sub_agent), threaded into the workspace-host dispatch viamake_workspace_host_for_bridge, derived once at bridge creation inagent_managerfrom the persisted session (parent_agent_id.is_some() || is_background; same spawn-time snapshot semantics as the toggle capture —is_backgroundcan flip viaagent.update, but the bridge keeps its surface until the next respawn). For layers (a) and (b) the flag reuses the toggle machinery: a sub-agent bridge's effective features forcestructuredQuestionsoff (effective_agent_features), pruning thews.app.question.*docs from the description and omitting the prelude installer (ws.app.questionisundefined). Layer (c) checksis_sub_agentFIRST and deniesapp.question.*frames with the redirect error namingws.agent.requestDiscussion/ws.agent.reportToParent(dispatch::SUB_AGENT_QUESTION_DENIED), so a sub-agent never sees the misleading "disabled in settings" denial;ws.help("app.question")takes the same branch and returns the honest top-level-only reason. Hook runs re-derive the owner's sub-agent status per run (hook_manager::hook_owner_is_sub_agent) and thread it through theprelude_for_bridge/make_workspace_host_for_bridgeentry points, so a sub-agent-owned hook gets the same pruning and denial as its owner's bridge. A genuinely disabledstructuredQuestionstoggle keeps the settings error for every top-level caller, and a top-level bridge with the toggle on is byte-identical to the pre-gate assembly. - Dynamic delegate-docs segment (specialist
modelOptions). The same per-bridge description assembly carries one dynamic segment: each visible specialist'smodelOptions(PROTOCOL §5.11) is resolved through the 3-tier fold at bridge creation (Services::specialist_model_options_for_workspace→specialist_model_options, project tier derived from the stored workspace record — worktree path, else repository path) and injected as continuation-indented lines of thews.agent.delegatedoc entry (tools::workspace_api_description_with_model_options), composing with the feature pruning above. Snapshot semantics match the[agentFeatures]toggles — captured once at bridge creation, never live-read — and when no specialist carries options (the default) the assembled description is byte-identical to the plain assembly by construction. - Prompt-section gating.
rules::assemble_system_promptthreads the captured flags into instruction assembly (intent-services/instructions.rs): disabled features drop their bundled-instruction sections (e.g. common.md's "Waiting on External Conditions", "Rich Chat Rendering", and "Raising Attention" sections, workspace-agent.md's dev-server script guidance) and the rules.rs-assembled "Asking the User Questions" section (structuredQuestions). With all defaults the assembled prompt and tool description are byte-identical to the pre-toggle output. - Hook runtime.
hook.scheduleis additionally rejected in the services layer whenbackgroundHooksis off, and that check reads the effective settings live. For sessions created after the flip, the MCP dispatch deny (captured flags) blocks the call first and the services check is redundant defense in depth; for pre-flip sessions — whose captured surface still advertisesws.hook.*and whose dispatch layer lets the frame through — the live services check is what denies it. Net effect: flippingbackgroundHooksoff denies new schedules immediately from all sessions. Already-active hooks are unaffected by the toggle and run to their terminal state/TTL. Hook script runs build theirws.*prelude from the effective flags read fresh per run — a hook outlives sessions and daemon restarts, so a hook run honors the same gates (e.g.hostExec) a newly created session would. - Per-turn state-snapshot injection (
stateSnapshot). The one toggle that gates neither a prompt section nor a tool: it governs only thecurrent ws.agent.snapshot() => {…}line thatAgentManager::build_turn_promptprefixes to outbound turn prompts (PROTOCOL §5.5 "Per-turn agent state snapshot").stateSnapshotis resolved inServices::agent_state_snapshot_linefrom the session's captured harness feature snapshot (Services::session_agent_features) like every other toggle (intentd#1273), so a flip applies to new sessions only; a legacy NULL-snapshot row falls back to the live settings until its first-activation freeze. Thews.agent.snapshot()MCP binding is deliberately never gated (no description/prelude/dispatch pruning), so the tool stays callable either way. The line is rebuilt per turn from live sources (hook store, watch registry, queue registry, event subscriptions, unsettled-children aggregate, pending questions, the session's attention request), skipped when the snapshot is trivial, and never persisted — the transcript row keeps the undecorated content, and all three skip paths (toggle off, trivial snapshot, build failure) leave the prompt byte-identical to pre-feature output. - New sessions only (except the live services-layer checks). Flags are captured once
at agent-session creation (the assembled system prompt is persisted
per-session) and at per-agent MCP bridge creation — never live-read per call
(deliberately unlike
workspaceApi.toonOutput) — so a settings change applies only to sessions created afterwards; existing sessions keep the surface they were created with. The two exceptions above (hook.schedule'sbackgroundHookscheck and the per-callmcpToolscheck on forwardedws.mcp.*calls) act on existing sessions immediately.
Wire contract: PROTOCOL.md §5 (system.status — child-process tree fields).
The daemon's cost to the machine is its descendant process tree, not its
own heap: a 183 MB intentd binary was measured owning a 21.5 GB / 95-process
tree (monorepo#2063). An operator diagnosing memory pressure reads
childProcesses / childMemoryBytes; memoryBytes covers only the daemon
binary and understates the real footprint by more than an order of magnitude.
Each claim below carries the issue holding the capture it came from
(monorepo#2062, #2063, #2107, #2109), so a reader can check the method without
re-deriving the numbers. The handful of figures that are arithmetic on
those captures rather than captures themselves — a 20-agent seat's ~12 GB,
three concurrent test runs at ~29 GB, the 256-adapter ~156 GB ceiling — are
marked as projections where they appear.
What an agent costs. Per-agent cost spans a 22× range, so agent count is
not a predictor of memory and agents.maxConcurrent is a concurrency cap,
not a resource cap (monorepo#2063):
| Subtree | RSS | Notes |
|---|---|---|
| Idle / conversing agent (median of 7) | ~660 MB | range 436–756 MB; npm exec → node ACP adapter → provider CLI → mcp-bridge |
| — provider CLI alone | 427–518 MB | |
Agent running vitest |
9,617 MB | 19 procs; 6 node workers at 0.8–2.3 GB each |
Agent running cargo check --workspace |
2,087 MB | 24 procs |
Agent running pnpm run test:unit |
1,154 MB | 10 procs |
| Ephemeral adapter chain (one-shot completion / model probe) | ~610 MB | monorepo#2062; holds no agent slot, bounded lifetime |
A single agent therefore spans 0.44 GB → 9.6 GB, and the top of that range is reached by an agent doing exactly what agents are for — three concurrent test runs projects to ~29 GB (3 × the measured 9.6 GB, not itself a capture), an ordinary coordinator fan-out.
The tree is retained, not leaked. Every agent touched inside the
agents.idleReapMinutes window stays resident (monorepo#2109, measured on
real claude-code chains, 10 agents driven to idle then left alone):
idleReapMinutes |
After idle | Result |
|---|---|---|
| 30 (default until monorepo#2109) | 10 minutes | 40 procs / 5.85 GB, flat — zero processes exited |
| 2 | 122 s after last turn | 0 procs / 0 GB — drained completely |
Retention claims in this section describe the idle-reap sweep in isolation.
The shipped default for memoryBudgetMb is auto (a RAM-derived budget), which
adds a second, independent eviction path: ProcessRegistry::evict_idle takes
no TTL and drops the LRU idle subtree to admit a spawn, so an idle tree can go
before its TTL and none of the retention figures below are guaranteed floors.
To observe the sweep-only behavior (no budget eviction), set
memoryBudgetMb = 0.
The reaper works; it was simply not asked to run for half an hour. That measurement is what moved the shipped default to 10 minutes: the same tree begins draining once the window passes rather than holding 5.85 GB for a further 20 minutes, and the 30-minute row above now describes the old default rather than the shipped one.
On upgrade, an existing seat keeps the value its
config.tomlalready carries — permanently. The 10-minute default applies to new installs: the config template is written only when the file is absent, and every install created before this change has an explicitidleReapMinutes = 30in it, which wins over the shipped default. There is no migration — that 30 stays until someone edits the file, by decision (monorepo#2109): a boot rewrite cannot tell a deliberate 30 from one the old template baked in, and silently overriding the former was judged worse than leaving the latter.So if your seat is accumulating memory right now, upgrading will not change that — open
config.tomland setidleReapMinutesyourself.
An agent
becomes a candidate at the TTL and is picked up by the next sweep (interval
ttl/4 clamped to [30s, 300s], reap_timings in the intentd binary
crate), so selection is bounded by TTL + one sweep — but release is not
the same instant: ProcessRegistry::evict_idle_older_than awaits each kill
serially and each carries a SIGTERM→SIGKILL grace plus a descendant sweep, so
a large idle set drains over a tail rather than all at once. Only processes
idle past the TTL are candidates, and the sweep skips any agent the manager
reports busy when it checks (AgentManager::reap_idle_older_than's
eligibility predicate).
Consequence for sizing: with the budget off, a seat that touches 20 agents
within the window holds all 20 subtrees at once even if only one is active —
projecting to ~12 GB at the measured ~0.6 GB idle median, more if any of them
ran a test suite.
The knobs, all under the [agents] table in config.toml (each is
self-described at the point of use in DEFAULT_CONFIG_TEMPLATE,
intent-core/src/settings_file.rs; all take effect on daemon restart):
| Knob | Default | Bounds |
|---|---|---|
idleReapMinutes |
10 (new installs; an existing config.toml keeps its own value — see above) |
How long an idle agent subtree is retained (0 disables the idle-reap sweep — it does not guarantee idle trees survive, since a non-zero memoryBudgetMb can still evict them at admission). The lever for a memory-constrained seat. |
memoryBudgetMb |
auto: (RAM − 8 GB) / 2, min 4 GB (absent key); small hosts lower it, see below |
Aggregate RSS of the whole child tree, as a soft admission gate on new spawns — binding only while the tree is over budget and host available memory is below the host reserve (8 GiB + one provisional agent; less on small hosts); see the headroom rule below. Absent key (the default) = auto (RAM-derived); explicit 0 = off (preserved for existing config files); positive value = budget in MB. Catalog max is the machine's own physical RAM, capped at 1,024,000 MB. |
maxConcurrentAdapters |
6 (on) |
Concurrently live ephemeral adapter chains (quick actions, model probes). |
maxConcurrent |
0 (auto from RAM) |
Agent slots. Not a memory bound — see the 22× range above. |
workloadMemoryMaxMb |
auto: RAM (or a lower parent cgroup limit) less a daemon reserve (15 % of it, the reserve clamped to 768 MiB–2 GiB; absent key) | Linux only: the hard memory.max of the shared cgroup box every workload runs in (below). 0 = no box; positive = MB. |
Small hosts (intent-hq/intent#9809).
Below 12 GiB of MemTotal (SMALL_HOST_BYTES), the auto values above are each
the lower of today's formula and a small-host one, so they can only drop:
with smallReserve = clamp(MemTotal / 2, 1 GiB, 8 GiB), the slot cap is
clamp((MemTotal − smallReserve) / 1 GiB, 2, 100), the budget
max((MemTotal − smallReserve) / 2, 512 MiB), and the host reserve
smallReserve + PROVISIONAL_AGENT_BYTES (host_memory_reserve_bytes). A
3.8 GiB host gets 2 slots, a ~0.95 GiB budget and a ~2.5 GiB reserve; at 12 GiB
and above (and when RAM is unknown) every value is unchanged.
Workload containment (intent-hq/intent#9809).
The knobs above gate new spawns; nothing in them bounds a process that is
already running. On a 4 GB host with no swap, one test run could thrash the VM
until the daemon, its SQLite pool and every client stalled. So on Linux the
daemon builds a cgroup v2 hierarchy at startup (intent_core::workload):
<domain>/{supervisor, daemon, workloads}, where domain is its own cgroup
(a systemd unit with Delegate=memory pids) or intentd-<hash> under the root
cgroup (root in a VM). The sitter moves to supervisor, the daemon to
daemon, and workloads gets memory.max = the ceiling and
memory.swap.max = 0, with memory.high left at max: without swap, a
memory.high throttle cannot reclaim a runaway's anonymous memory, so it
stalled the process just under the limit for minutes instead of letting the
kernel kill it (measured: ~105k high events, no kill), and swapping
workloads would stall the daemon as surely as running out of RAM. Every workload — agent CLIs, adapter chains, MCP and model servers,
scripts, setup and archive scripts, terminals, host.exec — runs in its own
leaf workloads/<kind>-<pid>-<seq>, joined before it runs any code: a
pre_exec hook for std/tokio commands (so a missing program still fails
the spawn) and the intentd cgroup-exec shim for PTY commands, which have no
pre_exec. When the box is full the kernel OOM-kills the largest process
inside it (memory.oom.group stays 0, so a test worker dies, not its agent);
a script, host.exec or terminal killed that way reports
exitReason: "memoryLimit", and an agent leaf's kill is logged with the
agent's id. Stopping a script or terminal kills its whole leaf, which also
catches setsid escapees. A sitter respawn starts in supervisor and
re-adopts the hierarchy; startup sweeps empty leaves.
Where the cgroup is not usable (not delegated, shared with other processes,
read-only) the daemon falls back to oom_score_adj (800 for scripts,
terminals and host.exec, 500 for agent-type roots) and reports why in
system.status.workloadContainment. workload_spawn_lint classifies every
spawn site as workload or internal. The daemon reserve's 768 MiB floor comes
from a measured 438 MB daemon RSS on a busy host plus OS and page-cache room.
- The budget binds only when the host is short — a two-condition rule
(intent-hq/intentd#1947).
budget_admitsinintent-services/src/agent_manager.rsrefuses a spawn (andevict_while_over_budgetdrains idle trees) only while both hold: the charged tree total is over budget and the host's available memory (sysinfoavailable memory, read in the same publishedsystem.statussweep as the tree) is belowHOST_MEMORY_RESERVE_BYTES= 8 GiB +PROVISIONAL_AGENT_BYTES. The tree total double-counts shared pages and includes every daemon descendant (dev servers, test runs, headless browsers started throughws.script/host.exec), so on a large host it crosses the budget — auto or an explicit small value alike — while tens of gigabytes are still free; an over-budget tree with that headroom is admitted without queueing or eviction. Strict fallback: when a published tree sample carries no headroom reading (available_memory: None— the host's available-memory sampling is unsupported or failed, sosysinforeported zero) the budget denies on the tree alone, exactly the pre-#1947 behaviour. This is distinct from having no tree sample yet: before the first published sweep lands,budget_deniesreturns no denial at all, so the gate stays inert rather than strict. OneTreeMemoryProbe::sample()returns bytes, sample id and headroom from the same sweep, so a decision never pairs one sweep's total with the next sweep's headroom. The idle-reap sweep (idleReapMinutes) is independent of this rule and still drains idle trees on its own TTL. - The idle-reap sweep keeps agents with running provider workers
(intent-hq/intentd#2573).
An idle agent whose current connection is continuous and has a §5.5b worker
row still
running(arun_in_backgrounddev server, say) is skipped by the TTL sweep, because killing its process would kill the worker with it. The keep-alive is bounded byWORKER_KEEPALIVE_CAP(24 h past the TTL, for a worker whose end report never arrives). Slot-cap admission and the memory-budget drain can still evict such an agent, but only after every idle agent without a running worker (KeepAliveFninintent-services/src/agent_manager.rs). memoryBudgetMbis a soft admission gate, not a ceiling (monorepo#2063, validated end-to-end against real agents under the strict policy — the tree-only criterion that is now the fallback above; on a host with headroom the gate does not engage, so these figures describe the host-short regime, not the common case on a large seat). Set to 1500 MB, a 20-agent simultaneous burst peaked at 3.06 GB against 12.37 GB unbounded, and settled at 1.73 GB against 11.56 GB; the same-budget 8-agent burst peaked at 2.47 GB and 3.09 GB across two runs — i.e. the bound does not scale with demand, a 4× larger request peaks the same (3.06 vs 3.09 GB). The costs: transient overshoot of 65–105% and steady state ~16% over. The overshoot is structural rather than accidental (live == 0always admits, the provisional charge is a fixedPROVISIONAL_AGENT_BYTES= 660 MB, andbudget_pending_bytesresets when a new sample seq lands while a just-spawned agent's RSS is still ramping —ProcessRegistryinintent-services/src/agent_manager.rs), so it is a fixed offset, not proportional to demand: when the gate is engaged, budget for roughly 2× the configured value as the transient. That sizing rule covers the admission transient the measurement exercised — a burst of comparable agents with the host short — and is not a runtime ceiling. The gate runs at spawn only: an already-admitted agent whose own workload grows (the 9.6 GBvitestcase above) is never re-checked and can carry the tree past the budget by itself, and the gate's only lever against that is refusing later spawns and evicting idle trees. Admission only — nothing running is ever killed, and all turns complete. The settings catalog advertises the bound asmin 0/max= detected physical RAM in MB, capped at 1,024,000 MB — which is also the value used where detection is unavailable (it is Linux/macOS only) and the static boundconfig.tomlparsing enforces. So a client renders a slider over the range the setting can meaningfully take, and on a seat with more than ~1 TB of RAM the cap binds instead of the RAM figure. The cap is not cosmetic: the catalog bound must never exceed the parse bound, orsettings.updatewould accept a value that the same schema then rejects on the way to disk. The parse bound itself stays static and machine-independent, so aconfig.tomlwritten on one seat still parses on another — meaning the divergence runs one way only, and a config carrying a budget above this machine's RAM still loads and is reported with avalueabove the advertisedmax.maxConcurrentAdapterscloses the quick-action burst path (monorepo#2062). One-shot completions and model probes never enterProcessRegistry, so they consume nomaxConcurrentslot and do not appear insystem.status.agents— before the bound the only ceiling wasserver.maxOutstandingRpcs(256), which projects to ~156 GB of adapter chains. Once a burst exceeds the cap, peak live chains equal the cap exactly and are invariant to how much bigger the burst is (a 16-call burst at cap 6 peaked at 3.57 GB); a burst smaller than the cap is unaffected and simply peaks at its own size. Over-limit callers queue FIFO on the semaphore inintent-services/src/acp_adapter.rsand, if their own timeout expires first, fail with-32603anderror.data.code = "adapter-busy"having spawned nothing — a retry is always safe.
Caveat: do not judge a burst from childMemoryPeakBytes until
monorepo#2107 is fixed. The high-water mark is a maximum over 5 s samples
(CHILD_TREE_SAMPLE_SECS), so a burst that peaks between ticks is never seen.
Measured against a 1 Hz ps descendant walk:
| Run | ps @ 1 Hz |
childMemoryPeakBytes |
Under-report |
|---|---|---|---|
| bounded (cap 6, 16 calls) | 3.57 GB | 3.57 GB | 0% |
| unbounded (cap 64, 16 calls) | 7.00 GB | 3.48 GB | −50% |
| unbounded (cap 64, 16 calls, repeat) | 8.97 GB | 5.43 GB | −39% |
Read from telemetry alone, the unbounded run looks cheaper than the bounded one — the inverted conclusion. Steady state is accurate (a running soak read 5.85 GB by both methods); the field aliases only on transients, which is precisely the case it was introduced for.
idleReapMinutes now defaults to 10, not 30 — on new installs; see the
upgrade note above for why an existing seat is unaffected (monorepo#2109,
reversing the earlier decision on that issue to leave defaults alone). The
reasoning that originally argued for holding still is unchanged and is what
keeps the new default off the floor: reaping earlier costs every user a warm
process on next
use, and the measured accumulation is a function of how many agents a seat
touches — which differs enormously between a single-agent user and a
coordinator fanning out a dozen. What changed is the read on where the
midpoint sits. 30 minutes is long enough that the two cases converge in the
worst direction — with the budget off, the coordinator holds every subtree it
touched anywhere in that half-hour window, re-extending it on each fan-out (the
5.85 GB flat row above measured 10 minutes of that, not a whole session), while
the single-agent
user gains a warm process they were unlikely to return to that late anyway. 10
minutes keeps the warm path for the case that actually re-enters an agent while
bounding what a fan-out retains, and 0 still turns the sweep off entirely for
anyone who wants the old behaviour — with the caveat above that 0 stops the
sweep, not every path that can reclaim an idle tree. A seat still hitting the
accumulation path should reach for idleReapMinutes first, then
memoryBudgetMb.
Wire contract: PROTOCOL.md §5 (system.status — file-watch coverage fields).
File events (file:*, plus the skills/specialists rescans) come from recursive
notify watchers over watch roots. Watchers are shared streams: one OS
watcher serves many roots, with a demux narrowing each event to the
subscriber's own root. Grouping is per platform — on macOS (FSEvents) roots
group per parent directory; on Linux (inotify) ALL roots share a single
global stream (intent-hq/intentd#1550).
That matters because every notify watcher costs one inotify instance
(one fd, capped by fs.inotify.max_user_instances, default 128): the earlier
per-parent-directory grouping made the instance count scale with the workspace
count and exhausted the cap on multi-workspace hosts
(intent-hq/intent#3708);
the single global stream keeps it at one instance total.
Recursive watches still scale with directory count: on Linux each watched
directory consumes one slot of fs.inotify.max_user_watches (default 8192 on
many distros, 65536 on newer kernels) regardless of how streams are grouped,
so a host with many or large checkouts can exhaust the watch cap even with a
single inotify instance.
Tuning a multi-workspace Linux host:
-
Raise
fs.inotify.max_user_watches— e.g.1048576(each slot costs ~1 KB of kernel memory only while in use):sudo sysctl fs.inotify.max_user_watches=1048576 echo fs.inotify.max_user_watches=1048576 | sudo tee /etc/sysctl.d/60-inotify.conf
-
Check the daemon's open-file limit (
ulimit -n/nofile): the global watch group holds inotify instances at one, but sockets, PTYs, and child pipes still consume fds — a lownofile(1024 on some distros) surfaces as the same class of resource failures on busy multi-workspace hosts.
Symptoms of exhausted limits. Watch-coverage degradation is WARN-logged;
the creation/registration WARNs carry the live /proc/sys/fs/inotify limits
(as os_watch_limits: inotify max_user_instances=… max_user_watches=…) so an
operator can judge at a glance whether a failure is cap exhaustion:
"shared watcher creation failed; roots in this group are unwatched until a retry succeeds"— the OS watcher itself could not be created (e.g. inotify instance exhaustion). Creation is retried with capped exponential backoff (about once a minute at the cap), and the group's roots are re-registered once it succeeds."shared watch registration failed"— one root's recursive registration failed (e.g.ENOSPCwatch-slot exhaustion, or the directory vanished)."shared watcher callback error; events may be missed"— the live watcher reported an error on its event stream (e.g.notify's "OS file watch limit reached").
The same degradation is surfaced on the wire as the system.status
fileWatch object (failedRoots > 0, or activeStreams below the expected
count — 0 while totalRoots > 0 under creation failure), so coverage loss
is visible to clients, not just in the daemon log.
Multi-MB tool_result.output / tool_use.input bodies do not live in the
agent_message.content JSON column. The message write path extracts any
such body over a 4 KiB inline ceiling into the agent_message_payload side
table (migration 0108, #3884; zlib-compressed when that is
smaller; one row per (message, block_ordinal, kind), kind =
tool_use_input / tool_result_output) and leaves the slim-projection
preview plus the inputTruncated / outputTruncated (+ *Bytes) flags in
the field's position — the same transform the serve-time slim projection
applies, so a slim page read (agent.getConversation) serves straight from
the content column with no side-table access. Full-fidelity reads
(agent.getMessageBlock) splice the original body back before the content
leaves the store, and legacy rows with inline bodies hydrate as no-ops:
splicing is driven purely by side-row presence.
(intent-store/src/message_payload.rs.)
Three mechanisms sit on top of that table (intent-hq/intentd#1757):
Bounded replay. When a lost ACP session is rebuilt, the recovery replay
(intent-services/src/history_xml.rs) renders each tool_use input and
tool_result output middle-truncated to agents.historyReplayToolContentChars
(default 4000, 500..=100000, read live from the settings snapshot at
replay time — previously a hard-coded constant). The store's replay read
(Store::get_agent_messages_for_replay) never materializes a whole
transcript's full bodies: side rows are paged by rowid in small batches and
each full body is decoded → stringified → truncated as soon as it is read,
then spliced in as the replay-preview block contract
(intent-core/src/replay_preview.rs: the heavy field becomes the truncated
preview string, plus the additive inputReplayOriginalChars /
outputReplayOriginalChars count). The formatter renders such a block
exactly as it would render the full body at the current cap — if the live
cap is smaller than the stored preview it re-truncates, and it never expands.
Retention sweep. agents.toolPayloadRetentionDays (default 0 =
disabled, max 3650) is enforced by the existing stream-retention loop
(spawn_stream_retention_loop in the intentd binary crate — the loop
keeps ticking, hourly at most, even when the event sweep is disabled). On
each tick, with the setting non-zero, Store::compact_tool_payloads_before
compacts every full-body side row whose owning message created_at is
older than the window into its *_replay kind (tool_use_input_replay /
tool_result_output_replay) holding exactly the replay-shaped preview at the
current cap ({"text": <preview>, "originalChars": N}, encoding none|zlib
and transfer handling exactly like every other side row), and deletes the
full row — irreversibly: setting the window back to 0 stops further
compaction but restores nothing, and raising the replay cap afterwards
cannot recover characters already deleted. Bodies already under the cap are
converted too, so every pruned block has one shape. Work is chunked (≤ 500 rows per scan plus
one write transaction per chunk; the CPU-bound decode/truncate runs on a
blocking thread before the transaction opens) so the sweep never holds the
write lock for long; delete + insert in one transaction keep the
conversation_bytes triggers balanced; a re-run finds nothing left to
convert (idempotent); the join on agent_message means 0109 staged rows and
thumbnails rows are never touched. Both settings are read live from the
settings snapshot per tick, so a value set from the Settings UI takes effect
on the next tick without a restart.
What a pruned block serves. Two preview shapes coexist and serve
different readers: the write-time slim preview (the head of the body
left inline in agent_message.content with the *Truncated / *Bytes
flags — what agent.getConversation pages and, once pruned,
agent.getMessageBlock return) and the replay preview (the head/tail
middle-truncated string + original char count in the *_replay side row —
consumed only by the recovery replay, never returned over the wire). Normal
hydration ignores replay kinds, so a pruned block keeps serving its inline
slim preview + flags — the agent.getConversation page is byte-identical
before and after the sweep, and so is the recovery replay at the cap in
effect at compaction (splice_replay_preview emits the same block contract
from a full row or a replay row). That equivalence is cap-relative: a later
smaller cap re-truncates a compacted preview exactly as it would a full
body, but a later larger cap renders a longer preview from a full row
while a *_replay row cannot expand past the characters it kept. The one
visible change is agent.getMessageBlock: the full
body no longer exists, so the block is served as the stored slim preview,
flags intact, plus the additive inputPruned: true / outputPruned: true.
Compaction is durable across transcript edits: agent.editAndRegenerate
truncates suffix-only (Store::truncate_agent_messages_from deletes rows at
seq >= the edited message in one write transaction, cascading only the
dropped rows' side rows through the 0109 trigger), so the kept prefix keeps
its ids, seq and every side row — full and *_replay alike — untouched
and a pruned block stays pruned (flags and replay preview intact) rather
than degrading to the inline head preview. The FE-driven
agent.replaceMessages swap still remints the whole transcript. That flag is decided from
store-side compaction metadata read from the same snapshot as the body
(Store::get_agent_message_by_id_with_pruned — a sweep committing between
two separate reads would otherwise stamp a just-served full body as pruned),
never inferred from surviving *Truncated flags: a retained full row that
fails to decode, or a body that arrived pre-flagged and was never
externalized, is served as before and never flagged. With the sweep disabled
the served block is exactly what it was before the sweep existed.
Hot read RPCs — the methods clients poll or fan out on focus (workspace.list
/ workspace.get, agent.list / agent.get, conversation pagination, event
reads) — obey one invariant: cost is O(rows returned). Work is
proportional to the size of the response, never to transcript length, blob
size, repository size, or history depth — and no unbounded filesystem or git
work (workdir walks, git diff, reflink probes) runs inline on these paths.
Every recent performance regression attached unbounded-cost computation to a
bounded-expectation read path (monorepo#958, #963, #1010, #1061, #1395/#1396);
this section records the design that prevents the next one.
Derived or enriched fields on hot read paths sit on a three-rung ladder — prefer the highest rung that fits:
- Stored on write. Maintain the derived value in the same transaction as
the write that changes it; the read path only selects columns. Embodiment:
the persisted
last_assistant_preview/last_user_preview/last_message_rolecolumns onagent_session(migrations 0066/0070) —agent.listpreviews are written at message-append time, so the read path never hydrates or decodes transcript bodies (#958). - Cached with invalidation. Compute off the hot path and serve from a
shared cache with explicit invalidation or a TTL. Embodiments: the
agent.listprojection cache (agent_list_cache.rs— event-driven invalidation on transcript writes, epoch-guarded against stale in-flight loads), and the disk-usage cache (disk_usage.rs— ~60 s TTL, stale-while-revalidate: an expired entry is served immediately while a single-flight background walk, guarded bysingle_flight.rs, refreshes it). - On-demand RPC. If a field cannot be made cheap, it does not belong on
a list payload: give it its own method the client calls when it actually
needs the value. Embodiment:
diffSummarywas removed from workspace metadata payloads (its per-workspacehead_diff_rolluppinned the blocking pool on every list poll, #963) in favor of on-demandgit.diffs.
Two corollaries:
- Degrade by omission, never by blocking. When a cached aggregate is cold or over budget, the read omits the optional field and lets a detached task backfill the cache for the next poll (disk usage's first-poll omission) — a hot RPC never waits out a probe or a filesystem walk.
- Window before materializing. Pagination selects and decodes only the
requested page inside SQLite (
get_agent_messages_page; the preview window query runs on a covering index and never fetchescontent), rather than hydrating the full log and slicing in memory (#1010).
New enrichment fields on hot read paths carry the burden of proof: they must name their rung on this ladder before they land. The companion agent-facing contract lives in the intentd repo's AGENTS.md.
Status: on intentd main (merged 2026-11-25 to 2026-11-27). This section
describes the seams those PRs add and their known limits. The
design that uses them is in
Owner work vs request writes.
Nothing here runs more than one process per tenant yet. The desktop daemon
(SQLite) behaves as before.
| Seam | intentd PR | Main files |
|---|---|---|
| Event fabric | intentd#3783 | intent-services/src/events/bus/fabric.rs, events/bus.rs |
| Event seq cursor | intentd#3778 | intent-store/src/event_repo.rs, postgres/events.rs |
| Process-local state snapshot | none (docs only) | orchestrator-state-snapshot.md |
| Leases (replace work claims, intentd#3779) | intentd#3793 | intent-store/src/lease_repo.rs, lease_keeper.rs, postgres/leases.rs, intent-services/src/lease_keeper.rs |
| Machine link ownership on leases | intentd#3794 | intent-node-connections/src/ownership/leased.rs, intent-store/src/postgres/nodes.rs, intent-svc-remote/src/lib.rs |
| Tenant ownership as a lease | intentd#3800 | intent-store/src/postgres/lease.rs (TenantLeaseKeeper), lease_repo.rs, intentd-orchestrator/src/serve.rs |
| Delivery claims as leases | intentd#3801 | intent-store/src/completion_watch_repo.rs, postgres/completion_watches.rs, postgres/leases.rs |
| Lifecycle gates as leases | intentd#3808 | intent-store/src/lifecycle_leases.rs |
| Single-flight gates as leases | intentd#3809 | intent-store/src/lease_keeper.rs (guard_writes), PR refresh, PR monitor and GitLab refresh code in intent-services |
| Lease-guarded wake send | intentd#3810 | intent-services/src/agent_ops.rs, agent_subscriptions.rs |
| Fenced lifecycle work | intentd#3835 | intent-store/src/lifecycle_leases.rs, retirement, archive and deletion paths in intent-services |
| Tenant state | intentd#3836 | intent-store/src/tenant_state.rs, postgres/lease.rs, intentd-orchestrator/src/serve.rs |
| Settings and GitLab pair in the store | intentd#3780 | intent-services/src/settings_registry.rs, settings_store_follower.rs, intent-store/src/postgres/tenant_config.rs |
| Agent queues from the store | intentd#3782 | intent-store/src/agent_queue_merge.rs, agent_queue_repo.rs, intent-services/src/agent_ops.rs |
| Background jobs | intentd#4078, #4084, #4089 | intent-store/src/job_repo.rs, postgres/jobs.rs, intent-services/src/jobs.rs, jobs/runner.rs, retention.rs |
| Request-write scope and method labels (off by default) | intentd#3920, #3939, #3944, #3996, #4009, #4013, #4016 | intent-core/src/request_scope.rs, intent-transport/src/request_role.rs, intent-services/src/request_role_inventory.rs, intent-store/src/postgres/mod.rs (write_role), intentd-orchestrator/tests/request_write_scope.rs |
| Replica mode (off by default) | intentd#4053, #4060, #4061, #4051, #4050, #4056, #4063, #4064 | intentd-orchestrator/src/serve.rs (serve_replica, ServedReplica), intent-transport/src/replica_gate.rs, intent-services (Services::with_replica, reply_activity), intentd-orchestrator/tests/replica_two_process_e2e.rs |
EventFabric(events/bus/fabric.rs) is the transport underEventBus. It haspublish(envelope),receiver()(raw stream, cursor,FenceHandle, controls) andreceiver_count().LocalFabricis the only implementation. It is the formerRawBus: onetokio::broadcastring and a raw cursor.EventBusholdsArc<dyn EventFabric>.EventBus::newbuilds aLocalFabric;EventBus::with_fabrictakes another one.delivery_task, filters, batching, fences andDelivery::Laggeddo not change.
Limits:
- The
MonitorandHistoryChangedlanes are local-only. A non-local fabric must still deliver them in-process. The home tap stays off the fabric. - Fence receipts are an in-process barrier. A networked fabric needs its
own ordering contract for
events.lostrecovery. - There is no networked fabric. An event published in one process reaches only that process's subscribers.
EventSeq = u64is a durable event's per-tenant log position. It is never 0. On Postgres it strictly increases in commit order; on SQLite see the first limit.Store::insert_event_seqandStore::insert_events_seqreturn each event with its seq.insert_event(s)delegate to them with the old signatures.Store::events_after(after, limit)reads events with seq greater thanafter, in seq order.Store::max_event_seq()returns the highest seq, or 0. Neither filters by caller visibility.- Postgres uses
row_seq(RETURNING row_seq, set under the tenant writer lock), with indexidx_event_row_seq. SQLite usesrowid.
Limits:
- A SQLite seq is not a safe cursor on its own. SQLite reuses a deleted
maximum
rowid, even within one process: retention deletes by timestamp and can remove the newest row, and the next insert takes its seq again. A consumer at that cursor then skips the new event. A SQLite cursor is safe only while nothing deletes the newest row between reads; a fullVACUUMcan also renumber rows. A durable cursor needs anAUTOINCREMENTseq. - Postgres seqs have gaps. All tables of a tenant share
row_seq. Treat a gap as normal. Do not detect loss by checking for seq + 1. - The bus does not call
insert_events_seqyet. No seq reaches the wire.
orchestrator-state-snapshot.md classifies
every Services field (231) and every tenant restore, sweep and loop in
intent-app/src/tenant.rs (26), taken 2026-11-25. Classes: owner, gate,
volatile, cache, connection, config, test, durable. A gate row
names its invariant and says if the Postgres tenant writer lock covers it.
| Class | Fields | Loops |
|---|---|---|
| owner | 31 | 25 |
| gate | 35 (12 partial, 23 no) | 0 |
| volatile | 45 | 0 |
| cache | 26 | 1 |
| connection / config / test | 8 / 36 / 50 | 0 |
It is a dated snapshot, not maintained, and no CI check keeps it current: a
guard test that failed on every new Services field was dropped as too
costly (the struct changed in 29 commits over the 30 days before the
snapshot). Re-check a row against the code before relying on it. Lasting
protection belongs in types, for example process-local state reachable only
through owner-only handles.
One lease mechanism replaces the work claims of intentd#3779. A lease does not depend on which process owns the tenant.
- A lease is a row keyed by
(scope, key).Store::acquire_lease(scope, key, ttl)returnsSome(Lease)when the key is free or expired by the database clock. Each new holder gets a highertoken, a fencing counter per key. Store::renew_leasereturnsfalsewhen the lease is lost.Store::release_leasefrees the key only if it still names this lease.Store::lease_is_heldchecks the lease id, the token and the expiry.- A write that must not land after the lease is lost calls
guard_leaseinside its own write transaction. On Postgres it takes aFOR SHARElock on the lease row; a lost lease fails the write withError::LeaseLost.guard_leaseis crate-private, so guarded writes areintent-storemethods. - Postgres: table
lease, primary key(tenant_id, scope, lease_key); release keeps the row so the token keeps counting. Acquire, renew and release take the tenant writer lock withFence::LeaseOnly: no tenant owner check, so a tenant takeover neither voids nor fences a lease.postgres_backend_lintallowsFence::LeaseOnlyonly inpostgres/leases.rs. SQLite: an in-process map with the same rules. LeaseKeeper(intent-store/src/lease_keeper.rs, re-exported byintent_services::lease_keeper) renews at half the TTL. Each renewal is bounded by the lease's remaining time. When the lease is lost or a renewal does not answer before expiry, itsLeaseFencefires and the held work stops.releasefrees the key on a clean stop.- Users:
spawn_token_usage_scan_loop(scope"token-usage-scan"): a process without the lease skips the tick.- Machine link ownership (scope
"machine-link", below). - Tenant ownership (scope
"tenant", below). - Delivery claims (scopes
"completion-watch"and"delegation-group", below). - Lifecycle gates (
intent-store/src/lifecycle_leases.rs, Postgres only): scopes"agent-retirement","workspace-retirement","archive-fence"and"workspace-deletion", taken after the in-process lock. While the deletion lease is live, it refuses agent inserts and user messages from other processes in that workspace. The work is fenced (intentd#3835): its store writes run underguard_writesand fail withError::LeaseLostonce the lease is lost, and a retry takes the lease again. Limits: a crashed holder, or an acquire that was granted and then cancelled, blocks the key until the TTL; work outside the store (stopping runtimes, publishing events, deleting folders) stops only at the next lease check. SQLite keeps the local gates and takes no lifecycle lease. - Single-flight work:
"pr-refresh"(per workspace and root),"pr-monitor-poll"(per monitor; the row is re-read after taking the lease) and"gitlab-credential-refresh"(per host, plus a version check on the stored refresh token; a token a peer already rotated is a transient error, not a disconnect). - Background jobs (scopes
"job.<kind>", see Background jobs): taken only throughacquire_job_lease, under the per-tenant job cap.
LeaseKeeper::guard_writes(fut)makes every owner-checked Postgres write insidefutguard the lease in its own transaction, so work that lost its lease writes nothing late.
Limits:
- The other 21 tenant loops do not use leases yet. Event retention and the idempotency reap run as background jobs.
- The token-usage scan's writes still go through
begin_write, so they still pass the tenant-owner fence. - The SQLite
guard_leaseis a check when the write starts, not a row lock. That is enough for one process.
Background work that any process of a tenant can run is kept as rows of the
job table, one per (kind, job_key) (intent-store/src/job_repo.rs,
Postgres postgres/jobs.rs). A row holds the schedule: period_ms (NULL for
a one-shot job), due_at, attempt (runs since the last success),
last_error, last_token and last_lease_id (the run's lease, matched by
finish_job, so a run records one result and a restarted process cannot
finish a dead process's run), and state (scheduled or dead). It has no
live lease columns: the lease is the lease row ("job.<kind>", job_key).
Store::ensure_jobcreates the row, due after its first delay, or updates only its period, so the due time and attempt survive a restart or a tenant takeover. It refuses to change a kind between one-shot and periodic; a kind whose shape changes takes a new name.Store::due_jobs(kinds, limit)andStore::next_job_due_in(kinds)read due rows of the given kinds by the store's clock (the database clock on Postgres; the wall clock on SQLite, one process per file).Store::acquire_job_lease(kind, key, ttl, tenant_cap)acquires the job lease unless the tenant already holdstenant_caplive job leases. Postgres counts them in the acquire's own transaction, under the tenant writer lock, so the cap holds across processes; SQLite counts them under the in-process lease map's lock.Store::acquire_leaserefusesjob.*scopes, so every job lease is capped, and a job lease renews only before its TTL passes, so a lapsed one cannot take back a cap place. Every delay is bounded byJOB_DELAY_MAX(10 years).Store::start_job(lease, retry_after)re-checks under the lease that the row is still due, counts the attempt, records the lease token and movesdue_atto the retry time. A run that never finishes (crash, lost lease) is due again then, as its next attempt, so a crashing job backs off instead of spinning every TTL.Store::finish_job(lease, result)recordsDone(next due time, attempt reset; a one-shot row is deleted),Failed(error up to 2 KiB, retry time) orDead(one-shot only; kept for diagnostics, never due).start_jobandfinish_jobguard the job lease in their transaction, so a runner whose lease lapsed writes nothing (Error::LeaseLost). Job writes are owner work: they take the owner fence and refuse a request handle.- Delivery is at least once. Every handler must be safe to repeat, and its
own writes run under
LeaseKeeper::guard_writes.
The runner (intent-services/src/jobs.rs, loop in jobs/runner.rs). A
JobHandler names its job (JobSpec: kind, key, period or one-shot, first
delay, lease TTL of 60 s, max_attempts of 5 for one-shot jobs, payload) and
does one run, returning JobNext::Period or JobNext::After(delay).
Services::spawn_job_runner(handlers, JobLimits) seeds every handler's job,
then on each pass reads the due jobs of its kinds (oldest first, up to
4 × tenant_cap). For each one it has a free local slot for, it acquires the
job lease (tenant_cap, default 2), keeps it with a LeaseKeeper, calls
start_job with the retry time, and runs the handler on its own task inside
guard_writes. The result goes to finish_job, then the lease is released.
The runner sleeps until the next due time, clamped to 1 s and 30 s, or until
a run ends.
- Backoff: 30 s doubling, capped at the period (1 h for a one-shot job), with ±10 % jitter. A periodic job never goes dead.
- Seeding: a seed the store refuses for a shape change drops that kind with a WARN; the other kinds run.
- Stopping: the settings drain stops taking jobs, cancels running
handlers at their next await and releases their leases within 5 s; a
cancelled run records nothing and is due again at its retry time. The
tenant's self-fence and a
NotOwnerrefusal stop the runner. While the tenant is notopen, the runner takes no job and polls every 30 s. - Replicas never run jobs:
spawn_job_runnercallsrefuse_owner_startfirst and returnsNone.
Jobs today. A tenant runtime starts one job runner
(intent_app::tenant::start_job_runner) with the orchestrator's two store
sweeps (intent-services/src/retention.rs):
| Kind | Handler | First run | Next run |
|---|---|---|---|
store.event-retention |
EventRetentionJob: one retention tick with the live events.streamRetentionHours and tool-payload settings |
30 s after the row is first seeded | the retention interval for the hours read on that run (period 1 h) |
store.idempotency-reap |
IdempotencyReapJob: one reap of idempotency keys and usage-rate buckets past their retention |
at once | its period, 1 h |
Both delete by cutoff in bounded batches, so a repeated run deletes nothing extra. A failed sweep is logged at WARN and the run still succeeds. The job rows keep their due times, so the cadence survives a restart or a takeover: an overdue sweep runs on the next holder's first pass. The desktop daemon still runs its own retention and reaper loops, which also run SQLite vacuum and optimize. A tenant stop aborts the runner with the tenant's other loops, so a run in flight keeps its job lease until the TTL (60 s), and the next holder takes that job only after it lapses.
Limits: only the process that started the tenant runtime runs jobs, so jobs do not yet spread across processes; a pool of non-owner runners needs a job write role (a fence that checks the tenant state and the lease guard, not the owner). There is no process-wide cap across tenants, no per-tenant or per-kind rate limit and no priorities. Due rows of a kind with no handler are skipped; remove a kind's rows when its handler goes.
- The tenant owner holds the lease
(tenant, "tenant", ""). Its token is the tenant epoch. Thetenant_leasetable and the owner and epoch columns oftenant_writerare gone. - An owner-only write reads the tenant lease in the statement right after
the writer lock (no extra round trip) and fails with
NotOwnerwhen this process does not hold it. A writer that is not atREAD COMMITTEDfails closed. - The generic lease API refuses the scope
"tenant"; onlyclaim_tenantandTenantLeaseKeeper(postgres/lease.rs) use it.TenantLeaseKeeperis aLeaseKeeperwith a fence margin: it renews halfway to the fence deadline.SelfFencestops work in the same order as before. - A tenant takeover does not void or fence leases in other scopes.
Limit: postgres/lease.rs still holds the tenant claim, the owner check
(ClaimSlot) and the keeper bridge; it is not yet a thin adapter.
tenant_writer.stateisopen,closingorclosed(intent-store/src/tenant_state.rs, intentd#3836). Every writer reads it while it holds the writer lock it already takes, in the existing statement that follows the lock (the one that reads the tenant lease), so the check adds no query, whoever holds the tenant lease.open: writes run.closing: a write in flight when the state moved commits (the move waits for its row lock); every later write fails withError::TenantClosed.closed: the tenant's work has stopped too.Store::move_tenant_statemoves toclosingfromopen, toclosedfromclosing, and back toopenfrom any state. A move from another state changes nothing and reports the state it found, so a tenant reopened during a stop stays open.- A graceful orchestrator stop runs in this order: drain the tenant's work
while it is still
open(agent checkpoints are written during the drain), try to move it toclosing, self-fence and stop, try to move it toclosed, then release the tenant lease. Starting a tenant moves it toopen. The moves are best effort: the move toclosinghas a 3 s budget and the move toclosed1 s; a failure or timeout is logged, and a tenant that already lost its lease skips them, so an error, a timeout or a lost lease can leave the tenant in another state. - SQLite: always open; a move is a no-op.
Limit: the event bus logs TenantClosed refusals at error level during
the window between closing and the fence; only NotOwner is treated as
expected there.
- A completion watch or delegation group is delivered under a lease
(scope
"completion-watch"or"delegation-group", key = row id, TTL 30 s,DELIVERY_CLAIM_TTL) held by aLeaseKeeperwhile the delivery runs. A process that finds the lease held retries later. - A crashed holder's lease expires, and another process delivers. A tenant takeover does not reset a live delivery lease.
- The
claim_epochandclaim_tokencolumns are gone. A settled row retires its lease (retire_lease, which refuses the"tenant"scope).
The durable wake write is guarded by the delivery lease (intentd#3810). On Postgres a queued wake stays hidden from the queue drain until its guarded sync commits, and a direct send guards its message append; if the lease is lost before that commit, the wake is not written. Strict watch registration guards its pair lease in the insert and retries.
Limits:
- The guard covers the wake's durable write only. Once it commits, a later lease loss does not undo it: the claim is not carried into later workers, requeues or drains, event publication and worker start run after the commit, and the watch is retired in a separate guarded transaction. If that settlement fails, it retries under the stable wake id, which keeps the wake from being sent twice.
- On SQLite the enqueue is a held check followed by the normal write-through, which is enough for one process.
- Delivery keeps an in-memory armed check before it reads the stored watch, because watch persistence is best effort and a missing row is ambiguous.
LeaseLinkOwnership(intent-node-connections/src/ownership/leased.rs, scope"machine-link") holds one lease per machine link. A claim first acquires or reuses the lease (its own committed write), then advances the link generation in a separate write transaction guarded by that lease. A failed generation update does not undo the acquisition: the lease stays held until it is released or expires. The link epoch is the lease token.- The welcome record and every journal ack guard the lease in their own transaction, so a process that lost the link cannot record either late.
- A lost lease (keeper fence) closes the link. A stopping connector
releases the lease only if it made the latest claim (same
LeaseOwnerand generation), so a replaced connector cannot release its replacement's link. - The orchestrator turns it on for each tenant before the first connector
starts (
RemoteServicesExt::use_leased_link_ownership). The desktop keepsLocalOwnership.
Limits:
- Re-adding a machine with its current credential leaves a probe claim as the latest one, so an idle connector can keep the lease until its next dial or stop.
- Link ownership no longer needs the tenant lease, but
serve_tenantstill starts connectors only in the tenant owner.
SettingsDocumentStoreis the persistence seam forSettingsRegistry.SettingsRegistry::load_from_storebuilds a store-backed registry. The file backend (desktop) does not change.- Postgres table
tenant_configholds the body and a revision.TenantConfigStore::compare_and_set(expected, body)returnsWritten(rev)or a conflict. A lost race isError::Conflict(-32005). settings_store_followerpolls every 2 s (DEFAULT_POLL_INTERVAL) and applies newer revisions throughServices::apply_stored_settings_reload. This sends the same hooks andsettings:changedas a file edit.FileSecretStore::with_backendputs the GitLab pair inTenantSecretsrows, not insecrets.json.serve_tenant(intentd-orchestrator/src/serve.rs) usesTenantSettingsandTenantSecrets. The follower stops on fence.
Limits:
- A
settings.updatethat loses the race returnsConflict. The registry tries to adopt the winning revision before it returns, so an immediate retry usually lands. The catch-up is best effort: if its read fails or another write lands, the follower poll (2 s) adopts the revision instead. There is no automatic retry. ConfigWatcherrefuses a store-backed registry.
Boot migrations still run for a store-backed registry: recover_tenant
(intentd-orchestrator/src/serve.rs) calls run_boot_settings_migrations,
and SettingsRegistry::strip_legacy writes through the store backend
(write_document).
Store::sync_agent_queue(agent, rows, claims)writes the queue. On Postgres, if the stored version moved, it does a 3-way merge of this process's change onto the stored rows under the tenant writer lock. Claimed ids that another process removed first come back aslost.Store::refresh_agent_queue(agent, local)merges stored rows into memory when the version moved. On SQLite both are a plain replace or a no-op.persist_queue_snapshotsyncs and adopts the merged result.agent.getQueuerefreshes first.- The single-entry drain and the flush drain use
claim_queue_popand drop lost entries. If the claim write fails,claim_queue_popputs the entries back and delivers nothing. Shutdown reconcile syncs.
Open items:
send_queued_message(s)_now, the recovery redrive and the agent manager pops in rehydrate do not claim yet. They can double-deliver across processes.- A crash between the drain and the user-row write loses the entry. A kept claimed row needs a schema change.
- A cancel answers from memory. It can report success for an entry that another process is already delivering.
has_ready_to_send, diagnostics and event snapshots read memory. Nothing starts a drain on one process when another process enqueues.move_agent_queuestill uses compare-and-swap and fails on a stale version.queue_submission_ordercan overlap across processes. Order uses row position, so only metadata is affected.- After a failed claim write, nothing reschedules that agent's drain. The entry waits for the next drain trigger.
Status: replica mode works behind two switches, for test deployments
only. The write role (intentd#3859),
the gate conversions in the table below, the
request-write scope and replica mode
are merged. With INTENTD_ORCHESTRATOR_REQUEST_WRITES=1, the orchestrator
runs 46 allow-listed RPCs inside the request-write scope. With
INTENTD_ORCHESTRATOR_REPLICA=1 as well, a process serves a tenant whose
lease another process holds, runs none of its owned work, and refuses what it
cannot serve. Both switches are off by default, and then every RPC runs in
the tenant owner. There is no router yet, so no client is sent to a replica
in production. It applies only to the Postgres store
(intentd-orchestrator). The desktop daemon (SQLite, one process per
database) does not change.
Today one process owns a tenant. It holds the tenant lease (scope
"tenant"; intent-store/src/postgres/lease.rs: Store::claim_tenant,
TenantLeaseKeeper), and every write checks the owner fence
(PgStore::begin_write → begin_write_as(Fence::Check) →
ClaimSlot::check in postgres/mod.rs and lease.rs). This section
describes how the fence narrows: owned work keeps the lease, and request
writes can come from any process.
Inputs:
- The process-local state snapshot
(one row per
Servicesfield and per tenant loop, taken 2026-11-25). It lists 35gate, 31ownerand 45volatilefields, and 25ownerloops. - Leases:
Store::acquire_lease,renew_lease,release_lease,guard_leaseandLeaseKeeper(intent-store/src/lease_repo.rs,lease_keeper.rs,postgres/leases.rs), used byspawn_token_usage_scan_loop, machine link ownership, tenant ownership and delivery claims.
For all seams and their limits, see Stateless orchestrator groundwork.
flowchart LR
O[Owner process: holds lease] -->|owner role: fence check| W[(tenant_writer row lock)]
R[Request replica: no lease] -->|request role: no owner check| W
W --> G[Per-row guard: row lock, version CAS, claim, unique key]
G --> T[(Tenant rows + event row_seq)]
O --> L[Owned work: loops, machine links, receive hooks]
The lease stays for work that assumes one runner per tenant. Each item moves off the lease only when it gets its own claim.
| Owned work | Where | Why it needs one owner |
|---|---|---|
| Tenant lease bookkeeping | lease.rs: claim_tenant, TenantLeaseKeeper |
It is how the fence changes. |
| Tenant loops not on leases or jobs (21 of 24) | intent-app/src/tenant.rs: spawn_pr_refresh_loop, spawn_pr_monitor_loop, spawn_completion_delivery_loop, spawn_auto_commit_loop, spawn_push_publisher, spawn_auto_archive_loop, spawn_auto_retire_loop, ... |
Two runners double forge calls, wakes, commits and pushes. |
Job runner (start_job_runner) |
intent-app/src/tenant.rs; jobs in intent-services/src/retention.rs |
Each job takes its own lease, but only the process that started the tenant runtime runs the runner today; a replica refuses it. See Background jobs. |
| Startup rehydration | rehydrate_hooks, rehydrate_pr_monitors, heal_event_subscriptions_on_startup |
They start timers and delivery tasks in this process. A second process would deliver again. |
| Machine links (start only) | resume_exposed_machines |
Each link holds its own lease (LeaseLinkOwnership), but connectors still start only in the owner. |
| Git receive hooks | head's git hub, installed by serve_tenant (intentd-orchestrator/src/serve.rs; test tests/node_git_hooks.rs) |
Hub repositories are on the owner's local disk. |
In-memory timers and runtimes (owner fields) |
hold_release_timers, debouncers, completion_delivery_retries, pending_workspace_deletes, pty, mcp_hub, event_bus |
State is only in this process memory. |
Rules:
- An owned item leaves the tenant lease only after it holds its own
lease (
acquire_lease(scope, key, ttl)with aLeaseKeeper). The token-usage scan, machine links and delivery claims do this. - A request replica starts no owned work. It does not call
start_backgroundand does not dial machines.
A request write is a write made while serving a client RPC. It does not use owner memory and does not need the lease.
- The writer lock stays. Every write still takes
lock_tenant_writer. Therow_seqtrigger refuses an insert unlessintent.writer_tenantis set under the lock, so the lock keeps commit order equal to seq order. One tenant still has one writer at a time across all processes. - No owner check. The request role ignores
owner_instanceandepochon the lockedWriterRow. An owner takeover does not refuse request writes. - A per-row guard. Each write that today relies on an in-process gate uses the target mechanism in the table below.
- Claims name the lease, not the tenant. A write for claimed work
checks its own lease (
guard_lease: lease id + token). - Events commit with the row. A write whose event order matters
inserts its event in the same transaction (
insert_events_seq). Today the bus batching writer commits events in a separate transaction, so seq order can differ from row order. - Owner-only tables refuse it. Lease rows, link ownership rows and receive-hook state accept only owner writes.
The role is a property of one store handle. It is not shared tenant state,
so one process can hold an owner handle for its loops and a request handle
for its RPCs. The ClaimSlot stays shared in tenant_registry::TenantState.
pub enum WriteRole { Owner, Request, Unclaimed }, held in a newPgStore.rolefield (not inTenantState).- Opens set it:
Store::open_postgres_owned/try_open_postgres_owned→Owner.Store::open_postgres→Unclaimed(today's rule: writes only while no process ever claimed the tenant; admin and repair tools keep it).- New
Store::open_postgres_request(pool, tenant, options, OrchestratorOnly)→Request. - New
Store::request_writer(&self) -> Store: a clone withWriteRole::Request, for an owner process's RPC path.
FencegainsRequest.begin_write()callsbegin_write_as(self.role.fence()):OwnerandUnclaimedmap toFence::Check,RequesttoFence::Request.Fence::Requesttakes the lock and skips the owner comparison only in a process that holds no claim. A request handle in a process that holds a claim (such as the owner'srequest_writer()) still compares the owner, so its writes stop at a takeover.- New
begin_owner_write(): refuses a request handle withError::NotOwner, then runsFence::Check.Unclaimedpasses, so admin and repair tools keep today's rule. Owner-only writes use it: lease rows, tenant claims and state moves, and machine link ownership (nodes.rs).
A process may use a request handle for an RPC only when every gate that RPC
touches is converted, and the volatile state it reads is in the database.
The scope lets the owner process serve allow-listed RPCs with the request role, so each one is proven safe before a replica serves it.
- Scope.
intent_core::request_scopeis a task-local scope. The router sets it inprepare_messagearounddispatch, only when the switch is on and the method is request-safe.scope()returns the request future directly, so the stack does not grow. Inside the scope an owner Postgres handle writes asWriteRole::Request(PgStore::write_role). In a process that holds a claim the request fence still compares the owner, so a scoped write stops at a takeover. Owner-only store work (begin_owner_write, lease and tenant writes, link ownership rows) refuses any handle withNotOwner. SQLite only logs. - Labels.
intent-transport/src/request_role.rsgives every router method one label:RequestSafe,OwnerOnly(the default) orReadOnly. A golden test fails on a method without a label. Counts: 46 RequestSafe, 263 OwnerOnly, 176 ReadOnly (485 methods). - Tripwire.
request_scope::owner_local(gate)records each process-local gate a scoped request reaches. Every process-localServicesfield is aProcessLocal<T>, whoseDerefrecords the hit, so no access path is missed. Golden inventories (intent-services/src/request_role_inventory.rs,tenant_registry) classify everyServices,EventBus,TenantStateandPgStorefield. Spawns go throughspawn_detached(records a hit) orspawn_daemon_carrying_scope(work that finishes the request's own write); a lint refuses a rawtokio::spawn. - Proof per method. A method becomes
RequestSafeonly with a fixture inintentd-orchestrator/tests/request_write_scope.rs(request_safe_methods_touch_only_shared_gates): no owner-only write, no tripwire hit, at least one write opened. A two-process probe checks that a held scoped write is refused withNotOwnerafter a takeover and the row is unchanged.read_only_methods_open_no_writeruns everyReadOnlymethod in the scope and fails on any write. - CI. Every PR runs the fixtures, the binary end-to-end test
(
request_writes_e2e, switch on and off, fails on a tripwire warning) and, in thestore-postgresjob, the orchestrator suites that serve a tenant's clients again with the switch on. The two-process gate suites callServicesdirectly, so the switch does not change them.
Request-safe methods, by family:
| Family | Methods | Why it is safe |
|---|---|---|
| Workspace row | workspace.update (not archived, status or repositoryPath, which run as the owner), setAutoCommit, markSeen, dismissAttention |
One row write under the tenant writer lock |
| Notes, tasks, comments, primitives | 30 methods, including note.list (default notes are an insert-if-absent) and task.assignAgent |
Note rev CAS; idempotency reservation rows; task projections in the baseline CAS |
| Workspace context, members, invites | workspace.updateContext, updateUiContext, members.add, members.setRole, invite.revoke |
Guest cap, credential and role checks run inside the write |
| Discussions | discussion.rename, react, delete |
Role, participant and reaction-version checks run inside the write |
| Other rows | host.invite.revoke, agent.markSeen, app.storage.set, app.storage.delete |
The join re-checks revoked_at; the seen marker is a compare-and-set; a storage write checks that the app's stored record still approves the session's bundle |
Everything else stays owner work. The reasons: processes and disk (git,
files, scripts, terminals, search, MCP servers, asset files, app fs and
exec), the agent runtime (agent turns, queues and wakes, discussion
send/stop/retry, hooks, PR monitors), process-local state the write depends
on (settings, provider profiles, push links), lifecycle leases (archive,
delete, retire, repository captures), presence (desktop, browser tabs,
transport revocation on member removal) and external-only writes (forges,
Linear, Sentry). app.fs.list, read, stat and app.secrets.list are
owner work because each call writes an audit row.
Accepted process-local state. A scoped request may read these
(ACCEPTED_OWNER_LOCAL). On the owner each is correct, because every agent
runs and every home setup opens there. A replica does what
the table says. Its rerun of every request-safe fixture
(request_safe_methods_run_on_a_replica) allows only event_writer,
event_fanout and line_attribution_recompute.
| Gate | On a replica |
|---|---|
event_writer |
Accepted with a limit. The writer task appends the event as a request write of that process, after the domain write commits, so events from two processes can reach the log out of row order. Moving the append into the request's own write waits for the event fabric |
event_fanout |
Accepted with a limit: a replica's clients see that replica's events; other clients read the durable rows. Transient events are not replayed |
agent_activity |
Not read. Replies derive activity from the stored session state that the owner's runtime writes at each turn's start and end (Services::reply_activity): no idle grace window, and it lags by that write |
display_status_cache |
Not kept. A replica records no baseline and emits no displayStatus, waiting or running-flag transition; the owner's next compute catches up. Its rows reply scriptsRunning and backgroundTasksRunning false |
agent_attention |
Not read. The display-status derivation leaves out deferred attention and secret-request waiters; stored attention rows and question markers still count |
line_attribution_recompute |
Replica-local. The replica recomputes after its own writes; the write is guarded by the note content the recompute read (upsert_note_line_attribution_if_content), so an older recompute never replaces a newer edit's attribution |
settings_snapshot |
Not reached. workspace.members.add reads the guest cap from the tenant settings document inside its write, under the writer lock a settings write also takes |
home_setup_status |
Not read. A replica opens no home, so its rows carry no setup in progress; the owner's events carry it |
app_session |
app.storage.set and delete are refused on a replica. Ending sessions in every process waits until replicas open sessions |
A context or UI-context write (workspace.updateContext,
workspace.updateUiContext) reads the workspace's existence inside its write,
so one that commits after another process deleted the workspace is
NotFound, not a foreign-key Internal.
Unversioned note writes retry across processes. Every note write on a
Postgres tenant compares the rev its writer read, and a note's write lane
(NoteWriteLanes) orders the writers of one process only. So the metadata
writers (task status and its redirects, task.markAsTask,
task.setRelations, task.assignAgent, task.removeAgentFromAllTasks, and
the title and tag writes of note.update and note.updateMetadata),
note.restoreVersion and note.update content without expectedVersion
re-read the note and re-derive their change when another process wrote it
between their read and their write (retry_metadata_conflict, at most 8
attempts; intentd#4050, intentd#4056). A caller's expectedVersion stays a
compare-and-swap: its Conflict (-32005) is returned, never retried.
Adopting a stray spec note bumps each moved child's rev, so a stale writer
cannot write the old parent back.
An orchestrator started with INTENTD_ORCHESTRATOR_REPLICA=1 (off by
default; test deployments only; a startup error without
INTENTD_ORCHESTRATOR_REQUEST_WRITES=1) serves a tenant whose lease another
instance holds as a replica, instead of waiting for that lease. A free
lease is still claimed at startup, so the first instance to start owns the
tenant.
What a replica builds. serve::serve_replica builds only what serving
clients takes:
- A request store handle (
Store::open_postgres_request): no claim, and owner-only store work refuses it withNotOwner. - The tenant's
Services, marked as a replica (Services::with_replica) before the feature crates are composed. - Its own event bus. Its clients see only its events.
- An adopt-only settings follower. It adopts newer documents but runs no
server.*hooks and no identity re-key; the lease holder runs them. - Its own client connections and listeners. Each replica makes its own TLS certificate, so its fingerprint differs from the owner's.
- A lease watcher that re-reads the tenant lease's live holder
(
Store::tenant_lease_holder) and the tenant state every second.
A replica starts none of the owner's work: no receive hooks, startup
recovery, agent manager, interrupted-agent resume, registries, loops, store
sweeps, machine links, MCP servers or tenant watchers. This is structural
(ServedReplica has no field for a lease, fence, tenant runtime or agent
manager), and each owner starter also checks Services::refuse_owner_start
first: on a replica it does nothing, logs at ERROR and counts
ReplicaState::refused_starts, which tests require to stay 0.
Every call a replica's router dispatches runs inside the request-write scope
(ScopeLog::for_replica), whatever the method's label. The replica keeps the
totals of its scopes (ReplicaScopeTotals: dispatches, writes opened,
owner-only writes, process-local gate hits); on a replica an owner-only write
or a process-local gate hit logs at ERROR every time. The TRACE target
intentd_orchestrator::replica_totals logs these totals and the live tokio
tasks on every watcher poll.
Method routing. A replica runs only the methods
intent_transport::replica_gate serves and refuses every other one, router
and fast path alike, before any handler runs: -32003 with
data = { code: "owner-required", method, leaseHolder, retryable: true }
(protocol §9). leaseHolder is the lease
watcher's last read, or null while no live lease exists. It serves:
- The request-safe router methods, inside its request-write scope, except
app.storage.setanddelete(a replica opens no app session), andworkspace.updateonly with request-safe fields. - The read-only methods in
REPLICA_READS(25), each proven to read only the store (replica_reads_touch_only_the_store). - Outside the router:
client.hello,drafts.*(request-safe fast-path writes,REQUEST_SAFE_FAST_PATHS) andsystem.status,startupStatusandshutdown, inside the scope; andevents.*, presence, thenote,taskandcommentchannels and every channel unsubscribe, outside the scope (the event bus starts a task per subscription, which the tripwire would count).
Everything else is refused, unknown names included: owner-only methods,
read-only methods that read owner memory, disk or machine links (home routing
never runs on a replica), host.*, browser.*, server.*, pairing.*, the
/invite flow, /tunnel, invite link creation, app.session.attach, and the
workspace, chat and agent channels (their snapshots read the owner's
live state). The gate sits after the collaborator allowlist, so a guest still
gets its refusal without data first. The golden
intent-transport/tests/goldens/replica_methods.txt records every
client-callable method's decision, so a new method is refused on a replica
until someone serves it there with a proof.
Revocation. The owner closes a revoked principal's connections through its in-process revocation feed, which a replica does not receive. A replica therefore checks, before each frame of a connection admitted with a per-principal credential, that the credential is still active (one indexed read, no write), and re-checks every connection every 2 s in its own task, so a connection that only listens also closes. When the credential is revoked, the principal is removed from the host, the host role changes or the admin token rotates (within its 60 s cache), or the read fails, the frame runs nothing and the connection closes.
When the lease frees up. A replica claims the tenant once its lease
watcher reads no live lease while the tenant is still open: its owner crashed
or lost the lease. It claims through try_serve_tenant, the same open a
normal start uses (ServedReplica::try_claim), so the owner's work starts
only after the claim. The reclaim claim
(Store::try_reclaim_postgres_owned) checks that the tenant is open under
the writer lock in the claim transaction and never moves the tenant state,
so a closed or closing tenant is never reopened. The lease decides a race
between replicas: the losers write and start nothing, and keep serving as
replicas that name the new holder.
On a win, the replica keeps serving while the owner is built. Its request handle shares the process's claim slot, so from the claim on its writes compare the owner. Then the orchestrator stops the replica's listeners (clients reconnect), stops the replica, starts the owner's listeners and watches the owner's fence. A failure before any claim leaves the replica serving and retries with backoff (up to 30 s). A failed open after a claim gives the lease back, and the claim's fence stops the replica too.
A clean owner stop moves the tenant to Closed before it releases the lease.
The watcher reads the lease holder first and the tenant state second, then
publishes the state before the holder. A holder read that finds the lease
released therefore pairs with a state read taken after the release, which
already shows Closed, so a released lease on a closed tenant is never
reported free: a closed tenant stops its replicas,
and the process exits 1 for its supervisor to restart it. Replicas therefore
cover an owner crash or a lost lease, not a graceful owner restart.
Two-process proof. intentd-orchestrator/tests/replica_two_process_e2e.rs
runs replica mode with real orchestrator binaries on one Postgres tenant, in
the store-postgres CI job (about 25 s). orch-a claims the tenant and
orch-b serves it as a replica. The test checks, in order:
- A client of B runs one call of every request-safe family, and each result is read back through A.
- A and B write one note 20 times each at once (content and metadata). No
client sees an error, every line is kept, and every write gets its own
rev. - Each process's clients see only that process's events, and every event reaches the shared log in the order its process emitted it.
- B refuses owner-only methods with
owner-requirednamingorch-a. A refused call writes no row and opens no store write. - B holds no lease row, starts no owner work, reaches no owner-only store work or process-local gate, and its live tasks settle after a burst of calls.
- A is killed. B claims the tenant and serves it as its owner on the same
socket, and a third replica,
orch-c, names B. - A process with the replica switch off still waits for the held lease.
- A clean stop of the owner closes the tenant, and the replica exits.
The test writes a JSON report (steps, timings, counts) to
$INTENTD_REPLICA_E2E_REPORT.
What is left before production replicas:
- A router that sends a client to a replica, and forwarding of
owner-requiredcalls to the lease holder. - A networked event fabric (NATS, a second
EventFabric), so a replica's clients see other processes' events, and with it event appends inside the domain write. - A graceful owner hand-off that releases the lease without closing the tenant, so replicas cover an owner restart.
- Replica-safe sources for owner-local reads: 55 read-only methods read
owner-local live state (
READ_ONLY_OWNER_LOCAL_READS; for exampleworkspace.get,agent.list,settings.get), and 14 hand work to the owner (READ_ONLY_HANDOFFS). Clients do not readagent:queue:updated.data.queueVersionyet. - Owner-only families to move: settings writes (mutation in a spawned
task, per-process revision counter), member removal (in-process queue
purge and connection close), app sessions, the archive-script lease
(
archive_script_gates) andbrowser_tab_displayed. - Background work as jobs with their own leases, so the tenant lease shrinks to a tenant state.
Families group the 35 gate rows of the snapshot, plus the store's own gates
(marked "(store)"). "Lock" is the snapshot's writer-lock value. A row marked
done names the merged change; where a process-local gate stays, it only
orders this process's own work.
| Family | Gate | Lock | Target mechanism |
|---|---|---|---|
| Write, then publish in order | browser_client_pin_gate |
partial | done: pin + workspace:updated delta in one writer transaction (intentd#3863); claimed tabs move only while the setter's pin is still the stored pin, read in the move's transaction, with their browser:tab-updated events (Store::reassign_claimed_browser_tabs_to_pin, intentd#3897) |
browser_tab_gate |
partial | done: every tab write (upsert, remove, sync, force close, claim, migration, superseded re-home) appends its browser:tab-* events in its transaction (TxEvents); a claim's write checks the pin it chose its host by (intentd#3897) |
|
pending_question_mutation_locks |
partial | done: marker set appends agent:updated in its CAS transaction and retries when another writer moved the marker; marker clear, proposals, question dismissal and secret resolutions read and write session metadata with their agent:updated in one transaction (Store::edit_agent_session_metadata, intentd#3897) |
|
attention_mutation_gates |
partial | done: clears and resolveBlocker append agent:updated in their transaction; a surfacing appends its event only in a transaction that finds its request still current (Store::surface_attention_request, intentd#3897) |
|
discussion_control_gates |
partial | no change needed: discussion:activity is transient and carries the activity version, bumped in the control's own transaction; clients merge by version |
|
agent_queue_publish_gate |
no | done: agent:queue:updated.data.queueVersion (shared-store daemons only) is the stored queue version the snapshot shows; clients drop a lower version (06-events.md, intentd#3897) |
|
task_event_baselines (store) |
no | done: a per-workspace baseline row with a version CAS; projection events are appended in the CAS transaction (intentd#3906). task_events_enabled stays per process |
|
| Read-modify-write of one record | agent_queue_persist_gate |
partial | done: version CAS (queue version + three-way merge, intentd#3782); drains, sends, removals and the poisoned-queue move claim or merge under the writer lock; claimed rows survive a crash; finished and cancelled entries are recorded (agent_queue_done) so no write or claim stores them again (intentd#3880) |
settings_revision_gate |
no | done: registry writes CAS on tenant_config.revision, and their rollbacks run under the revision gate the follower needs to adopt a newer document, so a restore is a CAS on the revision this process wrote (a newer write wins; the rollback reports incomplete). The hook-failure rollback restores a database-backed key only while it still holds the value the batch wrote (Store::restore_setting_if_unchanged, both backends; intentd#3929). Residual: a same-value write by another process in that window is undone (settings has no version) |
|
settings_secret_gates |
no | done: a failed batch restores each secret group (token + forge siblings) only while the token row is still one of this handle's writes (the last committed nonce, or a later attempt with an unknown outcome) holding a value the batch wrote: SecretStore::restore_if_unchanged, one writer transaction on tenant rows, so a newer write stands, same value included (intentd#3929). The per-account gate stays for this process's own order |
|
human_instruction_authority |
partial | done: sync/replace/move_agent_queue drop instructions whose author is revoked, read in the queue write's transaction, and a member removal bumps the swept agents' queue versions (intentd#3867). Workspace member removal, leave and the archive guest sweep take the same authority, and the drain re-checks workspace membership (intentd#4008). It reads the current revocation state, not a recorded authority version |
|
identity_transition |
partial | done: FOR UPDATE on the principal row in the write transaction (upsert_principal_checked, insert_workspace_invite_within_cap_as, insert_host_invite_as); the loser gets Error::Conflict or IdentityLocked (intentd#3867) |
|
group_persist_lane |
no | stays owner-only until an ordered design lands: a row lock alone does not keep enqueue order (a delayed upsert can recreate a settled group). Target: a versioned upsert plus a terminal settled state that refuses later upserts | |
note_write_lanes (store) |
covered | already safe: every note update is a CAS on rev; the lane only queues this process's writers. Residual: comment orphan flags are set after the persist commits (cosmetic, flags are one-way) |
|
| Quota (count, then insert) | pr_monitor_registration |
partial | done: row lock on a per-agent quota_lock row (scope pr-monitor); the count and the insert, adoption or owner change share one writer transaction (intentd#3861) |
invite_nonce_permits |
no | done: nonces are invite_nonce rows (both backends); issue counts and inserts under the per-tenant quota_lock row (scope invite-nonce); a prove claims the row, which keeps counting until spent or released (intentd#3861) |
|
| Dedupe and idempotency | dismissal_notices_sent |
no | done: an agent_dismissal_notice row per (agent, message id), INSERT ... ON CONFLICT DO NOTHING, released when the marker write fails; both backends (intentd#3865) |
idempotency_inflight |
partial | done: a pending idempotency_key row with an expiry by the database clock, renewed while the op runs; taken over only once expired, never by a takeover; waiters replay the stored result (intentd#3865) |
|
attachment_idempotency_inflight |
partial | done: the same reservation (key attachment-placement:<key>) before the binding lookup; waiters replay the binding (intentd#3865) |
|
| Single-flight work | completion_deliveries_in_flight |
partial | lease per watch or group (intentd#3801) |
completion_watch_registration_gate |
partial | pair lease guarded in the insert (intentd#3810); the in-memory armed check stays | |
automatic_pr_refresh |
no | lease pr-refresh per workspace and root (intentd#3809) |
|
review_monitor_poll_lane |
no | lease pr-monitor-poll per monitor (intentd#3809) |
|
legacy_pr_monitor_poll_lane |
no | lease pr-monitor-poll per monitor (intentd#3809) |
|
gitlab_credential_gate |
no | lease gitlab-credential-refresh per host + version check on persist (intentd#3809) |
|
| Multi-step lifecycle | agent_retirement_gates |
no | lease agent-retirement per agent (intentd#3808) |
archive_fence |
no | lease archive-fence per workspace (intentd#3808) |
|
workspace_mutations |
no | lease workspace-deletion; other processes' agent inserts and user messages in that workspace are refused (intentd#3808) |
|
desktop_writes scope (store) |
covered | already safe: the writer lock plus a target-live predicate in each desktop write | |
| Local process and disk | archive_script_gates |
no | stays owner-only: the run is on the owner's disk (head checkouts). Before unarchive, delete or retire run on a request handle, the run must hold a lease they wait on; archive_fence_after_archive_script checks only its own process's gate |
worktree_locks |
no | stays per host: keyed by local path; git's lock files cover other processes | |
scripts_running_state |
no | stays owner-only: derived from the owner's scripts and workers | |
warm_in_flight |
no | stays per process (local repo cache) | |
repository_review_capacity |
no | stays per process (local capacity). Its per-branch-pair MR create lock is keyed by boot id; GitLab refuses a duplicate open MR | |
repository_resource_capacity |
no | stays per process | |
repository_child_git_capacity |
no | stays per process | |
repository_checkout_capacity |
no | stays per process | |
repository_selection_capacity |
no | stays per process | |
desktop_writes.maintenance (store) |
no | stays owner-only (startup rehydration) | |
browser_tab_displayed (store) |
no | stays per process: a cache of the host connection's displayed fact, not an ordering gate. It moves with presence; browser-tab reads stay with the host's process until then |
|
queue_versions and its write_lock, writer_slot (store) |
covered | stay per process by design: CAS base, recovery lock and pool admission |
Notes:
- "Stays per process" is correct when the bound protects this process's CPU, memory or disk. N replicas then allow N times the work in total.
- Every Postgres write holds the tenant's
tenant_writerrow lock for its whole transaction, in every process and role. An in-process gate matters across processes only where its critical section spans more than one transaction or reads outside the transaction it writes in. - A version CAS that loses returns
Error::Conflict(as the store-backedSettingsRegistrydoes). The caller re-reads and retries, or reports the conflict.
- Claims survive an owner takeover. A lease depends only on its own id, token and expiry (by the database clock), not on the tenant epoch, so a takeover does not void it. This holds for delivery claims too (intentd#3801).
- One shared mechanism puts events in the domain transaction.
WriteTx::append_eventappends the event in the caller's transaction (SqliteEventTxon SQLite), andWriteTx::commit_handing_offhands it to the bus throughintent_store::CommittedEventsafter COMMIT, before the writer slot is released, so one process's hand-offs follow seq order (intentd#3863). Callers prepare events withEventBus::prepare_append. The bus batching writer stays for events that have no domain row; across the two paths, order is by commit. - A tenant state on the lock row closes request writes.
tenant_writerhas a state (open,closing,closed; intentd#3836). Every writer reads it under the lock it already takes and refuses when the tenant is notopen. No extra query. See Tenant state. - A quota row holds no count. The
quota_lockrow is only a lock anchor; the count is read from the quota's own rows under it, so nothing drifts (intentd#3861).
intent-core ◄───────────────────────────────────────────────┐
▲ ▲ ▲ ▲ ▲ ▲ ▲ ▲ │
│ │ │ │ │ │ │ └── intent-providers ◄── intent-acp │
│ │ │ │ │ │ │ (acp also ► pty, js) │
│ │ │ │ │ │ └──── intent-context │
│ │ │ │ │ └────── intent-git │
│ │ │ │ └──────── intent-sourcecontrol │
│ │ │ └────────── intent-pty │
│ │ └──────────── intent-linear / intent-sentry │
│ └────────────── intent-store ◄── intent-search │
└── intent-services ──► (store, git, sourcecontrol, acp, │
▲ context, providers, pty, search, │
│ linear, sentry) │
intent-transport ──► services intentd (bin) ──► all
(intent-js is a leaf with no workspace dependencies; it is consumed by
intent-acp and the binary.)
Rules:
intent-coreis a leaf — no dependency on any other workspace crate. It defines the domain vocabulary (ids, timestamps, errors, event types) and traits (ContextEngine,WorkspaceApi) that higher layers implement/consume. (intent-coreadditionally carries a dev-only, version-less dev-dependency onintentd-test-support— itself free of workspace dependencies — for the shared source-lint scaffolding; the normal-build leaf property is unchanged.)intent-transportnever touchesintent-storedirectly. It only depends onintent-services. This guarantees the RPC router and the agent MCP server share one code path.intent-acpcalls back into business logic through a trait (WorkspaceApi, defined inintent-core, implemented inintent-services) to avoid a dependency cycleservices → acp → services. Concretely:servicesconstructs the ACP client and hands it anArc<dyn WorkspaceApi>so the agent→BE MCP server reuses the same logic. (intent-acpadditionally carries a dev-only, version-less dev-dependency onintent-servicesso its binding tests can drive the real service implementations — a Cargo-permitted dev-dep cycle; the normal-build dependency direction is unchanged.)- No cross-imports between sibling "feature" service modules.
services::notesandservices::gitcommunicate through the store/event bus, not by importing each other. - The binary crate is the only place allowed to wire concrete implementations together (composition root), keeping every library crate testable in isolation.