Neuron is a runtime for building and operating complex software systems from composable, executable capabilities. This document is the architecture reference for the whole platform: the canonical model every authoring surface converges on, the boundaries that must never blur, and — in depth — how N.O.R.E. turns a registered assembly into running capabilities.
Note
N.O.R.E. (Neuron Operational Runtime Engine) is the internal name of the project runtime. Using Neuron — authoring, building, running, and inspecting assemblies — never requires knowing this name; the user-facing guides and the CLI describe it as the project runtime. It is named here only because this document is the architecture reference.
Tip
Reading paths:
- New to Neuron — The core idea, The canonical pipeline, What lives where.
- Authoring an assembly — Assembly definition, Authoring surfaces, Building & loading.
- Understanding the runtime — N.O.R.E. at a glance, The execution model, Executing one capability, Waiting and signals.
- Implementing or hosting capability runtimes — The capability runtime contract, The process runtime, The WASM runtime.
Modern software is composed of applications, services, workers, libraries, queues, databases, APIs, and infrastructure. As systems grow, the hard part stops being any individual component and becomes making all of them work together as one coherent system.
Neuron's answer is to stop making the runtime understand what a component is and instead make it understand what a component does — and how it connects. Everything executable is a capability: described by a contract, reached through a relationship, and operated by a runtime that does not need to know how it is implemented.
Important
Software should be composed from things that can do something, connected by explicit relationships, and operated by a runtime that does not need to understand what those things are.
This leads to a deliberately small set of primitives:
| Primitive | Responsibility | What it never knows |
|---|---|---|
| Assembly | Defines what exists and how it is connected | How capabilities are implemented |
| Module | An executable capability packaged for Neuron | The composition it belongs to |
| Capability | Exposes one executable capability | How the capability is executed |
| Capability Runtime | Provides the machinery that runs a Capability | The composition of the Assembly |
| Binding | Defines how two capabilities communicate | The business meaning of the data |
| Instance | A living realization of an Assembly | Implementation details of its Capabilities |
| N.O.R.E. | Operates registered Assemblies — instantiate, schedule, execute | What any capability actually means |
The separation between Capability and Capability Runtime is the load-bearing wall. It is what lets Neuron host capabilities implemented in any technology without turning the core into a collection of special cases: the Capability stays logical, the Capability Runtime stays mechanical, and the runtime only ever sees the capability runtime boundary.
In priority order:
- Correctness — behavior is defined, bounded, and tested at the right boundary.
- Architectural integrity — one authoritative place for every important domain behavior, no competing models.
- Isolation — source languages never leak into the runtime; the runtime never parses author input.
- Security — external capability runtimes are untrusted code and are hosted accordingly.
- Performance — concurrency and worker reuse are first-class, measured, not assumed.
- Scalability — the primitive model composes from one service to distributed systems.
- Maintainability — packages own a single responsibility and are named after it.
- Clear public APIs — the SDK, the capability runtime protocol, and the CLI are contracts.
- Testability — behavior is exercised through stable boundaries.
- Documentation — intent and constraints are explained where they matter.
All authoring surfaces converge on one canonical representation before anything language-, runtime-, or technology-specific happens:
flowchart TB
A[Source language<br/>YAML · TypeScript · future] --> B[Language-specific loader]
B --> C[Canonical assembly manifest]
C --> D[Validation]
D --> E[Compiler]
E --> F[Core assembly]
F --> G[Execution plan]
G --> H[Runtime<br/>N.O.R.E.]
Nothing downstream of the canonical manifest knows how an assembly was authored. YAML assemblies and TypeScript assemblies produce the same manifest, compile through the same compiler, and run on the same runtime.
The repository is a monorepo organized into strictly separated Go modules:
| Path | Responsibility |
|---|---|
application/ |
The neuron CLI — authoring, building, module resolution, client, daemon bootstrap |
nore/ |
N.O.R.E. — the Neuron Operational Runtime Engine |
shared/ |
Canonical types, capability runtime contract, version — agreed on by both Go modules |
packages/assembly-sdks/typescript/ |
@neuronruntime/sdk — TypeScript assembly-definition language |
packages/executor-sdks/golang/ |
Go SDK for authoring Neuron modules (capability runtimes) |
packages/executor-sdks/dotnet/ |
.NET SDK for authoring Neuron modules (Neuron.Executor) |
examples/ |
Runnable example assemblies and reference capability runtimes |
docs/ |
Getting started, architecture, installation, and module docs |
scripts/ |
Workspace development and release helpers |
The important fact: application and nore are separate Go modules that only agree through the canonical types and protocol contracts in shared. The CLI never reaches into the runtime's internals; the runtime never reads YAML or TypeScript.
flowchart LR
subgraph app["application module"]
CLI[neuron CLI]
BLD[builders<br/>yaml · typescript]
end
subgraph sh["shared module"]
CAN[canonical types]
PRO[capability runtime protocol]
VER[version]
end
subgraph nore["nore module"]
NOR[N.O.R.E.]
end
CLI -. reads canonical .-> CAN
BLD -. emits canonical .-> CAN
NOR -. consumes canonical .-> CAN
NOR -. implements .-> PRO
The version reported by neuron version and nore --version comes from a single source, shared/version, stamped at build time via -ldflags.
An Assembly is a composition of capabilities and the explicit relationships between them. The canonical YAML form mirrors the manifest structure in examples/ecommerce_order:
# assemblies/order-processing/assembly.yaml
apiVersion: neuron/v1
kind: Assembly
metadata:
name: order-processing
version: 1.0.0
description: Order processing pipeline
capabilities:
- ref: validate-order
entry: ../../capabilities/validate-order.yaml
- ref: parse-order
entry: ../../capabilities/parse-order.yaml
bindings:
- from: validate-order
to: parse-order
mappings:
- target: validation_data
expression: "source.result"
validations:
- expression: "source.result.valid == true"
message: "Order validation failed"A Capability names the logical unit and the capability runtime that provides it:
# capabilities/validate-order.yaml
apiVersion: neuron/v1
kind: Capability
metadata:
name: validate-order
version: 1.0.0
description: Validate incoming order request
spec:
capability runtime:
type: neuron:core:set
runtimeConfig:
execution:
mode: wait
timeout: 5s
config:
status: validated
valid: true
mappings:
- direction: input
source: execution.params.order
target: orderruntimeConfig declares how N.O.R.E. should drive the capability through its capability runtime — execution mode, timeout, retry behavior, and reserved resource constraints. It is grouped deliberately (execution, retry, resources), is per capability, and is never capability input. Every field is optional; N.O.R.E. supplies its own defaults for anything unset.
Execution flows along the bindings. Each binding declares what data flows between the two capabilities (mappings) and optionally which conditions must hold (validations). A mapping source names a structured reference — the upstream capability's result (source.result.<path>), the execution params (execution.params.<path>), a literal, or a project variable — which the loader parses into the canonical structured form. validations remain CEL expressions evaluated over source.result and execution.params.
The YAML surface is the canonical, zero-tooling authoring experience. A project is a directory with neuron.config.yaml pointing at a kind: Assembly entry file (assembly.yaml by default). The project configuration owns the Assembly identity (name and version) as well as the authoring language, entry file, and runtime defaults — identity is settled in project configuration before the source is canonicalized. neuron init scaffolds it, and neuron build consumes it. See examples/ecommerce_order for a complete project.
The TypeScript SDK (@neuronruntime/sdk) is the same capability: a typed, always-autocompleted way to describe assemblies in TypeScript, converging on the same canonical manifest.
// assembly.ts
import { Capability, Assembly } from "@neuronruntime/sdk";
const validate = Capability("validate-order")
.runtime({ name: "neuron:core:set" })
.paramsSchema<{ order: object }>()
.resultSchema<{ order: object; valid: boolean }>();
// The Assembly authors no identity: neuron.config.* owns name/version and
// `neuron build` injects them into the canonical manifest.
export default Assembly()
.paramsSchema<{ order: object }>()
.withParams((data) => validate.withParams({ order: data.order }))
.toManifest();The SDK is a definition tool. It describes assemblies; it does not execute them, and it must never become a runtime. The Go side remains responsible for parsing, validating, compiling, and running the canonical representation. See packages/assembly-sdks/typescript/README.md.
Each authoring surface has a dedicated loader in application (application/build/yaml, application/build/typescript). A loader's only job is to translate its source language into the canonical manifest — plus project-level concerns (paths, variables, entry points).
The pipeline in neuron build:
flowchart TB
A[project<br/>neuron.config.*] --> B[loader<br/>per authoring language]
B --> C[canonical manifest<br/>.neuron/manifest.json]
C --> D[validator]
D --> E[compiler<br/>core.Assembly]
E --> F[capability runtime resolution + freezing]
F --> G[N.O.R.E. registration<br/>POST /v1/register]
The validator and compiler are language-agnostic: they consume and emit canonical structures. YAML-specific quirks stay inside the YAML loader; TypeScript-specific quirks stay inside the TS loader.
Before canonicalization, the loader reads the project configuration (neuron.config.*): authoring language, entry file, project variables, and the Assembly identity (name / version, required for build). The project configuration is strict — unknown keys and engine plumbing (daemon.*, storage.*, capabilityRuntimes.storeDir) are rejected from project files.
The TypeScript loader delegates the actual build to the SDK CLI (neuron-sdk build --path <root> --entry <file>), which executes the entry module and writes .neuron/manifest.json — then the same canonical path continues. The entry file is selected the same way for both authors: the project's neuron.config.* entry field.
The compiler transforms the canonical manifest into the runtime/core structures N.O.R.E. consumes.
Warning
The compiler MUST remain source-language agnostic. It MUST NOT parse YAML or TypeScript, resolve GitHub repositories, download or install capability runtimes, launch processes, execute capabilities, own HTTP clients, or contain registry-specific behavior.
Those responsibilities belong to their own layers. The compiler is pure transformation: canonical manifest in, core assembly out.
A module is the public word for a capability packaged for Neuron. Within the model, a capability runtime is distilled through a chain of distinct responsibilities:
flowchart TB
A[Capability Runtime Requirement<br/>who + what version constraint] --> B[Capability Runtime Registry<br/>where packages are obtained]
B --> C[Capability Runtime Resolver<br/>which version satisfies the requirement]
C --> D[Capability Runtime Package<br/>immutable, self-describing artifact set]
D --> E[Verification<br/>cryptographic checks]
E --> F[Capability Runtime Installation<br/>install the selected artifact securely]
F --> G[Capability Runtime Store<br/>where the immutable artifact lives]
G --> H[Capability Runtime<br/>process · wasm · future]
H --> I[Capability Runtime Instance<br/>a live running realization]
No two steps merge:
| Step | Answers | Owns |
|---|---|---|
| Registry | Where | Providers (github, local, future registries) |
| Resolver | Which | Best version by semantic versioning, above the providers; prefers already-installed artifacts so running instances stay independent of the network |
| Installer | How | Verifying and installing the selected package archive |
| Store | Where it lives | The immutable installed artifact, keyed by name and exact version, under ~/.neuron/capabilityRuntimes |
| Runtime | How it executes | Spawning, supervising, and terminating capability runtime workers |
The CLI runs this pipeline during neuron build and then freezes the exact resolved versions into the build record. N.O.R.E. therefore never resolves modules itself — it receives a closed set of resolved capability runtimes and launches instances from them.
Built-in modules are the exception that proves the rule: they run in-process inside N.O.R.E., so resolution skips them and the runtime dispatches them directly. See docs/MODULES.md for the full model.
N.O.R.E. (Neuron Operational Runtime Engine) is the daemon that registers assemblies, creates instances, executes them, and persists their records. It is the operating environment of an assembly: it owns processes, memory, communication, isolation, resources, and scheduling — one level above what a capability runtime owns for itself.
| Concern | Responsibility |
|---|---|
| Registration | Receiving compiled Assembly definitions from the CLI and persisting them |
| Execution planning | Compiling the registered assembly and its frozen capability runtime set into a plan over an event bus |
| Instances | Creating, running, pausing, restarting, and removing living realizations of Assemblies |
| Capability runtimes | Hosting and supervising modules — in-process for built-ins, out-of-process for external modules (process and WASM providers) |
| Scheduling | Advancing executions, evaluating binding mappings and validations, handling cancellations |
| Persistence | Durable storage of registered assemblies, instances, executions, and events through the storage.Store contract. SQLite is the default driver; storage.provider (or --storage-driver / NEURON_STORAGE_PROVIDER) selects another registered driver |
| API | The local HTTP/JSON transport over which the CLI talks to the runtime |
N.O.R.E. deliberately does not:
- parse YAML or TypeScript,
- resolve or install external modules (the CLI does that and freezes the result),
- understand the business meaning of the modules it operates.
The canonical manifest is compiled by the CLI; N.O.R.E. receives the compiled core assembly representation.
| Backend | Backup | Restore |
|---|---|---|
| SQLite | Offline copy of the database file (<path>/nore.db) while N.O.R.E. is stopped. Optionally checkpoint the WAL before copying to produce a consistent single-file snapshot: sqlite3 <db> "PRAGMA wal_checkpoint(TRUNCATE)". |
Place the backup file at the target path and start N.O.R.E. The SQLite driver will open the database and apply any pending WAL migrations automatically. |
| PostgreSQL | pg_dump -Fc <dsn> > nore.backup.dump while N.O.R.E. is stopped. This produces a custom-format dump that preserves schemas, data, and ownership. |
pg_restore -d <dsn> nore.backup.dump. The target database must have the same or compatible schema version. |
Neuron uses schema version tracking via a schema_migrations table to determine whether the stored schema is compatible with the running binary. The table location per backend:
| Backend | schema_migrations table |
|---|---|
| SQLite | sqlite_master catalog row where name = 'schema_migrations' (or the dedicated table created by the migration framework). Records store the applied migration version. |
| PostgreSQL | schema_migrations table (created by the migration framework) with columns version BIGINT PRIMARY KEY, description TEXT, applied_at TIMESTAMPTZ, dirty BOOLEAN. |
Upgrade steps from a previous SQLite schema:
- Ensure N.O.R.E. is stopped — do not attempt an online migration.
- Run the migration framework against the existing SQLite database to bring it to the current schema version. The
migrate.Migratefunction applies pending migrations in order, recording each inschema_migrations. - Verify the
schema_migrationstable reflects the target version. For SQLite, query:SELECT * FROM schema_migrations ORDER BY version DESC LIMIT 1; - Start N.O.R.E. The binary will refuse to start if the schema version is newer than this binary understands (see
ErrNewerSchemainnore/internal/storage/migrate). If the schema is exactly at the current version, N.O.R.E. will start normally. - If the previous schema is ahead of this binary's supported maximum, the startup will fail with a precise error naming the current maximum supported version. In that case, apply compatible migrations backward (or forward via an intermediate binary) before restarting.
The storage configuration remains machine-level, not project-configured. It is set via storage.driver (or NEURON_STORAGE_DRIVER / --storage-driver CLI flag) at deployment time and is rejected from project configuration files so an assembly never embeds database settings.
In this phase, no indexed query operations were added behind the neutral storage.Store interface. The PostgreSQL backend includes an index on the key column of the kv_store table (CREATE INDEX IF NOT EXISTS idx_kv_store_key ON kv_store (key)) to accelerate List(prefix) lookups, but this was added without formal measurement of performance impact or extension of the neutral backend interface. The decision is recorded here for future optimization if measurement confirms indexed queries are needed. The SQLite backend performs full table scans via LIKE prefix matching, which is acceptable for the expected workloads in this phase.
Users requiring optimized prefix listings for large datasets should consider the PostgreSQL backend or add custom query methods outside the neutral contract in a later phase.
flowchart TB
subgraph nore
cmd[cmd/nore<br/>daemon entrypoint]
api[api<br/>HTTP/JSON API]
inst[instance<br/>lifecycle manager]
exec[execution<br/>state machine · scheduler · engine]
ev[event<br/>event bus · durable log]
rt[provider<br/>capability runtime host]
pl[planner<br/>assembly → execution plan]
rv[resolver<br/>CEL expressions]
st[storage<br/>contract + driver registry]
sys[assembly<br/>registered assembly repository]
plugin[plugin<br/>frozen records → adapters]
end
cmd --> api
api --> inst
api --> sys
inst --> exec
exec --> ev
exec --> rt
exec --> pl
rt --> plugin
exec --> rv
ev --> st
inst --> st
| Package | Responsibility |
|---|---|
cmd/nore |
Daemon entry point — flags, listeners, token, shutdown |
api |
HTTP/JSON API — transport only: validates requests, calls the instance manager and assembly repository, serializes responses and streams. Never interprets assembly semantics |
instance |
Lifecycle — create/remove/clear, restoration on startup, registry of live instances |
execution |
State machine — scheduler transitions, snapshotting, wait-for-completion, the capability runtime engine that drives module calls, and the execution store (in-memory, write-through to storage) |
event |
Single source of truth for state transitions; the durable event log used for persistence and streaming |
mechanism |
Provider registry — one provider contract, multiple first-party providers (process workers, WASM), with health checks, worker pooling, restart, and cancellation |
planner |
Compiles the registered Assembly + frozen capability runtimes into an executable plan. Source-language agnostic; owns no HTTP clients, registries, or file downloads |
resolver |
CEL expression resolver — binding mappings and validations |
storage |
Backend-neutral Store contract, sentinel errors, key construction, driver registry, and transactions. Concrete drivers live under storage/<driver> and are imported only by the composition root |
plugin |
Boundary between frozen capability runtime records and the providers — thin adapters, no process/socket/WASM machinery itself |
assembly |
Registered assembly repository and indexing |
The runtime boundary inside N.O.R.E. is the capability runtime abstraction. One contract, multiple first-party providers:
flowchart TB
ER[Capability Runtime] --> PROC[Process Runtime]
ER --> WASM[WASM Runtime]
ER -. planned .-> CONT[Container Runtime]
ER -. planned .-> REM[Remote Runtime]
PROC -->|neuron/capability-runtime-v1 · gRPC over Unix socket| W[long-lived worker processes]
WASM -->|neuron/capability-runtime-v1-json · stdio| MOD[wasm32-wasi modules]
A provider owns starting the capability runtime, connecting to it, health checking, executing requests, cancellation, deadlines, termination, and restart. The registry, installer, and compiler own none of that.
N.O.R.E. is the runtime process. The neuron CLI starts it for you; direct operation is not required for normal use. It runs in two modes:
- Project runtime — the normal mode, started by bare
neuronfor the current project (nore --project). It binds loopback TCP (runtime.host, defaultlocalhost;runtime.port, default auto) and writes a discovery record under<project>/.neuron/runtime/, so later CLI commands andneuron runfind the same endpoint. - Standalone daemon — started without a project. It binds a Unix domain socket (
~/.neuron/nore.sock, mode0600) by default and uses~/.neuron/noreas its data directory. Flows that run outside a project context (for exampleneuron buildregistration) use this mode.
A TCP listener refuses to start without an API token; local clients obtain the token from the socket's token file when possible. The process runs in the foreground and shuts down cleanly on SIGINT/SIGTERM.
| Endpoint | Operation |
|---|---|
GET /health |
Health check (used by the CLI bootstrap) |
POST /v1/register |
Register a compiled Assembly |
POST /v1/run?assembly=<selector> |
Run an Assembly synchronously and return its result |
GET /v1/instances |
List Instances |
POST /v1/instances |
Create an Instance and begin execution |
DELETE /v1/instances |
Remove all Instances |
GET /v1/instances/{id} |
Instance detail |
DELETE /v1/instances/{id} |
Remove an Instance |
POST /v1/instances/{id}/executions |
Create an execution |
GET /v1/instances/{id}/executions |
List executions |
GET /v1/instances/{id}/executions/{execID} |
Execution state |
GET /v1/instances/{id}/executions/{execID}/events |
List events |
GET /v1/instances/{id}/executions/{execID}/events/stream |
Stream events (Server-Sent Events) |
WS /v1/ws |
WebSocket endpoint for live event streaming |
Everything the runtime knows about a capability runtime is defined in shared/types/capabilityruntime. This module is the contract both sides compile against. It is deliberately dependency-free and carries no registry, resolver, or installer machinery.
Three pieces matter.
Describes one immutable artifact: its name and version, its runtime kind, its entrypoint, its declared protocol, its capabilities, and its per-platform artifacts.
{
"apiVersion": "neuron/v1",
"kind": "CapabilityRuntime",
"metadata": { "name": "my:capability", "version": "1.2.0" },
"runtime": { "type": "process", "entrypoint": "capability", "protocol": "neuron/capability-runtime-v1" },
"capabilities": ["capability"],
"features": [],
"platforms": { "linux-amd64": { "artifact": "capability-linux-amd64", "sha256": "..." } }
}runtime.type selects the provider (process or wasm); the protocol selects the transport; maxWorkers (optional) bounds the worker pool for process capability runtimes. Validation requires a correct apiVersion and kind, a name, a version, a runtime type, an entrypoint, and at least one capability.
platforms keys are selected by the runtime kind: process capability runtimes bind the host's native key (linux-amd64, …) because the artifact runs on the N.O.R.E. machine, while WASM capability runtimes bind the portable wasm32-wasi key. The mapping lives in one place, PlatformForRuntime (application/capabilityruntime/model.go). The preferred distribution unit is the capability runtime package archive (<name>-<version>-capability-runtime.neuron.tar.gz) carrying runtime.json plus every platform artifact; registries prefer it over per-platform assets and the installer reconciles its inner manifest against the resolved identity.
Manifests declare the protocol honestly:
- a gRPC-capable process capability runtime declares
neuron/capability-runtime-v1; - a WASI module or legacy command declares
neuron/capability-runtime-v1-json.
Defines the wire data model of an execution: a Request with a Params map, and a Response with a Result map and an optional Error string. An additive v1 extension adds an optional resume input to the request and an optional suspend outcome to the response; absent fields preserve the original wire shape. Two transports carry this data:
| Protocol | Transport | Used by |
|---|---|---|
neuron/capability-runtime-v1 |
gRPC (protobuf) over a Unix domain socket | Process capability runtimes (canonical) |
neuron/capability-runtime-v1-json |
One-shot line-delimited JSON over stdio | WASI modules and legacy process capability runtimes |
The gRPC surface is CapabilityRuntimeService in shared/protocol/capabilityruntime/v1/capability_runtime.proto, with Initialize, Execute, Health, and Shutdown RPCs. It carries the handshake, protocol version, identity, capabilities, structured input/output/errors, cancellation, deadlines, and health.
Suspend is opt-in and additive. A capability runtime must advertise suspend in InitializeResponse.features before it may return a suspend outcome; a client that did not negotiate the feature rejects the outcome explicitly instead of treating the response as an empty success. An executor may request only signal or timer waits — deadline is an engine-internal policy and is rejected in an executor-supplied suspend. Suspend is not a stackful continuation: a later fresh Execute carries the same logical operation ID, a new attempt ID, and a resume input, so the capability must reconstruct its state from the params and deduplicate on the logical operation ID together with the delivery ID (the client-supplied idempotency key), never on the attempt ID, which is new on every resume or retry. Both transports validate untrusted suspend and resume metadata at the boundary before it reaches the execution domain. Neuron ships executor SDKs for Go and .NET only; there is no TypeScript executor SDK. See Waiting and signals.
Note
A non-empty Error in a response is a controlled failure, even when the process exits zero.
Two Go interfaces define how a provider hosts an artifact:
type Provider interface {
Descriptor() Descriptor
Start(ctx context.Context, spec Spec) (Instance, error)
Close(ctx context.Context) error
}
type Instance interface {
Execute(ctx context.Context, req *Request) (*Response, error)
Health(ctx context.Context) error
Close(ctx context.Context) error
}Spec carries everything needed to launch one artifact: the capability runtime type and version, the runtime kind, the declared protocol, the entrypoint, the install root, and an optional worker-pool bound. Descriptor carries identity and the compatibility requirements. The returned Instance is the uniform execution handle — regardless of whether the underlying capability runtime is a child process or a WASM module.
A provider is the host or engine that runs a Capability Runtime artifact — the process provider runs one as an OS child process, the WASM provider runs one as a wasm32-wasi module. The provider contract is separate from the Capability Runtime invocation protocol: a provider launches and supervises an artifact and passes Request/Response through unchanged, so it can never redefine what params, result, lifecycle, or structured errors mean.
The contract lives in shared/types/provider (the two Go modules agree on it there) and is deliberately not a public control-plane API. It declares:
Descriptor— provider identity and compatibility: name, provider version, provider contract version, the runtime kinds it hosts, the Capability Runtime invocation protocols it speaks, and the platforms it runs on;Spec— what to launch, derived from a frozenResolvedCapabilityRuntime(a provider never resolves, downloads, or installs anything);Provider—Descriptor,Start, and a process-globalClose;Instance—Execute,Health,Close;- a typed
provider.Errorthat normalizes a missing provider, an unsupported runtime kind, an unsupported protocol, a platform mismatch, an incompatible provider contract version, and an unavailable provider.
A single registry (nore/internal/mechanism.Registry) owns the providers and the instances they launch. Providers register the kinds they declare:
reg := mechanism.New()
reg.Register(process.New(logger)) // declares the "process" kind
reg.Register(wasmRuntime) // declares the "wasm" kindStart(spec) selects the provider for spec.RuntimeKind and evaluates compatibility in one place (Select): the provider must implement this contract version and must match the runtime kind, the Capability Runtime protocol, and the platform. An incompatible or unknown kind fails with a typed provider.Error naming exactly what was not met — a frozen artifact that declares an unsupported or unknown runtime type is never silently mis-executed.
SupportedRuntimeKinds() in shared/types/capabilityruntime lists the two kinds a first-party provider hosts: process and wasm. The container and remote kinds are reserved for the future and currently have no provider.
The registry does not track launched instances. Whether two launches share one underlying runtime is the provider's decision and each provider shares differently: the process provider keeps one refcounted worker pool per capability runtime, the WASM provider keeps its compiled modules and sandbox engine on the provider itself, and the legacy JSON transport holds nothing between executions. Close releases what a provider holds for the whole process, once at shutdown.
In the running process there is a single shared registry, built lazily and shared by every instance (nore/internal/plugin.sharedRuntimes):
- the WASM provider owns process-global compiled-module state that every WASM adapter must share;
- the process provider tracks its worker pools by capability runtime identity, so two instances of the same assembly legitimately share one pool per capability runtime.
Providers are themselves installed artifacts. They are obtained with neuron install --provider <name>@<version>, which resolves, verifies, and installs one from the configured registries into the machine-global provider store (~/.neuron/providers, laid out as <name>/<version>/<digest>/). For local development, neuron provider build bootstraps descriptor-only first-party process and wasm provider artifacts into the same store, marked with source: bootstrap provenance. The provider contract itself never resolves, downloads, or installs anything — obtaining a provider is a CLI concern. See Provider installation for the artifact comparison.
There are two ways a capability type gets a capability runtime.
Core in-process capability runtimes. N.O.R.E. ships built-ins for common operations. They run inside the N.O.R.E. process and require nothing to be installed, resolved, or launched:
| Capability type | Behavior |
|---|---|
neuron:core:set |
Materializes a capability's value set (configuration with params overlaid) |
neuron:core:http |
Performs an HTTP request with SSRF protection, host allowlist, and retry policy |
neuron:core:command |
Runs a local program with cwd confinement, env allowlist, and process-group termination |
neuron:core:filesystem |
Reads files and lists directories, confined to the project root and extra roots |
They are registered by RegisterCoreRuntimes in nore/internal/registry, under both the canonical namespaced name (neuron:core:set, …) and the legacy bare name.
External capability runtimes. Anything else is hosted by a provider. An external capability runtime is an installed artifact (a native binary or a WASM module) that speaks one of the two declared wire protocols. External capability runtimes are declared as requirements in an assembly, resolved to exact versions at register time, frozen into the deployment as ResolvedCapabilityRuntime records, and launched by the matching provider when the assembly becomes an instance.
The distinction is decided in nore/internal/plugin.RegisterResolvedCapabilityRuntimes: a frozen capability runtime is only registered if no core capability runtime already exists for the same capability type. Core capability runtimes always win.
nore/internal/plugin is the boundary between frozen capability runtime records and the providers. It owns no process, socket, or WASM machinery itself. It only maps a ResolvedCapabilityRuntime onto the contract N.O.R.E.'s capability runtime engine consumes.
NewAdapter reads the frozen record's runtime kind and builds a provider.Spec:
- an empty runtime kind defaults to
process(the original capability runtime model); - an empty protocol defaults to
neuron/capability-runtime-v1-jsonso legacy capability runtimes that omit the declaration keep speaking JSON; - the entrypoint is resolved to an absolute path via
EntrypointPath(); maxWorkersfrom the frozen record is passed through.
It then calls the shared registry's Start(kind, spec). The returned instance is wrapped in an adapter that maps the engine's ExecutionContext to a Request and back, and turns a non-empty response error into a Go error.
An Assembly definition is static. An Instance is a living realization with its own state. Instances are created from a registered assembly, and each creation plans and runs the assembly across its capabilities:
flowchart LR
A[register assembly] --> B[create instance]
B --> C[plan execution]
C --> D[schedule over event bus]
D --> E[execute capabilities through capability runtimes]
E --> F[terminal execution state]
F --> G[events streamed over WebSocket · SSE fallback]
Register. neuron build builds the project, compiles it to an assembly, resolves every capability runtime requirement against the configured catalogs, installs what is missing, and freezes the exact resolutions into the deployment. The deployment never resolves or installs again. Frozen records are ResolvedCapabilityRuntime values: type, requested constraint, exact resolved version, registry, digest, runtime info, and the absolute install root.
Instance creation. An instance of the assembly is created on demand through Manager.GetOrCreate (nore/internal/instance). The manager reads the durable registered assembly, decodes the frozen capability runtime set from the opaque ExecutionConfigurations payload, and constructs the instance. Construction:
- builds the event bus, execution store, scheduler, capability runtime engine, and analytics,
- registers the core in-process capability runtimes,
- registers a runtime adapter for every frozen external capability runtime (
plugin.RegisterResolvedCapabilityRuntimes), and - compiles the blueprint for the assembly.
Start. Instance.Start sets the status to running and launches five concurrent loops: analytics, scheduler, capability runtime engine, event persistence, and either execution persistence (non-durable modes) or the durable-only due-timer and deadline poll loop (durable mode). Until this point nothing is listening.
Stop. Instance.Stop cancels the instance context, waits for in-flight work to drain, closes the capability runtime registry (which closes every registered adapter, releasing runtime-backed resources), and persists the stopped status.
Warning
Instances survive runtime restarts as metadata-only records: on startup, N.O.R.E. restores persisted instances and their executions so they stay queryable, but a restored instance has no runtime and cannot be started. Creating a new instance is how work is re-run.
On SIGINT/SIGTERM, N.O.R.E. closes its listeners and then gracefully stops all live instances before exiting (srv.StopInstances()), so capability-runtime-backed resources — worker processes and WASM modules — receive a clean shutdown instead of being torn down mid-operation by process exit. In-flight executions are flushed to storage before storage is closed.
N.O.R.E. treats every capability as a capability runtime. An execution is always a request/response operation at its core: input → execution → output (with stderr, status, and structured errors alongside). The runtime itself does not know what a capability does. It only knows the contract every capability runtime speaks: a params map in, a result map (or a structured error) out. Whatever the capability is — a database query, an HTTP call, a WASM module, a native binary, a remote API — the runtime sees the same shape.
Important
One Assembly can mix capabilities executed in completely different ways. This is a core property of N.O.R.E.: the Assembly composes capabilities; the runtime hosts them; the capability runtime contract keeps those two independent.
When an execution flows through the assembly, a capability's capability runtime is resolved from the registry (core capability runtime or adapter) and invoked with an ExecutionContext: the execution and correlation IDs, the capability definition, the resolved params, the capability's effective runtime configuration, and a logger bound to the execution.
The ExecutionContext keeps two things rigorously apart:
| Field | Owned by | Reaches the capability runtime? |
|---|---|---|
Params, CapabilityConfigurations |
the author's declaration | Yes — this is capability input |
RuntimeConfig |
N.O.R.E. | No — it tells the engine how to drive the invocation |
A runtimeConfig is resolved from the capability's runtime declaration, not from its input. The planner fills in N.O.R.E.'s defaults once, when the plan is built, so the engine always sees a complete configuration and no per-invocation defaulting cost is paid. The registered assembly keeps the configuration exactly as authored; defaults live on the plan and never mutate it. As a result, changing a default never rewrites a deployed assembly and never changes an assembly's identity hash — only what the author explicitly declares is frozen into the hash.
The engine enforces what the plan carries at the invocation boundary:
execution.mode: waitawaits the result before continuing the plan. It is the default.execution.mode: detachsplits the plan at that capability: the capability and everything downstream of it become a separately tracked child execution (parent_execution_id) that may outlive the caller, while the parent continues. The split is compiled once, when the plan is built, so detaching costs no graph work at runtime. A detached task runs under a bounded drain window during shutdown (--detached-drain-timeout, default30s), and is markeddetachedin the parent rather thancompleted, because its work lives elsewhere.execution.timeoutbounds the whole invocation, including every retry attempt and the backoff between them — so an exponential backoff cannot keep a capability alive past the deadline its author declared.retryretries every failure with fixed or exponential backoff, except shutdown cancellation and an already-exhausted deadline. Neuron has no capability-level error taxonomy, so it does not guess which failures are transient; each scheduled re-attempt emitscapability.retry.resourcesis a reserved group with no fields. No provider enforces resource constraints yet, so any key under it is rejected when the declaration is decoded rather than silently ignored — an option is never accepted unless it is actually honored.
The capability runtime returns the result map. Errors from the capability runtime are distinguished:
| Case | Meaning |
|---|---|
| Go error from the adapter | Real failure (Execute RPC failed, worker died, process crashed, timeout) |
| Empty error + response | Success; response carries the result |
Non-empty response Error |
Controlled failure surfaced downstream without the transport failing |
Note
Execution history and events are an observability and persistence concern, not part of the execution semantics: an execution does not depend on persistence being enabled.
N.O.R.E. provides an at-least-once dispatch guarantee for capable work. When an execution plan advances to a capability, the engine records a dispatch intent — a unit of ready work persisted to the store so that a process restart or crash does not lose track of which capabilities remain to be executed. The dispatch intent is the core mechanism that makes at-least-once possible.
Each dispatch intent carries an owner field and a lease_expires_at timestamp. The claiming workflow uses a compare-and-swap (CAS) pattern within a storage transaction:
- Read the dispatch intent from the store.
- Check claimability: the intent is claimable if it has no owner, or if its lease has expired (
LeaseExpiresAtis before now). An intent held by a live owner is ineligible for re-claim. - Write a new owner and lease expiry (
now + leaseDuration) atomically via compare-and-swap. The CAS ensures that if two callers read the same intent concurrently, only one wins the claim — the other observes a conflict and retries or declines. - Release: when an owner finishes with an intent,
ReleaseDispatchIntentclears the owner, making the intent claimable again. A release that mismatches the current owner is a no-op, preventing a stale worker from reclaiming work already re-claimed by another owner.
This CAS+lease pattern guarantees that at any moment, at most one owner claims a given dispatch intent, but if that owner crashes or its lease expires, the intent becomes claimable again — ensuring no ready work is permanently lost.
Because the runtime guarantees at-least-once dispatch — not exactly-once — an external capability runtime must design its handlers to be idempotent. If a capability is re-dispatched after a crash or network partition, the same params may be delivered again; the runtime does not deduplicate externally visible effects. The capability runtime author is responsible for ensuring that repeated execution with the same inputs produces the same result or safely merges duplicates.
The at-least-once guarantee covers dispatch lifecycle — recording, claiming, and re-dispatching ready work. It does not guarantee exactly-once execution of external side effects (e.g., writing to a database, sending a network request). Those are the responsibility of the capability runtime implementation. The runtime may record events and persist execution state, but durable execution resumption does not claim exactly-once semantics for the capability's business logic.
flowchart TB
A[Execution plan advances to capability] --> B[Engine records dispatch intent]
B --> C[Dispatch intent persisted with owner + lease]
C --> D[Worker claims intent via CAS+lease]
D -->|lease expires or owner crashes| E[intent becomes claimable again]
E --> F[Another worker claims the same intent]
F --> G[Capability executed again (idempotent handler required)]
sequenceDiagram
participant C as API client
participant IM as Instance Manager
participant S as Scheduler
participant EB as Event Bus
participant EX as Capability Runtime Engine
participant RT as Capability Runtime
C->>IM: POST /v1/instances
IM->>S: create execution
S->>EB: emit execution.started
loop over capabilities via bindings
S->>EX: evaluate mappings + validations (CEL)
EX->>RT: Execute(request)
RT-->>EX: Response
EX-->>S: capability outcome
S->>EB: emit capability.completed
end
S->>EB: emit execution.completed
EB-->>C: streamed events
Every transition emits an event — execution.started, capability.ready, capability.started, capability.completed, capability.failed, capability.log, and a terminal execution.completed, execution.failed, or execution.cancelled. Events are streamed to clients and persisted according to storage policy.
stateDiagram-v2
[*] --> Started: instance created
Started --> Scheduling: execution plan ready
Scheduling --> Running: capability dispatched
Running --> Running: next capability
Running --> Completed: terminal success
Running --> Failed: transport or controlled error
Running --> Cancelled: cancellation requested
Completed --> [*]
Failed --> [*]
Cancelled --> [*]
Executions honor deadlines and support cancellation. A capability may also enter a wait instead of completing: the execution is then waiting, is excluded from in-flight worker accounting, and can remain non-terminal until a signal or timer resumes it.
A capability that fails fails the whole execution. There is no continue-on-error, no per-capability retry budget that spans siblings, and no partial result: the execution ends in Failed with the failing capability's message as the reason.
This is deliberate, and it is the single most consequential behavior in the engine, so it is worth stating plainly rather than leaving it to be inferred from the state diagram:
- Downstream capabilities never start. The plan stops advancing at the failure.
- Capabilities already running are stopped. The scheduler releases the execution's scope, so in-flight siblings see their context cancelled rather than being left to finish. This is recorded as
cancelled, notfailed— see Cancellation for why that distinction matters. A sibling stopped because another capability failed did not itself break, and reporting it as broken would send whoever is debugging the run to the wrong capability. - Detached work is the exception. A detached task owns its own execution, so it survives the failure of the execution that handed it off, bounded by its own deadline and its own drain budget.
What the operator sees is therefore unambiguous: execution.failed names the capability that actually broke and carries its message. Any other capability in that execution was stopped as a consequence, and should not be read as an independent fault.
A capability deadline is a failure — the work did not finish in time and nobody chose to stop it. An explicit cancellation is a different thing: somebody decided the work should stop, so it ends in StatusCancelled and the capability that was interrupted is recorded as cancelled rather than failed. Reporting an aborted capability as broken would blame an implementation for a decision it did not make.
Cancellation has three owners, and keeping them separate is what makes it work:
| Component | Responsibility |
|---|---|
execution.ScopeRegistry |
Owns one cancellable context per live execution. Binds on start, releases on a terminal state. |
Scheduler |
Decides that an execution is cancelled and records it. Making the execution terminal is what stops the plan from advancing. |
| Capability runtime engine | Invokes each capability under its execution's scope, so a cancellation reaches the work. |
The scope lives beside the execution model rather than inside it. An Execution is a persisted value — marshalled, written, rebuilt after a restart — and a context.Context is a runtime lifetime; holding one on the model would put a live handle inside a value that outlives the process.
A client cancels an execution with POST /v1/instances/{id}/executions/{execID}/cancel. The response distinguishes three outcomes, because a caller must be able to tell them apart: 404 (no such instance or execution), 409 (it already reached a terminal state, so nothing was stopped), and 200 (stopped by this call). Reporting success for an execution that had already finished would tell an operator their stop took effect when it did nothing.
Detached work is cancelled through its own execution. A detached task outlives the execution that handed off to it, so cancelling that execution leaves the task running under its own scope — and cancelling the task's execution stops it.
neuron run cancels on Ctrl-C and keeps streaming until the cancellation is reported, so the outcome is presented like any other terminal state rather than the CLI exiting silently while the work continues. A second Ctrl-C force-quits.
A capability that needs external input can suspend instead of completing. The engine records a durable wait on the capability (signal, timer, or engine-owned deadline) with its reason, correlation key, expected signal, wait deadline, and payload schema, and derives waiting status for the execution when no runnable work remains. This is the state-machine and protocol contract implemented in N.O.R.E.; it is separate from durability modes, which decide what survives a restart.
The primary signal route is POST /v1/executions/{id}/signals/{name}. POST /v1/instances/{id}/executions/{execID}/signals/{signalName} remains as a compatibility surface with the same behavior. The owning instance is resolved from the durable execution record, so a caller cannot address an execution through the wrong instance. The request body requires deliveryId and accepts an optional payload object and correlationKey. The delivery is persisted before the acknowledgement is written; the HTTP handler only validates the request and maps the domain result, and never mutates execution state or walks the assembly blueprint.
Delivery identifiers are idempotency keys. Presenting the same deliveryId with the same payload again returns 200 with status: "replay" and creates no second transition; reusing a deliveryId with a different payload returns 409 (signal_delivery_conflict). A payload is validated against the wait's declared schema; the validator is a bounded, standard-library object-shape check, not full JSON Schema. Wait selection and delivery are decided in the execution domain, which also rejects ambiguous waits.
Signal error responses carry a stable code alongside the HTTP status so callers can branch without parsing the message:
| Condition | Status | Code |
|---|---|---|
| Missing, malformed, or oversized request fields | 400 | invalid_signal_request |
| Payload does not satisfy the wait schema | 400 | invalid_signal_payload |
| No matching wait, or execution/instance not found (cross-instance misses are indistinguishable) | 404 | no_matching_wait / execution_not_found |
More than one wait matches, or deliveryId reused with a different payload |
409 | ambiguous_wait / signal_delivery_conflict |
| Wait expired or execution already terminal | 410 | signal_expired |
| Durable wait store unavailable | 503 | signal_unavailable |
GET /v1/instances/{id}/executions accepts ?status=waiting and projects each suspended capability's wait type, expected signal, wait reason, correlation key, and deadline. The projection reads persisted wait state, so restored executions expose the same details as live ones.
Note
These contracts are implemented end to end in a hosted durable instance, subject to the unresolved limitations recorded below. Durable instances run an instance-scoped poll loop that resumes elapsed timer waits, expires execution deadlines, and reconciles ready dispatch intents on the configured timerPoll cadence; non-durable instances remain event-driven. Signal delivery, wait state, retry waits, timer polling, deadline expiry, recovery of restored waits, and bounded instance-scoped dispatch-intent reconciliation are implemented and tested at their respective boundaries. Instance CLI commands prefer a discovered live project runtime when no explicit remote is set. End-to-end restart, idempotency, and deadline-policy acceptance tests pass, and the final Phase 5 validation gate (T-032) passed after T-081 (./scripts/script.sh printed All modules built and tested successfully.). PostgreSQL parity is unverified without a test DSN.
Live events are streamed over the WebSocket endpoint (WS /v1/ws); the SSE stream (GET .../events/stream) remains available for transports without WebSocket support.
The event bus is the single source of truth for state transitions, and it has two independent consumers: the live subscribers (API streams) and the persister (durable log). Because persistence is asynchronous, an event published at time T may reach the store slightly after T. A client that subscribes to live events at exactly T would therefore miss that event — it is neither in the live subscription nor in the store yet.
The rule that keeps streaming lossless, implemented in nore/internal/stream:
- subscribe to live events first, then take a history snapshot — everything in the snapshot and everything after the subscription is covered;
- emit live events as they arrive, deduplicated by event ID;
- on every live event, and on a short reconciliation interval (25 ms), re-read persisted history after the last delivered event and emit anything new.
A client therefore sees every event exactly once, in order, whether it subscribes before, during, or after the execution — and a fast execution that completes before the client can attach is never lost.
The providers are the only place launch machinery lives. Both implement the same provider.Provider contract; each owns its own process, socket, or module state.
The process provider (nore/internal/mechanism/process) hosts external capability runtimes as OS child processes. It declares the runtime kind process.
It supports two transports, selected by the frozen record's declared protocol:
| Protocol | Model | Used by |
|---|---|---|
neuron/capability-runtime-v1 |
Long-lived gRPC server over a Unix domain socket, with a pool of worker processes per capability runtime | Capability runtimes built on the Go SDK (canonical) |
neuron/capability-runtime-v1-json |
One-shot command: one JSON request on stdin, one JSON response on stdout | WASI modules and capability runtimes that predate gRPC (legacy) |
The process runtime owns the entire process lifecycle for the capability runtimes it hosts: starting worker processes, connecting to them and negotiating the protocol, health checking, leasing executions to workers, cancellation and deadlines, graceful shutdown, and reaping. It never cares what the capability does; it only launches a declared entrypoint, talks the declared protocol, and keeps the process healthy.
When the frozen record declares neuron/capability-runtime-v1-json, each execution spawns a fresh process: the runtime marshals the Request to JSON, feeds it on stdin, the process runs to completion writing a single JSON Response to stdout, and the runtime parses the response. Anything on stderr is diagnostics.
Key properties:
- No worker reuse — every execution pays the process startup cost. The transport exists for compatibility with WASI modules and pre-gRPC artifacts; capability runtimes that want connection reuse must be migrated to the gRPC protocol.
- A non-zero exit code is a transport failure. A zero exit code with a non-empty
errorin the response is a controlled failure. - A green context deadline kills the process through
exec.CommandContext. Each execution also carries a defensive timeout (10 minutes by default); the stricter of the caller deadline and the default bound applies. Healthonly verifies the entrypoint exists and is not a directory. There is no long-lived process to probe.Closeis a no-op: one-shot executions own their process lifecycle.
Warning
For process capability runtimes this is the legacy path. New ones should prefer the gRPC transport.
When the frozen record declares neuron/capability-runtime-v1, the runtime maintains a pool of long-lived worker processes per capability runtime type. Executions are leased to workers and workers are reused across executions. This is the default for process capability runtimes because process startup is the dominant execution cost.
Starting a worker is a three-step handshake bounded by a start timeout (30 seconds by default):
sequenceDiagram
participant RT as Runtime
participant CR as Capability runtime process
RT->>RT: create temp socket directory
RT->>CR: spawn entrypoint with env
Note over CR: NEURON_CAPABILITY_RUNTIME_SOCKET, READY,<br/>PROTOCOL, TYPE, VERSION
CR->>CR: start gRPC server
CR->>CR: create readiness file
RT->>RT: poll readiness file every 50 ms
RT->>CR: dial Unix socket
RT->>CR: Initialize(protocol, type, version)
CR-->>RT: supported protocol + capabilities
RT->>RT: worker marked healthy, joins pool
-
Spawning. The runtime creates a temporary socket directory and launches the entrypoint as a child process. The process environment carries:
NEURON_CAPABILITY_RUNTIME_PROTOCOL,NEURON_CAPABILITY_RUNTIME_TYPE,NEURON_CAPABILITY_RUNTIME_VERSIONdescribing the execution,NEURON_CAPABILITY_RUNTIME_SOCKETpointing at the capability runtime's Unix domain socket,NEURON_CAPABILITY_RUNTIME_READYpointing at a readiness file it must create.
The worker's working directory is set to the capability runtime's install root when one is declared.
-
Readiness. The capability runtime starts its gRPC server and creates the readiness file. The runtime polls for the file (every 50 ms) until it appears or the start timeout expires.
-
Negotiation. The runtime dials the Unix socket, sends an
Initializerequest carrying the declared protocol version plus the capability runtime type and version, and the capability runtime replies with its supported protocol version and capabilities. An empty reply version is rejected. On success the worker is marked healthy and joins the pool.
Note
If any step fails, the process is shut down and the start fails with the specific failing stage. The runtime also removes a stale socket file before listening so a crash from a previous run never blocks startup.
Each Execute call leases a worker rather than spawning a process:
- the pool first tries to take an idle, healthy worker from its available channel;
- if none is idle and the pool is under capacity, a new worker is started;
- if the pool is at capacity, the request waits for a worker to become available, subject to the caller's context (cancellation propagates).
The worker executes the request over gRPC and is returned to the pool. A deadline carried by the caller context becomes the gRPC deadline, so a canceled or timed-out execution aborts the RPC.
maxWorkers (from the manifest's runtime.maxWorkers, carried through the frozen record) bounds the number of concurrent worker processes per capability runtime type. A value of 0 or unset uses the runtime default of 1 — concurrency beyond one worker therefore requires an explicit manifest declaration.
The pool is created lazily: the first Execute starts the first worker. A pool is owned by the process runtime keyed by type@version, so recreating an instance for the same capability runtime closes any previous pool for that key before installing the new one.
- Health. A worker reconnects to its socket on every request and is marked healthy after a successful initialization.
Healthreports the pool healthy when at least one worker is healthy. - Restart. A worker that is found unhealthy is closed and replaced; requests are never sent to a known-unhealthy worker.
- Graceful shutdown. Closing the pool first calls
Shutdownon every worker (with a 10-second bound), then closes the gRPC connection. The runtime waits for each process to exit, kills it only if it overruns the same bound, and clears the socket directory. Closing an already-closed pool is a no-op.
The transport is decided entirely by the frozen record's protocol:
| Declared protocol | Behavior |
|---|---|
neuron/capability-runtime-v1 |
gRPC worker pool |
neuron/capability-runtime-v1-json |
One-shot JSON process |
| anything else | Start fails with an explicit unsupported-protocol error |
| empty | Normalized by the adapter layer to neuron/capability-runtime-v1-json for legacy compatibility |
Tip
If the entrypoint does not exist, Start fails fast with a missing-entrypoint error.
The WASM provider (nore/internal/mechanism/wasm) hosts external capability runtimes as wasm32-wasi WebAssembly modules, implemented on top of wazero, the pure-Go WASI runtime. It is registered for the runtime kind wasm.
WASI preview1 has no socket interface, so a gRPC server cannot run inside a WASI module. The stdin/stdout JSON transport is therefore the only option — and it is the natural one: a module that reads a request from stdin and writes a response to stdout behaves identically as a native process and as a WASM module. A WASM capability runtime and a legacy process capability runtime are byte-for-byte compatible at the protocol level.
Important
One property dominates everything about the WASM runtime: it is process-global.
The wazero runtime is created exactly once per process, lazily, and is shared by every WASM instance. It owns the compilation engine and the module registry. withCloseOnContextDone is enabled so wazero inserts periodic checks that interrupt in-flight calls when their context is canceled or reaches its deadline — this is what kills runaway modules cleanly.
Compiled modules are cached in memory inside the shared runtime, keyed by the frozen entrypoint path. Each distinct module file is compiled exactly once and reused by every subsequent execution and by every other instance that references the same file — one compiled module per distinct module file, not one for the whole process. The cache is shared because a wazero runtime holds the compiled-code engine and module registry (creating one per instance wastes memory and recompiles native code), and because compiled modules are immutable and safe to instantiate concurrently, so executions never serialize on the cache.
Each execution is a full, isolated sandbox cycle: the runtime marshals the Request to JSON, prepares a fresh module configuration (empty stdin replaced by the request bytes, stdout/stderr buffers, the capability runtime environment — NEURON_CAPABILITY_RUNTIME_PROTOCOL, _TYPE, _VERSION — wall time, nanotime, and sleep support), fetches the shared compiled module (compiling on first use), instantiates a fresh module instance, and invokes the _start export against the execution context. A module missing _start is rejected. The instance owns only its compiled-module reference and timeout; each Execute recovers the shared compiled module and instantiates on demand, so parallel requests run in parallel sandboxes.
A WASI command exits by calling proc_exit: exit code zero closes the module cleanly; a non-zero code is a controlled failure. Any other call error is a transport failure. Whatever the module wrote to stdout is parsed as the JSON Response and returned.
Every execution carries a defensive timeout (10 minutes by default); when the caller context carries a deadline, the stricter of the two applies. The deadline is applied to the _start call, and because the shared runtime is configured with withCloseOnContextDone, wazero interrupts the still-running call and closes the module automatically when the deadline hits. A module that loops forever cannot leak a goroutine, block the process, or outlive its window.
The instance's Close is a no-op by design. The wazero runtime and the compiled modules are owned by the process and shared by every instance, so closing one adapter never tears down resources other instances still need; the shared runtime is released only when the process shuts down. The entrypoint existence is verified at Start, so a missing artifact fails fast when the instance is created rather than on the first execution. Compilation is lazy, so the first Execute (or Health) pays the compile cost and every later one reuses the cached module — a healthy instance therefore implies the module compiles.
A frozen record whose runtime kind is neither process nor wasm (for example container or remote) is rejected at adapter creation with an explicit unsupported-runtime error. The runtime never guesses: an artifact that cannot be hosted correctly is never started.
Every provider enforces a defensive execution bound (10 minutes by default) when the caller context carries no deadline; the stricter of the two applies when the caller does carry one. Runaway behavior never blocks the process:
- process capability runtimes are reaped by timeout and the pool restarts workers;
- WASM modules are interrupted by wazero's close-on-context-done and their module is torn down.
Successful and failed executions both flow back through the same response contract. Controlled failures (a non-empty error) and transport failures are distinguishable to callers.
A capability runtime is an artifact that an assembly's capability types resolve to. Creating one means producing two things.
The artifact. Either a native binary or script that speaks one of the two protocols, or a wasm32-wasi module that reads a JSON request from stdin and writes a JSON response to stdout.
For process capability runtimes that want the gRPC transport, the fastest path is the Go SDK (packages/executor-sdks/golang): implement a Handler, call Serve, and the SDK handles sockets, readiness, negotiation, and lifecycle. The SDK transparently falls back to the JSON transport when launched without a socket, so one binary serves both. The .NET SDK (packages/executor-sdks/dotnet) covers the same ground for C#. Capability runtime authors are not required to write Go: the gRPC protocol is language-independent (shared/protocol/capabilityruntime/v1/capability_runtime.proto), and the JSON protocol is trivially implemented anywhere.
A WASI module is built from the same stdlib-only source:
GOOS=wasip1 GOARCH=wasm go build -o capability.wasm .The manifest. Every capability runtime ships a runtime.json — see the manifest contract. A process capability runtime declares neuron/capability-runtime-v1 (with maxWorkers when it wants more than one concurrent worker); a WASI module or legacy command declares neuron/capability-runtime-v1-json and binds the wasm32-wasi platform key.
From there the normal evolution holds: the artifact is distributed through a registry, resolved by requirement, verified and installed into the store, frozen into a deployment, and finally operated unchanged by the matching provider. The reference module examples/capability-runtimes/echo ships in this repository, compiled to both a native binary and a wasm32-wasi module from a single Go source.
N.O.R.E. persists registered assemblies, instance metadata, execution snapshots, and the event log through one backend-neutral contract, storage.Store. Generic runtime packages depend only on that contract. Concrete drivers live under nore/internal/storage/<driver>; only the composition root (cmd/nore) imports one, so the execution, event, instance, assembly, and planner packages cannot acquire a backend dependency.
SQLite is the default driver. --storage-driver selects a registered driver, and its default comes from NEURON_STORAGE_PROVIDER; the CLI forwards the effective internal storage provider to the runtime as that flag. Storage configuration itself is engine-owned and is rejected from project files. storage.Open performs the whole lifecycle: validate the driver, construct it, run migrations, and Ping. An unknown driver or a failed open aborts startup with an actionable error; there is no silent fallback to another backend. A store is passed to runtime components as storage.Store; no component constructs its own backend.
The contract has explicit failure semantics. Missing records are storage.ErrNotFound, compare-and-swap losses are storage.ErrConflict, insert-only collisions are storage.ErrAlreadyExists, and nested/re-entrant transaction use is storage.ErrNestedTransaction / storage.ErrTransactionActive. Callers distinguish absence from backend or decode failures with errors.Is; a failed read is never reported as an empty list or a missing record.
storage.Store.WithTx(ctx, fn) runs fn against a storage.Tx that exposes the same Get/Put/Delete/List operations bound to one transaction. Returning an error or a cancelled context rolls back. A plain Store operation attempted while a transaction is active returns ErrTransactionActive; a nested WithTx returns ErrNestedTransaction rather than joining or deadlocking. Store and transaction concurrency rules are part of the contract suite (nore/internal/storage/storagetest), not an assumption about SQLite.
Transactions are required when one logical operation writes more than one key:
- Assembly registration writes the artifact and updates the version index atomically. Superseded artifacts are retained, so registration never deletes work a durable execution still references. A failed registration leaves no partial artifact or index entry.
- Execution save reads the persisted revision, compares it with the writer's revision, and writes the next snapshot in one transaction. This is the compare-and-swap guard that rejects a stale writer.
- Execution transition plus dispatch intent persists the next execution snapshot and the ready dispatch intents atomically. A stale writer is rejected and a failed intent write rolls back the transition.
- Timer operations use
Store.WithTimer, which shares the main KV surface with a due-time-indexed timer surface.PutTimerrecords an explicit due time;DueTimersreturns at mostlimitdue, unleased timers ordered by due time then key;ClaimTimer,RenewTimer, andDeleteTimerOwneduse an opaque per-claim owner token so a stale claimant cannot complete or extend another worker's timer. The shared contract suite exercises these operations on memory and SQLite; PostgreSQL coverage is gated on a test DSN and is not claimed here.
Single-key reads and writes use the plain Store; they do not need a transaction.
Three guarantees are separate and must not be conflated:
| Guarantee | Meaning | Status |
|---|---|---|
| Observability | A run's transitions and output can be inspected through events and the API | Implemented |
| Persistence | Registered assemblies, instance metadata, execution history, and events survive a restart and remain queryable | Implemented |
| Durable execution | Unfinished work resumes after a restart from its last committed transition, with at-least-once dispatch | Implemented |
Under fan-in, a detached branch may not participate in a join. A detached capability runs in a separately tracked execution that the parent never waits for; if a predecessor from a detached scope feeds into a join with multiple incoming bindings, the join can never become satisfied. Linear chains with a single predecessor from a detached scope are allowed — the downstream capability runs inside the detached scope and is handled by buildDetachedScopes (nore/internal/planner/detach.go). This rule is enforced during compilation in nore/internal/planner/compiler.go:154-160, where the planner rejects any binding from a detached capability to a join point (multiple incoming bindings). The intent is to prevent an unsatisfiable join state that would result from mixing detached scope ownership with fan-in convergence.
Persistence does not imply durable execution. N.O.R.E. keeps live executions in memory and writes snapshots through to storage, so live work is fast and completed history survives a restart. Saving a snapshot is not the same as recording a resumable transition and dispatch intent.
In history mode, restore is metadata-only: unfinished executions are marked failed because no runtime can resume them. In durable mode, N.O.R.E. recompiles each execution's pinned assembly artifact, restores completed capabilities and recorded joins, and re-dispatches unfinished work. Interrupted running capabilities follow at-least-once dispatch, so external effects must be idempotent; recovery does not claim exactly-once execution.
The policy surface names three modes, configured at runtime.execution.durability. Durability is deployment-level configuration: the project configuration file rejects the key, and it is set through --durability or NEURON_EXECUTION_DURABILITY.
| Mode | Semantics |
|---|---|
runtime.execution.durability: none |
No execution/event history is retained. Live executions remain observable in memory, but nothing survives a restart. |
runtime.execution.durability: history |
Execution and event history is retained for inspection, but unfinished work is not resumed. Restore marks it failed. This is the default. |
runtime.execution.durability: durable |
Execution transitions and dispatch intent are persisted atomically; unfinished work is restored and resumed from the last committed state, with at-least-once dispatch. Startup refuses a non-transactional backend when this mode is selected. |
All three modes are wired through the CLI, daemon, and project launch paths. Instance CLI commands prefer a discovered live project runtime over the build daemon when no explicit remote endpoint is configured, so a command addresses the runtime that owns a recovered execution. Recovery restores pending and running root executions, recorded joins, detached tasks, durable retry waits, and suspended waits against the execution's immutable artifact; snapshots carry wait state and the execution deadline. A resumed or retried invocation carries a fresh attempt ID while the logical operation ID is stable across restarts; capability runtimes must deduplicate on the logical operation ID together with the delivery ID, never on the attempt ID. The capability-level suspend/resume contract and the state machine that resumes restored waits are implemented and tested at their boundaries.
The store (nore/internal/execution/store.go) exposes a bounded, owner-fenced, instance-filtered claim over a dispatch_ready/ ready index, and durable instances run an instance-scoped poll loop over bounded due-wait and deadline indexes. A consumer-local reconciler (nore/internal/execution/reconciler) claims bounded per-instance batches with a fresh fencing token per pass, releases each claim before publishing CapabilityReady on its own instance bus, and never completes intents; failed publishes leave intents discoverable. End-to-end restart, duplicate-delivery, authorization, worker-occupancy, and deadline-policy acceptance tests pass, and the final Phase 5 validation gate (T-032) passed after T-081 (./scripts/script.sh printed All modules built and tested successfully.). PostgreSQL parity remains unverified without a test DSN.
Wait and timer behavior is also governed by deployment-level settings under runtime.execution. These are operational settings owned by the deployment, not by an assembly: project configuration rejects the key, and values are supplied through global configuration, NEURON_* environment variables, or nore flags before being forwarded to N.O.R.E. They never enter assembly identity and never turn a non-durable execution into a durable one.
| Setting | Default | Meaning |
|---|---|---|
runtime.execution.waitDeadlinePolicy |
fail |
Action when a wait deadline expires: fail (capability fails with wait_timeout), cancel, or continue (resume as though satisfied). |
runtime.execution.maxLifetime |
720h (30 days) |
Bound on the whole execution; 0 disables it. Distinct from a capability's execution.timeout. |
runtime.execution.timerPoll.interval |
1s |
Cadence of the durable-only due-timer and deadline poll loop; must be at least 100ms and at most 1m. |
runtime.execution.timerPoll.batchSize |
256 |
Maximum due timers claimed in one pass; must be between 1 and 4096. |
The short environment names are NEURON_WAIT_DEADLINE_POLICY, NEURON_EXECUTION_MAX_LIFETIME, NEURON_TIMER_POLL_INTERVAL, and NEURON_TIMER_POLL_BATCH_SIZE. Invalid values fail configuration load rather than falling back silently. Durable instances start a due-timer and deadline poll loop that consumes the interval and batch size at the configured cadence, producing periodic timer-driven resumes and deadline expiry; non-durable instances remain event-driven and start no such loop. See Waiting and signals.
Registered assemblies are stored under assemblies/{id}/{version}/{hash}/{env}/manifest. A key that carries a hash resolves exactly that artifact; an unknown or mismatched artifact is an error, never a fallback to the latest content.
Artifacts are immutable once written. Registering the same assembly version again moves the version index to the new artifact but retains the earlier hashes, so a durable execution pinned to an older hash remains recoverable. The CLI reports a same-version replacement and warns that the previous artifact is retained; a version bump is still the clearest way to express a graph change.
Removal is never a side effect of registration. It happens only through explicit deletion or startup garbage collection. Retention is configured under runtime.execution.retention:
| Key | Meaning |
|---|---|
maxAge |
Minimum age of a superseded artifact before it may be removed, e.g. 168h. Empty keeps artifacts indefinitely. |
maxArtifactsPerVersion |
Maximum artifacts retained for one assembly/version. Zero keeps all. |
The current artifact of every registered version and every hash referenced by a non-terminal execution are always retained, regardless of policy. Destructive instance removal and clearing are refused while unfinished executions exist unless --force is supplied; forced removal deletes their execution history.
Note
Execution history and events are an observability and persistence concern, not part of execution semantics. History is retained by default and can be disabled with runtime.execution.durability: none; execution must not depend on retention being enabled.
- Default transport is local. N.O.R.E. listens on a Unix socket (mode
0600) owned by the local user, in a directory created with mode0700. - The API is authenticated. Every route except the health probe requires the daemon's API token as
Authorization: Bearer <token>, compared in constant time. The daemon publishes the token in<socket>.token(mode0600) and generates one when none exists, so a local client needs no configuration. The socket alone is not a boundary: any local process can connect to it. TCP is opt-in and refuses to start without a token; the token authenticates the caller but does not encrypt traffic, so a TCP listener belongs behind TLS termination. - External capability runtimes are untrusted. They are verified by digest before install, hosted out-of-process, and never loaded into the N.O.R.E. address space (with the deliberate exception of modules shipped as part of N.O.R.E. itself).
- Capabilities are metadata, not permissions. A module manifest may declare capabilities; the runtime enforces actual permissions at the execution boundary.
- GitHub is a distribution source, not a security boundary. Release artifacts are verified by digest before installation.
- Concurrency is bounded by a capability runtime worker pool (
-workers, default 8); long-lived workers are reused across requests rather than respawned per invocation, so warm execution latency is dominated by the capability runtime protocol call rather than process startup. - Resolution prefers already-installed artifacts, so instance execution stays local and offline once modules are in the store.
- The WASM provider keeps compilation and compiled modules shared process-wide, so instance creation does not pay a compile cost.
- Optimization follows measurement, not assumption: the tunable numbers are worker counts, the 25 ms stream reconciliation interval, and the 10-minute defensive execution bound.
Note
Do not prematurely introduce distributed infrastructure; the local model is the base case, and distribution is an explicit, incremental option.
| Modules & capability runtimes | The unified module model in detail — docs/MODULES.md |
| Getting started | Build and run your first assembly — docs/GETTING_STARTED.md |
| CLI | The neuron CLI, the user-facing surface — application/README.md |
| TypeScript SDK | The assembly-definition language — packages/assembly-sdks/typescript/README.md |
| Go SDK | Author a capability runtime — packages/executor-sdks/golang/README.md |
| .NET SDK | Author a capability runtime — packages/executor-sdks/dotnet/README.md |