minimal agent cli memoria.tools
README.md

Headless execution (WP3) #

execution dispatches the WP2 reducer through actual threads with injected provider/tool/store services. WP4 provides real native/process services and registered tools for callers; WP8 adds actual OpenRouter composition in a separate opt-in headless root. WP9 adds explicit private-store/headless workflow composition. WP11 now connects an opt-in plain-text frontend without any old src integration. Default/status/login commands remain diagnostic; explicit --chat --accept-network owns interactive execution and durable sessions.

Lifecycle and owner entrypoints #

  • init/destroy own a Runtime's agent and canonical conversation. Empty and repeated teardown remain safe. destroy asserts that no executor is attached.
  • step(runtime, input, instructions, definitions, limits) remains the immediate borrowed-output reducer API for an unattached runtime. It does not dispatch.
  • init_executor(executor, runtime, config, sink, allocator) attaches one owner to an initialized idle session with an empty queue and no unrecovered Active records. It requires adapter, clocks, root issuer/mutex and (for Durable) Store.save. It clones run-frozen instructions and registry definitions/procedures; model-visible definitions come from that same frozen registry. Partial setup failure releases acquired allocations and does not attach the runtime.
  • send borrows host Submit/Set_Selection/Suspend/Cancel/Retry_Save input and returns conversation.Error. Worker/checkpoint completions cannot be injected here. Event_Sink consumes reducer events before actions are cloned/dispatched. Sink events are callback-borrowed; clone if retaining them.
  • poll(executor, wait=false) drains one owned ordered event or joins one released worker and applies its terminal. Nonblocking polling suits a future frontend; wait=true is for headless loops/shutdown, not interactive input.
  • close stops admission/selection changes, suspends dequeue, commits cancellation, clears pending prompts, drains/joins, then saves the latest idle revision if needed. It returns false for unsaved history and never automatically retries. Explicit Retry_Save remains available after failed close; it cannot replay an effect. The host must map failed close to an unsaved warning/nonzero exit status.
  • After close, call destroy_executor, then destroy(runtime), then destroy root services/allocators. Destruction with retained jobs asserts. Repeated empty executor destruction and repeated close are safe.

Executor/runtime addresses must remain stable. send, poll and close check the creating thread and refuse callback reentry. Direct step while attached also refuses, so sinks cannot bypass this guard. Job/clone helpers are internal machinery, not alternate owner entrypoints. Only the owner mutates conversation/agent state.

Concurrency and ownership #

WP12b root selection binding supplies agent.next_protocol/next_capabilities and enforce_capabilities, separately from Services.model (the next adapter). At dequeue the reducer freezes active protocol/capabilities; before publishing Turn_Started, executor freezes active_model. Model jobs copy that active binding, including every follow-up after tools/checkpoints. Root registry/variant/adapter data is immutable and must outlive jobs. Active protocol/capabilities do not change when UI changes next selection. Tools are omitted and incompatible tool/reasoning callbacks rejected when captured capabilities disallow them. Legacy headless compositions without capability enforcement retain their explicit fixed State.protocol. Canonical request/tool selection and provenance-safe continuation projection are unchanged.

One dedicated worker per runtime executes provider, tool or save; there is no shared finite pool. Tools remain sequential. One not-yet-started owned checkpoint snapshot may wait behind a save; newer gates replace/destroy that pending snapshot. Saves cannot overlap or finish out of dispatch order within a runtime. Root services must support isolated runs across runtimes; WP17 owns child capacity/cancellation.

Workers retain no runtime, mutable conversation, registry, root issuer or frontend pointer. Model jobs own the complete projected request: message/content strings and slices, provenance, identity/selection, compacted context, instructions and definitions. Tool jobs own call/identity/selection, definition strings, workspace and native/process service ID/description strings; they copy procedure tables/capabilities and computed deadline/output budget. WP4 also passes the root clock callback/data to tool workers so deadline checks share the issuer's coordinate. Clock callback/data must be worker-safe, remain alive until join, and support concurrent parent/child reads. Captured selection is exposed as tool.Context.selection (the WP3 shared-contract addition). Save jobs own a full cloned session plus the entire checkpoint key, and verify the requested revision equals snapshot revision before starting.

Adapter/tool/store opaque data and backend service data remain borrowed root lifetime, never destroyed here. Registry data/procedures cannot be retired while workers can invoke them. Backends must validate the native/process procedures they need; nil never grants permission. WP4 implements these validations and operations.

The executor allocator must be thread-safe, long-lived and freeable from owner and worker threads (Odin's tracked test allocator is thread-safe). Thread creation and worker context.allocator are explicit; core:thread manages the default thread-local temporary allocator. Callback payloads crossing the mailbox are cloned before callback return and destroyed after transition even if stale/duplicate/rejected. Foreign callback identities are rejected while still borrowed, before allocation/protocol state changes; already-owned stale mailbox envelopes are still destroyed. Returned tool results/store errors use the provided output allocator and standard destruction APIs. Partial clones release exactly once; joined jobs reclaim snapshots/envelopes.

Services.identity_mutex is a root-owned mutex shared with identities by every root/child owner. Immediate step locks it when supplied; executors require it. Restored-ID observation and transition issuance share a critical section. The issuer never resets on teardown. A mutex-free immediate driver is valid only with a single serialized root owner, as in WP2.

Frozen budgets and reliable paths #

Resource Enforced limit
Frozen instructions 64 KiB valid UTF-8
Frozen registry 128 definitions; 1 MiB allocation-work quota including arrays/strings
Provider/tool/save snapshot 32 MiB allocation-work quota including structural arrays
Ordered mailbox 64 items; 4 MiB owned allocation-work charges
Callback envelope 4 MiB quota; progress text <=64 KiB
Result/diagnostic allocator 128 KiB allocation-work quota
Returned tool text / safe diagnostic 64 KiB; excess is infrastructure/checkpoint failure
Tool deadline injected monotonic now +120s default; explicit positive timeout <=120s

Budget charges successful Alloc/Resize sizes, not just visible text. Frees do not refund this per-owner work quota; it stops a clone before oversized allocation. Fixed Job/Envelope/thread structs are bounded separately by counts. At most one producer-local and one consumer-local envelope (each <=4 MiB), one active and one pending snapshot exist. A just-joined snapshot may briefly remain while the next is built; total job snapshots remain at most two. Canonical history, reducer projection and backend-private scratch are separate owners with their own ticket budgets. No silent history trimming is performed. Allocation refusal from the tool/store output allocator fails infrastructure/checkpoint even if an injected implementation incorrectly returns success after that refusal.

The fixed terminal/control area is independent of mailbox capacity. Scoped cancellation sets a mutex-protected flag and wakes blocked publishers; new output/progress is discarded only after cancellation/protocol failure. Ordered accepted output is never silently dropped normally. Optional progress may be omitted on resource refusal. Oversized/malformed provider payloads fail the request and signal cancellation rather than complete an incomplete response.

A provider terminal callback is retained but not applied until Adapter.run returns and its thread actually joins. Missing/duplicate terminal events fail visibly. Late usage/ served-model metadata before return is retained in fixed bounded fields; snapshot/delta counters normalize without duplicate addition, including after cancellation with a full mailbox. Final metadata applies before terminal finalization. No new text/calls/reasoning is allowed after terminal. Tool terminal results (including late completed effects after cancel) and save outcomes also wait for join.

Checkpoints and remaining boundaries #

Keys match unique ID/session/revision/reason/policy. Durable acknowledgements follow an actual successful injected Store.save. WP3 unit tests use an owned memory fake; WP9 tests/headlessstore exercises actual disk durability. Volatile deliberately skips store I/O and is never labeled Durable. Superseded results still release snapshots. Save failure blocks work; retry saves the latest revision under a fresh key without replay/follow-up. Idle shutdown uses a fresh Shutdown key after workers drain; failure blocks save-only recovery without revising a previously durable completed turn. Explicit Retry_Save can recover this case too; no failed-save loop occurs.

Serialization here is per runtime, not writer authority across runtimes/processes. WP9's concrete backend now owns the bounded codec, durable commit, revision conflicts, writer locks, load/list/resume and compaction storage protocol. WP5/WP6 own transport/ parser budgets and cancellation; H08-H09 pre-output retry/backoff remains pending. This executor runs adapters/tools once and never retries them. Clocks are injected: monotonic durations stay process-local; wall time persists. Tool rounds remain zero/unlimited unless explicitly capped.

Cancellation is cooperative: adapters/tools must observe checks and finish cleanup; store saves must return. A hung backend can keep close waiting. Never forcibly free/terminate its data. WP4/WP5/WP9 own concrete deadline enforcement; WP10/WP11 own signals/terminal restoration/interactive shutdown; WP17 owns child cancellation trees. Full C09/C10 product startup/shutdown and F01-F24 are not claimed.

Evidence #

executor_test.odin and ownership_test.odin run actual threads with scripted fake adapter/ registry/store and injected clocks: no frontend imports, network, files, sleeps or credentials. They cover sequential effects, save failure/retry, item/byte backpressure, cancellation, truthful late effects, terminal-before-return, stale ownership, late usage, queue/suspension/ selection capture, serial superseded saves, owner/reentry guards, concurrent root issuance, 100-turn cleanup, setup/thread failures and nested allocation-failure sweeps. Validation command/counts: WP3 ticket. The validation runner treats tracked leaks/bad frees as test failures, not warnings.

WP8 actual-provider composition boundary #

Actual OpenRouter adapter now composes through the existing Services.model and worker snapshot/mailbox APIs; no executor/reducer retry handshake was changed. Instruction snapshot and restricted native fixture definitions freeze before admission. Opt-in root intentionally retains explicit Volatile acknowledgements; it does not bind the separate WP9 backend. It retains root-owned HTTP/auth/adapter/fixture data through cancel/drain/join. H08-H09 retry attempt coordinator remains deliberately required/pending: fail-fast once per request, no hidden adapter/codec/HTTP retries or effect replay. Real localhost acceptance evidence: tests/headlessopenrouter; no live auth or full subagent tree.

WP9 real-store integration (2026-10-08) #

sessionstore.adapter(lease) now supplies actual private durable persistence to the existing immutable worker jobs/full gate ID/session/revision/reason/policy acknowledgements. Store callbacks remain backward-compatible with fake adapters. Real native-effect tests live in tests/headlessstore: all save reasons, stale superseded gates, failure-before-tool/after-effect, cancellation, orderly close and explicit persistence retry without replay. Two minimal runtime corrections refuse nil-model submissions before admission on unavailable selection resume, and retain post-rename Durability even when diagnostic allocation is refused. Neither adds a reducer or an implicit retry. Root/lease allocators and services outlive joins; store scratch uses its own bounded root allocator, not the small diagnostic budget.

WP9 review regression (2026-10-08), app/sessions_test.odin: an attached idle executor survives switch's current-checkpoint Write/Directory_Sync failure. The public app retry API dispatches an exact-revision Durable Retry_Save job, joins its ack back to Idle without model/effects, then switches its borrowed adapter to a new lease. Orderly Shutdown saves the new session and preserves the old snapshot. Root services remain alive through teardown; no further executor API change.