apoc
Unrestricted process control and durable execution for LLM agents.
apoc (apocalypse) replaces shell-shaped process inspection, PID bookkeeping,
background-job glue, and one-off supervisors with one typed control plane. It
gives agents fresh process state, exact process identities, durable executions,
bounded concurrency, resource ownership, causal history, and JavaScript
composition through the same command graph.
It is built for workloads where independent operations run concurrently, long-lived work must survive the initiating call, and later agents need to inspect exact outcomes without reconstructing state from terminal transcripts.
Install · Quick start · Execution model · MCP · Security · Operations · Reference
Core guarantees
| Capability | Contract |
|---|---|
| Process identity | Mutations target boot ID, PID, and nanosecond start time to prevent PID-reuse mistakes. |
| Durable execution | Accepted commands retain specifications, attempts, bounded logs, events, ownership, and terminal results. |
| Exact arguments | Direct argv is the default; shell parsing requires explicit --shell. |
| Replay safety | Caller-supplied idempotency keys prevent repeated operating-system mutations. |
| One command graph | CLI, MCP, and Code Mode share schemas, validation, history, and execution state. |
| Local-first operation | No account, telemetry service, or required remote control plane. |
Status and scope
| Property | Current contract |
|---|---|
| Release | 0.9.1 |
| Platform | Supported: macOS |
| Minimum Rust version | 1.95 |
| Interfaces | CLI, MCP stdio, Code Mode JavaScript, and an embedded Rust library |
| Compatibility | SemVer releases with versioned durable schemas and pre-migration database backups |
| Release gates | rustfmt, Clippy with warnings denied, workspace tests, package contents, and publish dry-run on macOS CI |
| State | Local SQLite database, execution logs, and content-addressed artifacts |
| Authority | The operating-system permissions of the user who starts apoc |
| License | MIT |
The 0.x line is actively evolving. Breaking public-interface changes receive
a minor version bump; durable state changes use explicit schema migrations.
Security and trust model
apoc is not a sandbox, policy engine, confirmation layer, or embedded model. It exposes destructive operations and their metadata directly, using the authority of the user who starts it. The calling agent remains responsible for selecting the correct target and action.
apoc can ask a decider you register before it launches a command. It ships no deciders and no rules; with none registered it asks nothing, records nothing, and refuses nothing. A decider guards against accidents, not adversaries: apoc has no privilege boundary, so an agent that can run commands can also remove a decider. See Ask a decider before commands run.
apoc has no telemetry, account service, update checker, or automatic network access. Network requests occur only when the user configures and invokes an HTTP, MCP, or OpenAPI provider.
Composed Code Mode
Prefer native MCP arguments over shell-quoted JavaScript. A short call is enough:
Local calls inherit the outer purpose and derive mutation keys automatically.
Optional outer purpose states the intent once. Optional idempotency_key
preserves child replay across new executions; without it, keys stay scoped to
one execution and its replay passes. Explicit nested values override defaults,
and external connector arguments remain unchanged.
Save lengthy source and use apoc code run @program.js --purpose 'Verify build' --idempotency-key build-v1 --timeout-ms 45000. Files are UTF-8 and resolve
relative to the caller directory. CLI mutations require a purpose and key;
framework discovery is purpose-free.
Commands judge exit zero by default. Add an expectation when success means
something else. Compose dependent calls with await, independent calls with
Promise.all, and return only the result the next decision needs.
See the operator skill for concise examples and references.
Install
apoc skill install writes the embedded operator contract to
~/.agents/skills/apoc and links the Codex and Claude skill roots to that
canonical copy. Run it again after an upgrade. A successful status reports
"ready": true.
Each crates.io release contains the complete MIT-licensed source. Development happens in a private repository; the crates.io package and docs.rs source view are the public source distribution.
Quick start
Run one exact-argv command and receive its durable result:
The default response contains only the execution ID and verdict:
Retained logs and the complete record require an explicit addressed read.
Use the returned execution ID to inspect or control the work later:
execution wait --timeout-ms is a client wait boundary. If the execution is
still active at that boundary, it returns the current pending verdict without
canceling or failing the execution.
Limit a native execution and every process it owns with one family budget:
memory_limit_mb caps combined resident memory. cpu_percent caps the sampled
combined CPU rate, where 100 percent equals one logical CPU. cpu_time_ms caps
accumulated CPU time. apoc samples these native ceilings every 100 milliseconds,
persists the measured breach, and recursively cancels the execution graph. They
are cancellation ceilings, not kernel reservations. Use built-in isolated
execution with memory_mb, cpu_count, and pids_max when the command needs
hard VM resource allocation.
Run the same exact-argv command in apoc's built-in macOS VZ guest with
--isolated. This path does not require provider registration. local resolves
the packaged or development VM bundle; an absolute bundle path and a canonical
sha256:<digest> image reference are also accepted.
Rust INCURS owns this command surface and the native apoc-macos-vz provider.
apoc keeps the durable execution identity, retry policy, verified image,
exports, redacted logs, controls, and recovery. The provider owns
Virtualization.framework configuration, pooling, snapshot attempts, and the
guest transport. Snapshot restore failures are recorded against the compatible
image fingerprint and fall back to a cold warmed VM instead of claiming a
snapshot exists.
Declare files or directories to import after the guest command with --export.
Each matching export becomes a verified, content-addressed execution artifact.
The source is an absolute guest path, the destination is a unique artifact name,
and when is success, failure, or always.
apoc verifies the guest SHA-256 and the total artifact byte budget before it
stores anything. It rejects incomplete streams, undeclared indexes, duplicate
destinations, missing condition-matching exports, and exports emitted for the
wrong terminal condition. The stored envelope uses application/x-tar; its
archive contains the exported value at value.
An isolated execution remains controllable through its apoc execution ID. Start the command, then send UTF-8 input, a named signal, or cancellation through the same public lifecycle used for native commands.
apoc claims each input, signal, or cancel idempotency key before dispatch and records the result afterward. An exact retry returns the original result, a changed request conflicts, and an ambiguous prior dispatch is not repeated. It rejects new controls before provider acceptance and after terminal state. Terminal publication guarantees the active control handle is gone and the VM slot can return to the pool.
Pass --pty to allocate a controlling terminal inside the isolated guest.
Standard output and standard error share the stdout event stream, and
execution input writes through the PTY master. The initial terminal size is
80 columns by 24 rows.
Isolated commands accept secret environment references without storing their
resolved values. apoc resolves each value only while constructing the provider
request, withholds logs while redaction is pending, and replaces every complete
value with [REDACTED] before publishing terminal state. Recovery removes
potentially unsafe logs if a required value can no longer be resolved.
--max-attempts also applies to isolated executions. apoc retains one public
execution ID, assigns deterministic provider request IDs ending in
:attempt:N, records every failed attempt, appends output in attempt order,
and makes cancellation wake retry backoff immediately. Live input and signals
are unavailable between attempts until the next provider identity is accepted.
Choose the smallest execution surface
| Work | Preferred surface |
|---|---|
| One process query or mutation | apoc process ... |
| One managed command | apoc execution command or start |
| One isolated macOS VZ command | apoc execution command --isolated or start --isolated |
| Live processes for a known execution | apoc execution tree EXECUTION_ID |
| Repeat a command or typed apoc operation until an outcome | apoc poll run or start |
| Known independent commands | apoc execution batch |
| A native stdout pipeline | apoc execution pipeline |
| Heterogeneous concurrent tools | apoc code run |
| Agent-host integration | apoc --mcp |
| External MCP, OpenAPI, or macOS action | apoc provider ... and apoc action ... |
| Prior apoc use in this worktree | apoc history ... |
Every surface resolves through the same typed graph and durable lifecycle:
CLI MCP Code Mode
| | |
+----------+-------------+
|
typed command graph
|
per-user daemon
/ | \
executions events ownership
|
macOS processes, isolated VZ, and providers
All commands support TOON, JSON, YAML, Markdown, and JSONL output. Use
--schema for one command's JSON Schema and --llms for the compact
LLM-readable command manifest. Use --filter-output when an agent needs only a
few fields from a CLI response. Code Mode programs should return a compact
synthesis instead of complete nested execution envelopes.
Process discovery and control
apoc resolves a selector from a fresh native snapshot before every mutation.
The durable identity is BOOT_ID:PID@STARTED_AT_NS, so PID reuse cannot redirect
an operation to a different process.
When an execution ID is available, inspect its processes with execution tree.
It recursively follows owned child executions and verifies every captured root by
boot ID, PID, and nanosecond start time before returning a fresh tree. Its
state is pending, active, terminal, or inconsistent; terminal
executions return an explicit terminal result with an empty processes array.
Do not extract a PID or PGID from execution get and pass it to process tree.
Selectors are pid:, name:, match: regular expressions, pgid:, port:
with optional /tcp or /udp, and all. A bare integer is a PID.
Structured queries combine process fields, regular expressions, socket ownership, and recorded apoc ownership:
The causal journal answers relationship questions from recorded evidence:
Process mutations accept caller-supplied idempotency keys. Repeating the same
normalized request and key returns the original receipt without another
operating-system call. Empty selections fail unless --allow-empty is explicit.
These commands can stop or suspend host processes. Resolve and inspect the selector before mutating a target when its identity is not already known.
Durable execution contract
execution is the public lifecycle abstraction. Direct argv is the default.
Place apoc options before the first literal --, then pass each exact child
argv value after it. That first separator belongs to apoc; every later --
belongs to the child. Structured MCP and Code Mode calls use the same arg
array. If apoc reports an unknown child flag, do not retry with --arg; move
apoc options before -- and the complete child argv after it. Use --shell
only when the program intentionally requires zsh parsing.
An execution records its versioned specification, working directory, repository and worktree state, attempts, exact process identities, output paths, parent, session, lease, progress time, and terminal result.
- An omitted working directory inherits the caller's current directory through the CLI, MCP, and Code Mode.
- A relative
--cwdresolves from that directory. apoc validates and canonicalizes it before accepting the execution. command,batch, andpipelinereturn a verdict, or{ execution, replayed, logs }at--verbosity trace.- The CLI exit status matches the managed result while structured stdout remains available to the caller.
- Inline stdout and stderr are bounded 32 KiB tails with explicit truncation
flags. Full logs remain available through
execution logs. - Launch failures, nonzero exits, timeouts, and cancellations are terminal execution results after acceptance. They are not transport failures.
- A progress timeout advances when retained stdout or stderr grows or the
execution lifecycle advances. If it stalls, apoc preserves
last_progress_atand records both that timestamp andstalled_atin the terminal result. - Reusing an idempotency key for a different normalized request fails before launching work.
Use execution list --error-code CODE to find executions by their canonical
terminal cause, including launch failures, timeouts, stalls, and cancellations.
Opt-in execution telemetry
Execution resource telemetry is off by default. Add --telemetry to execution command, start,
batch, pipeline, either poll target, or code run/start when a task needs
measurements. The default interval is 250 ms and the default retained raw-data
cap is 64 MiB; override them with --telemetry-interval-ms and
--telemetry-max-bytes.
One capture follows the selected execution, every recursively owned apoc child execution, and every live OS descendant of their stable process identities. A sample contains wall time, current and accumulated CPU, resident and virtual memory, disk reads and writes, and process count. It excludes command lines, environment values, and log contents. When the byte cap is reached, apoc removes the oldest complete samples and preserves stable sequence numbers for the newest ones.
Attach to work that is already running with a keyed mutation. get returns a
compact newest-and-peaks summary unless the caller addresses raw NDJSON lines:
Active captures resume after daemon recovery. A telemetry collection or storage
fault marks only the capture degraded; it never changes the execution verdict.
With telemetry disabled, apoc starts no sampler and writes no capture or sample
records.
Secret environment values use NAME=env:VARIABLE. apoc stores the reference
and resolves the value only when the process launches. Literal environment
values are part of the durable execution specification and are stored locally.
Local error tracking
apoc automatically records local error metadata in
<apoc state directory>/telemetry/errors.jsonl. On macOS the default is
~/Library/Application Support/apoc/telemetry/errors.jsonl; APOC_HOME selects
a different state directory. Nothing is uploaded.
The log covers CLI and parser failures, MCP tool errors, typed-command failures, daemon RPC faults, failed execution transitions, Code Mode errors, history storage failures, and Rust panics. Records contain a timestamp, build and execution-schema versions, OS and architecture, PID, operation, error code, available invocation and execution IDs, and a SHA-256 error fingerprint. Panic records also identify the source location. Arguments, environment values, purpose text, output logs, and raw error messages are excluded. Use the IDs to inspect existing durable history and execution records when the complete diagnostic is needed.
Each log retains at most 1 MiB and rotates to errors.previous.jsonl, keeping
at most 2 MiB across the pair. The directory is private (0700), and files are
0600. Recording is best effort: unavailable storage or a contended nonblocking
lock skips the event without changing a command's output, exit status, or
verdict. Set APOC_ERROR_TELEMETRY=off before launching apoc to disable it;
restart an existing daemon for that daemon to inherit the setting.
This error log is separate from the opt-in execution resource sampler described above. Successful executions and allowed nonzero exits do not generate execution-failure events.
Debug a managed Node execution
Use debugger run to launch Node as a durable execution and return its linked
debugger session in one typed call. apoc adds --inspect-brk=HOST:PORT when the
Node argv does not already declare an inspector option. Every other argument
remains exact argv.
Use debugger open when the target already exists. debugger targets returns
Node and page target identities, titles, URLs, and WebSocket endpoints.
Debugger source locations are one-based. Breakpoints use a source suffix and
survive script reloads because apoc sends Debugger.setBreakpointByUrl.
step accepts over, into, or out. continue waits for the next pause,
exit, or disconnect; resume returns the observed running state. Source,
scopes, variables, this, properties, prototypes, scripts, listeners, console,
exceptions, health, Chrome DevTools Protocol (CDP) trace, and durable event reads are separate typed
commands. Evaluation retains object IDs, unserializable values, descriptions,
and exception details. If a CLI object ID begins with -, put the positional
arguments after the first literal --.
Every debugger mutation requires an idempotency key. Sessions, actor-scoped
selection, breakpoints, hit counts, events, diagnostics, and replay receipts
are durable. On daemon restart, apoc reconnects an open Node session and
restores its breakpoints. debugger restart cancels and relaunches the linked
execution while preserving the session and breakpoint identities. debugger close disconnects CDP but does not cancel the linked execution; cancel that
execution explicitly when the program should stop.
Capture taps and expression watches
A tap is a conditional CDP logpoint that captures one JavaScript expression
without pausing the target. The source line is one-based. By default, apoc
escapes the source suffix into a URL regular expression; url_regex overrides
that match for bundles and generated scripts.
debugger_tap_list reports whether each tap resolved against a loaded script.
An unresolved tap remains pending and resolves when CDP reports its eventual
script location. debugger_tap_hits returns retained hits in chronological
order. Tap sentinel messages are routed into hit storage at the protocol-event
boundary and never enter user console, recorder after, timeline, or why
evidence. debugger_tap_remove disables the adapter breakpoint but preserves
its hit history.
An expression watch samples a running or paused JavaScript runtime every 250
milliseconds and stores only value or evaluation-error transitions. The target
is both its label and default expression; use expression when the label and
JavaScript differ. The access value records the evidence intent as read,
write, or rw.
debugger_watch_list, debugger_watch_hits, and debugger_watch_remove read,
inspect, and disable watches. apoc retains the newest 1,000 hits per tap or
watch while preserving total observed hit counts. Enabled taps and watch
workers restore when an open debugger session reconnects or restarts. Every add
or remove requires an idempotency key.
Control a browser page
Launch Chrome through execution start, discover its page target with
debugger targets, and attach it with debugger open --target-id. The session
view reports browser_cdp, the stable page target ID, and any linked execution.
The browser subgroup then uses that named durable session.
For headless automation, launch Chrome for Testing rather than branded Google
Chrome. Branded Chrome 153 quits --headless=new on its own about thirty
seconds after launch, with a clean exit and no message, which ends the debugger
session midway; the session error then reads Debugger connection closed: the connection failed: .... Chrome for Testing stays up. Install it with
npx @puppeteer/browsers install chrome@stable.
debugger browser navigate supports URL, reload, back, and forward. click
and type dispatch trusted input; select updates the element and dispatches
input and change events. DOM, computed styles, cookies, local and session
storage, performance metrics, network requests and bodies, WebSocket frames,
and page lifecycle events are addressed reads.
debugger browser screenshot stores a content-addressed PNG artifact. It can
capture the viewport, full page, or one selector; optional viewport overrides
and forced hover, active, focus, or visited state are restored before
the command returns. Inline base64 PNG bytes require --inline.
Mocks, device emulation, throttling, and JavaScript and CSS coverage are durable browser-session state. Mocks restore after daemon restart. Every navigation, interaction, capture, mock, emulation, throttling, and coverage command requires an idempotency key.
Record a browser session
Start a flight recording on an attached page session. apoc captures the current page immediately, captures later frame navigations, and resumes the capture worker when the daemon reconnects the session.
capture adds a reasoned manual frame. shoot is the deliberate-capture
variant. mark captures a frame and protects it with a named timeline mark.
captures and marks read one recording by its durable ID. replay restores
one retained capture URL and vertical scroll position. stop captures a final
frame and terminalizes the recording.
after captures current browser state and compares it with --at capture:ID
or --at mark:NAME; without --at, it uses the latest retained capture. The
durable result includes changed pixels and their bounding region, new console
entries, exceptions and failed requests, storage and computed-style changes,
new accessibility findings, performance changes, explicit probe warnings, and
a content-addressed self-contained HTML report. after-get reads one analysis
by ID, and afters lists analyses for a recording.
timeline joins captures, marks, console errors, exceptions, network failures,
after diffs, debugger events, invocation purposes, workspace commit and dirty
digests, executions, and correlated apoc causal events by epoch millisecond. It
returns bounded structured items and a content-addressed, self-contained HTML
filmstrip. Timeline trimming retains every mark, error, exception, and diff and
at least the newest item of every joined evidence kind. The report mutation
requires an idempotency key.
why selects the latest recorded error or exception, optionally restricted by
a case-insensitive substring, then ranks edits with explicit causal path
evidence, diffs, executions, and causal events inside a configurable lookback
window. Stack-file matches receive a deterministic boost. The result includes
the nearest mark, invocation purpose, commit, diff, and execution plus explicit
limitations when apoc did not record file-level edit or commit evidence.
The first, latest, and marked captures are protected from count and logical-byte
retention trimming. If those protected frames exceed a configured bound, status
reports retention_overflow instead of claiming that apoc discarded evidence.
Every recorder mutation requires an idempotency key.
Record and replay a browser flow
A flow records user actions while a browser flight recording is running. It preserves a stable selector and structural fallback for clicks, changed inputs, and selected key presses, plus scroll positions and top-level navigations. An active flow resumes after the daemon reconnects its browser session.
Perform the browser actions, then call debugger_flow_stop. debugger_flow_run
opens the recorded start URL and replays the ordered steps. Before each element
action, it waits until the primary selector or structural fallback is visible
and hit-testable. Every attempted step stores a browser capture. New console
errors or exceptions fail that step and skip the remaining steps. Starting with
the second run, each step reports its screenshot difference from the matching
step in the preceding run.
debugger_flow_list returns compact durable flow records.
debugger_flow_show returns one named flow with its ordered steps and prior run
evidence. Record, stop, and run are mutations and require idempotency keys. A
flow remains tied to its browser session and the active flight recording that
owns its captures.
Preserve and replay a debugger evidence trace
An evidence trace binds a named interval to an existing debugger session and its apoc-owned execution. If a browser flight recording is active when the trace starts, the trace also binds that recording. Starting a trace does not launch or own another process.
trace_stop closes the interval. trace_show joins debugger events, recording
captures and marks, after analyses, tap hits, watch transitions, and flow steps
into one bounded chronological timeline. trace_list returns compact durable
trace records.
trace_use selects a trace for the invoking actor. trace_replay selects the
latest item or an explicit KIND:ID anchor and restores a browser capture when
that item is replayable. trace_cursor reads the current anchor. trace_move
moves backward or forward through the timeline, optionally filtered by kind;
trace_jump moves to the previous or next item of a required kind. Unknown and
malformed anchors fail instead of silently selecting different evidence.
trace_export writes a versioned JSON bundle into apoc's content-addressed
artifact store. trace_import validates a bundle from an explicit path,
preserves its trace identity and items, marks it imported, and stores its exact
bytes in the receiving artifact store. trace_gc keeps the requested newest
terminal traces plus every active recording trace. All trace state mutations,
including cursor movement, require idempotency keys.
Record and replay an rr trace
rr_record launches rr as a durable apoc execution and passes the target as
exact argv. It defaults to the built-in isolated VZ backend on macOS and the
native backend elsewhere. Select either path explicitly with backend: "isolated"
or backend: "native"; isolated calls accept image: "local", an absolute
bundle path, or a canonical image digest. apoc owns the recording execution,
logs, lease, terminal verdict, export artifact, and resulting trace identity.
The local macOS image pins the software-counter rr fork at Git revision
c93b27695e2bed5ceec7770a568379452cbf55c5. The bundle verifier exposes that
revision as build.rr_software_counters_revision. Isolated recording uses rr's
-W -n software-counter mode because Apple Silicon VMs do not expose the
hardware performance counters required by upstream rr.
The CLI equivalent places apoc options before the first literal separator and the exact target argv after it:
After a successful isolated recording, the provider exports the workspace-bound trace as a digest-verified execution artifact. apoc copies it into the debugger CAS, materializes a sandbox-readable replay copy, and removes the uniquely named temporary workspace directory. Native recording uses the same final artifact and materialized trace contract. apoc does not infer success from a directory alone: if the managed execution reaches no successful verdict, the trace fails and no partial directory is promoted as a replay artifact.
rr_replay starts interactive rr replay as a durable PTY execution. Use its
execution ID with execution_attach, execution_input, execution_signal, and
execution_cancel; replay does not introduce a second lifecycle. Event, process
ID, and end-of-trace selection map to rr -g, -p, and -e. rr_ps runs rr
process inspection as a one-shot durable execution and returns its bounded
logs.
rr_import accepts an explicit rr trace directory without requiring rr to be
installed on the importing host. It archives without following symlinks,
validates extraction through the tar reader, normalizes replay permissions, and
stores both the CAS artifact and an apoc-owned materialized directory. rr_list
and rr_show return the
durable trace, execution, replay, artifact, failure, and timestamp links. Only
rr-backed traces claim instruction-level replay; debugger evidence traces do
not.
Every call is an assertion
Agent context is the scarcest resource in an execution loop, so an execution answers with a verdict and nothing else. Silence is safe because the caller declares what a correct result looks like before the command runs.
That is the entire response, for a success and a failure alike. outcome uses
the JUnit and TAP vocabulary:
outcome |
Meaning |
|---|---|
passed |
Exited zero and any declared expectation held |
failed |
The assertion did not hold: a nonzero exit, or a missed expectation |
error |
A fault reached no verdict: launch failure, stall, or cancellation |
skipped |
Declared but never launched |
pending |
Durably owned and not yet terminal |
- Expectations are the predicates a poll already evaluates:
--expect-exit-code,--expect-stdout-regex,--expect-stderr-regex,--expect-json-pointerwith--expect-json-equals, and--expect-js. A poll evaluates one repeatedly; a command evaluates it once. - The CLI exit status mirrors the verdict, so a shell caller needs no payload at all. A missed expectation exits nonzero even when the program exited zero.
- The expectation is stored in the durable spec, so invocation history records what each call asserted, not merely what it ran.
- A batch or pipeline has no single output to assert against, so every declared
command carries its own
expect. A child whose assertion did not hold fails that child and its parent, even when the program exited zero.
Reveal output progressively
Output is never returned unless it is asked for. Search the durable log, then expand around what you find:
Matching runs inside the daemon, so a 500 KB log is never shipped to a caller
that wants one line. Every slice reports total_matches, stdout_lines, and
stderr_lines, so a caller always knows how much it has not read.
Verbosity
--verbosity off|error|warn|info|debug|trace, following syslog and tracing.
The default is error, the verdict above. -v reaches info (status, exit
code, withheld sizes, follow-up reads) and -vv reaches debug (bounded log
tails); each of those only adds to the level below it. -q lowers the level, and
off returns no payload at all.
trace is the exception to that ladder: it answers with the complete durable
record rather than the verdict envelope, so a typed consumer addresses the record
by the JSON Pointer it already uses. It still carries outcome, so no level
costs you the verdict.
APOC_VERBOSITY sets a session default and reaches nested Code Mode calls
through the invoking process. --view outcome|full and APOC_VIEW remain as
deprecated aliases, each keeping the contract it named: outcome is the
collapsed verdict, full is the complete record.
execution logs, attach, tree, and poll iterations always return their own
detail because they are the drill-down. Poll conditions and recipe output
validation always evaluate the complete record, so their pointers, regexes, and
schemas address every field.
Poll commands and typed apoc operations
Use poll run when one observation must be repeated until it matches or reaches
a bound. Use poll start to return the durable parent execution immediately.
Both forms use the existing execution get, wait, and cancel lifecycle.
Poll options are named arguments and have no ordering requirement before --.
The separator preserves exact command argv. Interval behavior uses these request
arguments; it does not use interval subcommands.
--interval-mode |
Arguments | Behavior |
|---|---|---|
fixed-delay |
--interval-ms |
Wait after each unmatched observation. |
backoff |
--initial-interval-ms, --multiplier, --max-interval-ms |
Increase the delay to the cap. |
fixed-rate |
--interval-ms |
Use acceptance-based ticks, skip missed ticks, and never overlap. |
Conditions include repeated --until-exit-code, stdout or stderr regex,
--until-json-pointer with --until-json-equals, and a pure boolean
--until-js expression over observation. Select one condition family. A poll
without a condition must include --max-iterations or --duration-ms and
completes as bounded sampling. A condition that reaches a bound fails with
POLL_CONDITION_NOT_MET.
Poll the shared typed graph with apoc as the target. This does not spawn a
nested apoc CLI process:
The parent result stays compact. Expand only the evidence needed for diagnosis:
Run independent commands concurrently
Use one batch when the agent already knows the independent commands. apoc bounds
concurrency, records each child, and returns a compact failure-oriented parent.
max_parallel defaults to the logical CPU count and is limited to 256.
CLI callers may pass --commands once with a JSON array, or repeat it with one
JSON command object per occurrence. Use --file commands.json for larger or
reusable definitions. MCP and Code Mode pass the structured array directly.
Use a pipeline only when stdout must flow between stages. apoc creates native pipes, starts every stage before waiting, keeps each child's stderr separate, captures final stdout on the parent, and enables pipefail by default.
Compose heterogeneous work in Code Mode
Code Mode runs generated JavaScript in isolated QuickJS actors. The worker pool
defaults to min(logical CPUs, 8); set APOC_CODE_WORKERS to override it.
Separate programs use separate actors, and one program can issue independent
host calls concurrently with Promise.all.
Use the typed apoc.wait({ ms, purpose }) host call for a short delay when no
observable poll condition exists. It is capped at 60,000 milliseconds and does
not start a managed process; JavaScript setTimeout is not part of the QuickJS
contract.
Code Mode persists source, immutable capabilities, ordered calls, replay state, result, events, and oversized artifacts. Provider mutations record intent before dispatch. Replay skips operations that already have a durable applied receipt.
Do not fan out shell strings that each invoke apoc through a host tool's
Promise.all. Use one execution batch for known commands or one Code Mode
program with typed apoc.* calls. Avoid concatenating large source trees with
cat; use targeted searches, bounded reads, or a compact Code Mode synthesis.
After apoc accepts a managed execution, an unsuccessful terminal status resolves
normally inside JavaScript. Inspect execution.status and throw explicitly when
the surrounding program must fail.
If an outer Code Mode execution ends before its accepted child work is summarized, recover the direct children without replaying the whole program:
The parent filter returns direct children only and composes with status and
cursor pagination. Use execution_get or execution_logs only for selected
IDs. Provider-action receipts are separate from command lifecycle records, so
receipt_get is not a command recovery API.
The local executor's 300-second limit measures uninterrupted JavaScript. It is
renewed immediately before and after every host tool call, so connector and
managed-command wait time does not consume the runaway-loop budget. The outer
code run --timeout-ms value controls how long that client waits; accepted work
remains durable. A runaway loop fails with CODE_EXECUTION_TIMEOUT.
Coordinate agents and resources
A session groups one agent's executions under a heartbeat. Its root lease is
session/SESSION_ID. When the heartbeat expires, the daemon releases the lease,
cancels session-owned executions, and releases their reservations.
Reservations provide atomic apoc-local ownership for ports, paths, exact
processes, devices, and custom keys. Port reservations also report native socket
conflicts. reservation wait waits for up to 30 seconds.
Extend the capability graph
Providers add Streamable HTTP MCP, supervised MCP stdio, or OpenAPI operations
to the same graph. Their names become Code Mode namespaces. Secret configuration
uses PROVIDER:REFERENCE and resolves only when a client connects or a child
starts.
From an unpacked apoc source package, build and sign the native Rust VZ provider and build the verified Linux arm64 VM bundle. Isolated execution resolves the provider internally and does not require registration.
build-provider.sh builds apoc-macos-vz, signs it, and verifies the
com.apple.security.virtualization entitlement. Run it whenever Cargo replaces
the provider binary; an unsigned provider cannot start a virtual machine.
action run and action start use the durable Code Mode lifecycle. Calls with
the same stable resource identity are ordered. Independent resources can run
concurrently. Every mutation stores an intent followed by an applied, failed, or
unknown receipt.
The packaged native macOS VZ provider contains the Rust provider, Linux guest, versioned wire protocol, build scripts, and signing entitlement. The image format is verified in Rust without starting the daemon, provider, or a VM.
Use apoc through MCP
The built-in command graph serves MCP stdio with apoc --mcp. Register the
absolute installed path so the agent host does not depend on shell startup
configuration:
APOC_BIN=
The MCP, CLI, and Code Mode surfaces share command schemas, execution state, idempotency behavior, and output contracts.
apoc --mcp serves the five Code Mode lifecycle tools — codemode_search,
codemode_execute, codemode_execution, codemode_decide, codemode_cancel —
and nothing else. The surface stays five tools however many commands apoc grows
and however many MCP servers you configure, so adding either never costs the
model another tool schema.
A program reaches apoc's own commands under apoc.*, and every MCP server already
configured on this machine, each under its own namespace: servers registered with Claude
Code, Codex, Cursor, VS Code, Copilot, Amp, Gemini, Windsurf or OpenCode are discovered
without anything to switch on. A namespace is named without being contacted and connects
on its first call, so a server that is slow, unreachable or removed costs nothing until a
program uses it, and cannot fail an execution that never names it. One
program can therefore read a repository, ask a downstream server about it, and
join both in JavaScript without returning to the model in between; only what it
returns crosses back.
apoc mcp check reports what was discovered without starting anything, and names the
reason a namespace is empty — an unsupported transport, a placeholder only a person can
supply, a rejected credential. apoc mcp refresh is the one command that contacts
servers and caches their schemas.
Two consequences worth knowing. The administrative command groups — daemon,
code, profile, env, recipe, recording, receipt, capability, action,
provider, connector, skill, mcp, decider — are reachable from the CLI but not from a
program, because each either cannot run safely from inside an execution or is a
human-at-a-terminal operation. And codemode_decide always reports that there is
nothing to decide: apoc runs every tool without pausing.
Embed apoc in a Rust program
The same core the daemon runs can live inside another Rust process, with no
daemon and no socket. It answers the daemon's own requests by method name, and
Code Mode programs it runs reach apoc.* in-process.
use json;
Apoc blocks the calling thread and owns its own runtime; from async code, use
apoc::CoreHandle::open(apoc::CoreConfig::new(path)).await instead. Calling the
blocking API inside an async runtime returns BLOCKING_FROM_ASYNC rather than
deadlocking.
An embedded core owns its state root exclusively. Opening a root that another
core or the per-user daemon already owns fails with STATE_ROOT_BUSY, because
two owners would cancel each other's work. To work with the daemon's state,
talk to the daemon.
No daemon does not mean no threads. An open core runs process monitors, a maintenance loop for hooks and lease expiry, and a pool of JavaScript workers, and commands it starts keep running under their own budgets after a call returns.
Configure isolated profiles
Profiles are exclusive durable environments. A command selects one explicit
--profile, otherwise the longest matching canonical workspace root, otherwise
the nearest canonical cwd ancestor whose directory name exactly matches an
existing profile, otherwise the per-user default. Durable root mappings take
precedence over directory-name recognition. An explicit profile that disagrees
with either workspace selection fails instead of merging credentials. apoc never
creates a profile from a directory name; with no existing match and no default,
it runs without a profile. Secret values remain unresolved references and
resolve only when apoc constructs a process or provider transport.
# From /work/personal/project, cwd recognition now selects personal automatically.
# Use an explicit root mapping when the directory name differs from the profile.
Each accepted execution pins the selected profile generation for its complete
child graph. Profile-controlled names are removed from daemon inheritance before
that generation is applied, and explicit command or command-unit overrides are
rejected. env list, env doctor, and profile show never return literal
values or secret references. The deprecated env --global form targets the
current default profile and creates legacy-default only when a compatible
mutation needs one. Every profile and environment mutation requires an
--idempotency-key.
Search invocation history
apoc records each typed CLI, MCP, and Code Mode invocation in its local SQLite
database. Queries are local by default: every directory in one Git worktree
shares a scope, while a directory outside Git has its own exact canonical scope.
Use --global only when the task needs history from every recorded workspace.
Normalized arguments and options are stored and searchable. Secret-bearing
fields keep only their destination names; values, providers, and references are
removed before normalized input, search text, and pattern signatures are
written. Literal environment and header values remain recordable, so use
structured secret options for credentials.
list and search return bounded reverse-chronological pages with
invocations and next_cursor. They accept exact filters for source,
surface, command, status, actor, linked execution, and error-code,
plus since-ms and until-ms. --global and --cwd cannot be combined. A local query does
not include imported records whose original working directory is unknown.
timeline returns complete sanitized records oldest-first. Its opaque cursor
holds a stable acceptance snapshot, so calls accepted after the first page do
not appear later in the same traversal. The default limit is 100 and the
maximum is 500.
history query runs one read-only SQL statement against an isolated in-memory
history table, never against apoc's durable database. The table exposes
id, purpose, started_at, updated_at, status, command_path, source,
surface, actor, execution_id, and error_code for filtering and ordering,
but results may contain only id and purpose. The CLI returns compact
columns plus positional rows, defaults to 20 rows, and hard-caps at 100 even
when the SQL asks for more. Use history get ID only after a purpose identifies
something worth expanding.
Native capture is automatic and does not call DevSQL. Historical shell and agent transcripts can contain literal credentials, so inspect their retention and access before importing them. The following explicit command runs DevSQL once, imports only shell segments that invoke apoc, redacts recognized secret flags, preserves source provenance, and skips records already imported:
Imported records have source: "devsql". Ordinary capture and every later
history query remain independent of DevSQL.
React to typed apoc calls
Hooks run Code Mode JavaScript after an exact typed command starts, succeeds, or
fails. Configure the dotted method identity shown by Code Mode, such as
execution.command; apoc normalizes the command graph's display path before
matching. A hook is local to the current worktree or canonical directory unless
you pass --global. A local hook shadows a global hook with the same name, while
differently named hooks stack.
The hook program receives a frozen hook object. hook.delivery contains
id, hook, generation, phase, attempt, and max_attempts;
hook.invocation is the source invocation snapshot with normalized input and
terminal status when applicable. Use hook.delivery.id in nested mutation
idempotency keys so a daemon-interrupted attempt can replay safely.
When invocation history reaches a configured lifecycle transition, matching
deliveries are persisted and run asynchronously in the daemon. Hook success or failure never
changes the source call's verdict. Failed programs retry with bounded exponential
backoff and become durably failed after max_attempts. Daemon recovery returns
interrupted deliveries to pending. Calls made by a hook carry hook depth and do
not create more hook deliveries, preventing accidental recursion. Each attempt
also emits hook.delivery.started and hook.delivery.result causal events.
Use hook get, list, remove, delivery, and deliveries to manage and
inspect definitions and outcomes. At least one of --on-start, --on-success,
or --on-failure is required.
Ask a decider before commands run
A decider is a Code Mode program you register. Before apoc launches a command,
it runs every enabled decider that covers the command's verb, with a frozen
intent describing the launch in scope, and waits for
{decision: "allow" | "refuse" | "pending", reason}. Any refusal stops the
launch, which fails with INTENT_REFUSED and the decider's own reason.
--on-unavailable is required: you decide whether a decider that times out,
fails, or returns something malformed lets the command through or refuses it.
Such an intent is recorded as unchecked, never as ruled. The decider group is
available on the CLI but not inside Code Mode programs.
What is checked today is every command launch: execution command and
start, each batch child and pipeline stage, poll command iterations, and
commands run from Code Mode programs, hooks, and recipes. Not yet checked:
process signals and stops, calls into MCP servers and providers, isolated and
provider-backed executions, and debugger sessions.
What an intent can and cannot tell a decider:
- Its targets are only what apoc itself resolved: for a command, the executable
on the path it will launch. apoc does not parse arguments, so
rm -rf $TMPDIR/xnames/bin/rmand nothing else. - A shell string is not analysable:
analysableis false and its only target isopaque:.analysable: truemeans apoc did not have to give up on the request's form, not that it understood the effect. - A decider's own commands are not offered back to deciders.
pendingcurrently refuses; nothing yet holds a command open until someone answers.
intent list records an entry only when at least one decider was asked.
Build a temporary command namespace
Use recipes when repeated commands should become a small composable interface
without creating a standalone binary. Dotted names form the namespace. A recipe
is local to the current Git worktree, or the exact current directory outside
Git, unless you pass --global. Local definitions shadow global definitions
with the same name.
apoc resolves the complete declared dependency graph before execution. Missing,
expired, cyclic, deeper-than-16, and larger-than-64 graphs fail before Code Mode
runs. The resolved functions execute inside one Code Mode program. Draft
2020-12 input and output schemas validate the top-level recipe boundary. Repeat
--require-env NAME on recipe put when a recipe must fail before Code Mode if
a literal or secret value cannot resolve. Portable bundles include required key
names, never values or references.
The caller LLM can propose a recipe from exact chronological evidence without making it executable. apoc stores the candidate and rationale; it does not run an embedded model or infer candidates with built-in heuristics.
Suggestions remain separate from lookup, dependency resolution, execution
tools, and bundles. Adoption atomically creates the exact candidate and links
the suggestion. The default adopted lifetime is 604800000 ms (7 days); pass a
positive --ttl-ms to override it. A different existing generation is a
conflict unless you pass --replace.
Expired recipes remain durable but are hidden and cannot run. recipe pin
clears one expiry, and recipe prune deletes expired recipes in the selected
scope. Both commands require --idempotency-key.
recipe export writes RecipeBundleV1 and includes transitive dependencies.
The bundle excludes scope, expiry, timestamps, receipts, and resolved secrets.
recipe import validates the whole bundle before one atomic database write and
rejects conflicts unless you pass --replace.
Record ordinary work into a command
Use recordings when the work that should become a recipe is work you are about to do anyway. Bracket it, run apoc normally, and stop with the name it should take. apoc transcribes the captured invocations into one Code Mode program and writes it into the recipe namespace described above.
A recording is local to the current Git worktree, or the exact current directory
outside Git, unless you pass --global. One recording is active per scope at a
time. Every typed invocation in that scope joins the recording, reads included,
except the recording commands themselves and the nested host calls inside a
code run program, which would otherwise emit twice.
Transcription is exact. Each call site is the recorded command_path and its
stored normalized input, so execution command becomes apoc.execution_command.
Options left unset or left at their declared default are omitted, because
omitting them resolves to the same value when the recipe runs. apoc does not run
an embedded model and does not invent steps.
Three sources decide which recorded literals become recipe inputs. Earlier sources win.
| Source | Declared by | Result |
|---|---|---|
| Explicit holder | recording param NAME=VALUE |
Required input, substituted wherever that exact value appears. |
| Take difference | A second recording start with the same name |
Required input for every path whose value changed between takes. |
| Recorded variation | The same normalizer behind history patterns |
Optional input that falls back to the recorded literal. |
recording param compares values as JSON strings; pass --json when the holder
should match an exact number, array, or object. recording literal '$.timeout_ms'
forces one step-relative path to stay literal in every step.
Recorded idempotency keys never become literals. Each one is rebuilt from a
single required runKey input, so rerunning a recipe performs real work instead
of replaying the original receipts. Recorded secret references are redacted in
history and cannot be transcribed, so each redacted destination becomes a
required input holding its PROVIDER:REFERENCE.
Read recording status before stopping to see the exact ordered call sites, then
repeat --skip INVOCATION_ID on recording stop to drop the ones that were
incidental. Adding a take requires the same call sequence; a different length or
a different command at the same position fails with RECORDING_TAKES_DIVERGED
and writes nothing.
Stop with --suggest instead of a plain stop when the candidate should stay
non-executable. That path stores a recipe suggestion with each take as
positive evidence and leaves adoption to recipe adopt. It requires at least two
takes, matching the evidence rule for suggestions.
Recorded parallelism is emitted sequentially. A recording captures the order
calls were accepted, not their concurrency, so rewrite the emitted body with
Promise.all through recipe put when the steps are independent.
Inspect events and state
apoc appends monotonically ordered lifecycle events. Repeated large payloads are content-addressed and deduplicated; event metadata remains after payload pruning.
Commands that need durable ownership automatically start one detached daemon per user.
| State | Default macOS path |
|---|---|
| Database | ~/Library/Application Support/apoc/apoc.sqlite3 |
| Execution logs | ~/Library/Application Support/apoc/runs/ |
| Daemon log | ~/Library/Application Support/apoc/daemon.log |
| Socket | $TMPDIR/apoc-<effective-user-id>/apoc.sock |
Ordinary consumer work uses the installed per-user controller without setting
APOC_HOME or APOC_RUNTIME_DIR. Set both only for apoc tests and integration
fixtures, or for an explicitly bounded isolation task. Return to the default
controller after a temporary compatibility workaround is no longer needed;
never carry a dated temporary runtime into later ordinary work.
Set both APOC_HOME and APOC_RUNTIME_DIR to run a bounded isolated instance. apoc
backs up a non-empty database before each schema migration. The runtime directory
uses mode 0700; the Unix socket uses mode 0600. $TMPDIR represents the
platform temporary directory returned to the process and is commonly under
/var/folders/.../T on macOS. <effective-user-id> is the numeric effective
user ID returned by the operating system.
Cleanup
The daemon runs one cleanup pass every 10 minutes. apoc gc runs the same pass
on demand. Without --apply it only reports counts and a sample of up to 10 IDs
per category.
- Orphans. apoc closes a running execution when its process identity (boot ID,
PID, and start time) is gone and no supervisor owns it. The run becomes
interrupted. The execution becomesfailedwithEXECUTION_INTERRUPTEDand the cause. It is never markedcompleted, and nothing is signaled. A Code Mode program that no actor owns any longer is closed the same way. First, its execution-owned children are canceled. Work whose owning execution finished or vanished, or whose session closed or expired, is canceled withEXECUTION_OWNER_GONE. Cancellation goes through typed cancellation, which re-verifies process identity before it sends a signal. The check skips work touched within the lastAPOC_GC_ORPHAN_GRACE_MS(default 60000). - Unowned background work.
execution startwith no parent and no session gets a lifetime of 24 hours (APOC_GC_UNOWNED_LIFETIME_MS). The clock restarts on every get, tree, wait, attach, input, signal, or log read. Set--lifetime-ms Nto change it, or--keep-aliveto opt out.APOC_GC_UNOWNED=report(the default) lists expired work.stopcancels it through typed cancellation withEXECUTION_EXPIRED.offskips the check. - History retention. apoc deletes terminal executions older than
APOC_GC_RETENTION_DAYS(default 30;0disables) in batches of 200. Deletion includes their events, unpinned payloads, process events, leases, invocation records, search rows, observation versions, and run logs. It also deletes older terminal invocation records and process events that belong to no execution. To keep an execution, its children, and its invocations, label it--label apoc.keep=true. Recording invocations are always kept. - Space. New databases use incremental auto-vacuum, so deleted pages go back
to the operating system. An older database reuses its free pages and keeps its
file size. apoc never runs a full
VACUUMon its own.
A daemon with a non-default APOC_HOME or APOC_RUNTIME_DIR exits once it has
had no connected client and no nonterminal work for APOC_DAEMON_IDLE_EXIT_MS
(default 1800000; 0 disables). It also exits soon after its APOC_HOME is
deleted. The default per-user daemon never exits on its own.
APOC_GC_INTERVAL_MS sets the pass period, and 0 disables the periodic pass.
apoc daemon status reports gc with the last pass's counts and pending
counts.
Upgrade and verify
The next durable command starts the current daemon build. apoc version reports
the client version and public execution schema. apoc daemon status reports the
daemon build and schema when it is running.
Reference
There is no public issue tracker or support channel. The structured CLI help, JSON Schemas, embedded operator skill, and packaged source are the public product contract.
License
apoc is available under the MIT License.