Architecture
This page explains how Neusym is built: the layers, how kits connect without knowing each other, what happens when an agent calls a tool, and the rules neusym plan checks. Read it when you want to…
This page explains how Neusym is built: the layers, how kits connect without knowing each other, what happens when an agent calls a tool, and the rules neusym plan checks. Read it when you want to understand a plan error or write your own kit. The full specification is ARCHITECTURE.md. In a checkout of this repository, neusym is node apps/cli/dist/src/index.js.
#Layers
Imports go one way: kits and drivers depend on contracts and core, never the other way round, and no core package, kit or app imports a kit or a driver.
| Layer | Folder | What it holds | May import |
|---|---|---|---|
| core | core/ | sdk (types and helpers), kernel (plans and runs an environment), loader (finds packages by name and loads them), operator (services the CLI and server share), testkit | sdk: nothing. kernel: only sdk. loader: sdk, kernel, Node's file and module APIs |
| contracts | contracts/<name>/ | one package per port, with the extension points and events it owns | @neusym/sdk; other contracts for types only |
| kits | kits/<category>/<id>/ | one rule or capability each | @neusym/sdk and the contracts in its package.json |
| drivers | drivers/<port>/<id>/ | backends: in-memory, SQLite, files, Postgres (Enterprise) | @neusym/sdk, its contracts, its own dependencies; the network only if driver.json says network: true |
| profiles | profiles/, profiles-ee/ (Enterprise) | JSON that picks a driver for each port | no code |
| apps | apps/cli, apps/server, apps/tui | the neusym CLI, the HTTP server, the terminal UI | core and contracts, never kits or drivers |
The kernel reads no files and opens no connections. The loader reads the workspace file and loads each kit and driver by package name, so a kit is plugged in by a line in workspace.yaml, not by an import. The profile binds only the drivers the kits need: the seven-kit environment from Build an Environment plans to five (store, bus, model, blobs, vault).
npm run check (scripts/ci/run-check.mjs) enforces this. It compares every package.json with the allow-list (a kit may depend only on @neusym/sdk and @neusym/contract-*), refuses cycles between contracts, and reads every source file under src/ as tokens (scripts/ci/source-scan.mjs) to check it against scripts/boundaries/rules.json: a kit that imports another kit fails with disallowed import "@neusym/kit-budget", and one that writes a point name as a plain string fails with raw connection string literal "task.complete" in kit code. ARCHITECTURE.md has the layer graph and the plug-in rules behind these checks.
#Contracts
Kits meet through contracts: packages under contracts/ that define three kinds of connection. A port is a named, versioned interface, like budget@1. One kit or driver provides it, never two; other kits list it in requires (plan fails without it) or optional (used when present). The budget kit provides budget@1, planner requires it, and harness uses it when it is there. Port methods take the caller's context first, as in getScopeBudget(ctx, scopeId), so each call acts for one tenant.
An extension point is a named place where kits add stages. The kit that runs the point lists it in runs; the kernel then calls every stage in order. A stage has one of four kinds:
| Kind | What the stage does | Example point |
|---|---|---|
| guard | votes allow, abstain, deny or require_approval | action.authorize, task.complete |
| intercept | wraps the call, like middleware | action.execute |
| collect | adds items to what the model sees | context.build |
| filter | changes or drops those items | context.build: secrets redacts, tenancy isolates, injection-guard marks outside text |
Each point has ordered, named phases, and a stage picks a phase instead of a priority number. In contracts/tools/contract.json, action.authorize has the guard phases precheck, budget, taint, tenant, policy, authority and validate, and "requiresAuthority": "execute". The budget kit joins it with { "point": "action.authorize", "kind": "guard", "stage": "action-budget", "phase": "budget" } in its kit.json. A point belongs to the contract of the port whose kit runs it: tool-gateway provides tools@1 and runs action.authorize, so the point lives in @neusym/contract-tools. A kit from outside this repository can bring new points and events in its own contract package.
An event is a record one kit publishes and others listen to. task.changed (in contracts/tasks) is published by tasks when a task is created or changes state; budget, worker-pool and others listen. A kit commits its events in the same store transaction as its writes, and the kernel sets each event's source to the kit's id. Delivery is in Coordination and Events.
#How a tool call is checked
When the model asks for a tool, harness hands the call to tool-gateway, which runs the action.authorize guard point. Here is the tool call from the Quickstart's status-report example (neusym run examples/demo-product/status-report "Inspect item-1" --model-turns examples/demo-product/status-report/turns/matching.json --full):
├─ tool.call demo_inspect ok 5ms
│ ├─ guard action.authorize allow 1ms
│ │ ├─ budget:action-budget abstain 0ms
│ │ ├─ injection-guard:taint-write-guard abstain 1ms
│ │ └─ tenancy:tenant-scope abstain 0ms
│ ├─ intercept action.execute 0ms
│ ├─ event action.completed → intake #5 0ms
│ └─ event action.completed → observability #5 0msThe kernel (core/kernel/src/executor.ts) decides in steps:
- Shape and level. The call must name a tool and an effect (
read,draft,executeorcommit), or it is denied withMALFORMED_ACTION_PROPOSAL. The effect must fit the level: anexecutetool in areviewenvironment is denied withLEVEL_CEILING_DENIED. Both happen before any guard runs. - Phase 1: every guard votes, in phase order, then by kit id and stage name (above: phases
budget,taint,tenant). Phase 1 is read-only: a guard reads only its own kit's collections, and any write fails withPHASE1_WRITE_FORBIDDEN. A guard that wants to record something returnscommitWritesandcommitEventswith its vote. A guard that throws or times out counts asdeny. - Tally. Any
denywins, then anyrequire_approval. If a kit claims authority for the point (authorityFor), it must voteallow; otherwise no objection meansallow. - Phase 2. On
allow, the kernel commits all the guards' writes and events in one store transaction. If another write got there first, it runs Phase 1 again, at most three attempts in all, then denies withGUARD_COMMIT_CONFLICT. Ondenyorrequire_approvalnothing is written except aguard.refusedevent, which only the kernel publishes, naming the point, the code and who decided. - Run. The
action.executeintercepts wrap the real call, andtool-gatewaypublishesaction.completed.
The other guard points use the same Phase 1, tally and Phase 2: harness.step before each model call, output.release and task.complete before an answer leaves, trigger.admit, delegation.spawn, memory.admit, and package.install (Enterprise supply-chain). These points need an authority: action.authorize from level execute (action-gate), task.complete from draft (completion-gate) and delegation.spawn always (budget). What each guard enforces is in Authority and Safety.
#Confinement
A kit reaches everything through the handles its create function receives, and each handle checks the kit's manifest:
| A kit can | Only when | Otherwise |
|---|---|---|
read and write store collections (handles.storeFor(ctx)) | they are in its collections | COLLECTION_NOT_OWNED |
| publish an event | its type is in events.publishes and it is not a kernel event | EVENT_NOT_DECLARED, EVENT_RESERVED |
get a port (handles.requirePort, getPort) | the port is in requires, optional or provides | refused |
run an extension point (handles.runGuards and the like) | the point is in runs | refused |
read its own collections across tenants (systemStore) or start work for any tenant (issueContext) | it requests the grant and the workspace gives it | the handle is missing |
The store and bus ports themselves (store@1, bus@1) are never handed to a kit. Every call carries a context (ctx) for one tenant and one actor. The kernel accepts only contexts it issued (CONTEXT_NOT_ISSUED) and refuses a copy with another tenant or actor (CONTEXT_TENANT_MISMATCH, CONTEXT_ACTOR_MISMATCH). A copy may record less (capture) or move live work to shadow or simulation, never back.
A kit never holds a driver object. It gets a frozen facade with only the methods the port contract lists in members, no lifecycle methods (close, flush, start, stop), and the caller's tenant bound into each call as the contract's tenantBinding says. During a guard, only the contract's readMembers can be called. See Tenant-Bound Driver Facades. Kits run in the host process; isolation: { <kit-id>: worker } in the workspace file runs one in its own worker thread.
#Determinism
Models propose; the kernel and the kits decide, and a decision must come out the same every time. So core, contracts, kits and examples/ may not read the clock or a random source: rules.json forbids Date.now, new Date(), Date(), Math.random, crypto.randomUUID, crypto.getRandomValues, performance.now and process.hrtime there. A kit asks its context instead (ctx.nowMs(), ctx.nowIso(), ctx.nextId(), or handles.clock and handles.ids). The host passes the real clock; tests pass FakeClock from @neusym/testkit. Loading code is closed too: sdk, kernel, operator, contracts and kits may not use import(), require, eval or new Function. The loader loads kit and driver code, and only the packages the workspace file and its profile name.
#What plan checks
neusym plan reads the workspace file, finds every kit and driver by package name, and reads their manifests and contracts without running kit code. It checks that each package is installed at the requested version and built, and that driver config fits each driver's schema. Then it runs the composition rules below, prints every error at once and exits with code 1. The kernel runs the same rules again at boot. Fixing errors by plugging kits in and out is covered in Build an Environment. Take that guide's seven-kit environment and delete the tool-gateway line:
Workspace composition failed with 5 error(s):
[Z3] Dead contribution: kit "budget" contributes "action-budget" to "action.authorize", which no loaded kit runs (mark optional: true if intended to be dormant).
[Z3] Dead contribution: kit "tenancy" contributes "tenant-scope" to "action.authorize", which no loaded kit runs (mark optional: true if intended to be dormant).
[Z3] Dead contribution: kit "injection-guard" contributes "taint-write-guard" to "action.authorize", which no loaded kit runs (mark optional: true if intended to be dormant).
[Z1] Kit "harness" requires port "tools@1", which has no provider in this workspace.
[Z5] Level "review" requires socket port "tools@1" (from "review" contract), which has no provider.tool-gateway ran action.authorize, so three guards now target a point nothing runs (Z3), and both harness (Z1) and the review level (Z5) miss the tools port. The table lists every rule. Z5 to Z8 come from the level policy (data in @neusym/contract-levels) and add up: a commit environment must pass all four. Z9 to Z14 belong to a port's contract and run only when that port is in the environment.
| Rule | Checked by | Plan refuses when |
|---|---|---|
| Z1 | kernel | a port has two providers, a port in a kit's requires has none, or a kit lists store@1, bus@1 or a host-only port |
| Z2 | kernel | a kit is loaded twice, two kits declare the same collection or owned record type, or a kit is planned but not built |
| Z3 | kernel | a point or event is in no contract, a stage uses a kind or phase the point lacks, a stage targets a point nothing runs (without optional: true), two kits claim one point's authority, a point that needs an authority has none, or a kit publishes a kernel event |
| Z4 | kernel | a grant goes to a kit that is not loaded or did not request it, a requested grant is missing, the level is below a kit's needs.minLevel, config does not fit a configSchema or names a kit that is not loaded, or a needed capability or driver port is missing |
| Z5 | level policy | the review level's ports or phases are missing; also an unknown level, or kits at level empty |
| Z6 | level policy | the draft level's ports, authority or phases are missing |
| Z7 | level policy | the execute level's ports, authority or phases are missing |
| Z8 | level policy | the commit level's ports are missing |
| Z9 | store@1 | the store driver lacks a capability a kit needs, or a collection index names no field |
| Z10 | scheduler@1 | a scheduler is loaded without a spending cap (budget@1) |
| Z11 | retrieval@1 | search runs without scopes@1, without a search index that filters by scope, or without listening to scope.revoked (and to the ingestion, lineage and memory change events when those are loaded) |
| Z12 | retrieval@1 | a kit adds results to retrieval.search without requiring scopes@1 |
| Z13 | policy@1 | the policy kit (Enterprise policy-engine) can read memory or search results |
| Z14 | memory@1, policy@1 | a kit with a guard, intercept or filter stage can read learned memory (memory@1, retrieval@1, search-index@1), directly or through another kit |
#Writing a kit
Start from the scaffold, at the root of a Neusym checkout (--dir <root> writes elsewhere):
neusym kit init safety/answer-limitIt creates kits/safety/answer-limit/ with kit.json, a package.json named @neusym/kit-answer-limit, a tsconfig.json that extends the repository's tsconfig.base.json, an empty kit in src/index.ts, and a test that boots the kit alone with bootKitInIsolation. The category (safety) only picks the folder. The fields of kit.json:
| Field | What it declares |
|---|---|
id, version, needs.minLevel | the kit's name (used in kitConfigs and grants), its version, and the lowest level it loads at |
provides, requires, optional | ports, always with a version (tasks@1) |
collections, owns | the store collections it reads and writes, with indexes; record types only it may own |
runs, contributes | points it runs; stages it adds (point, kind, phase, stage, and optional: true if the point may be absent) |
events | event types it publishes and listens to |
authorityFor, requests | points where its allow is required; the grants it asks for (systemStore, contextIssuer), which the workspace must give |
configSchema | JSON Schema for its config; defaults live only here |
This kit adds one instruction to the model's context and refuses to complete a task whose answer is too long. Its kit.json declares:
"contributes": [
{ "point": "context.build", "kind": "collect", "phase": "skills", "stage": "limit-hint" },
{ "point": "task.complete", "kind": "guard", "phase": "validate", "stage": "check-length" }
],
"configSchema": { "type": "object", "additionalProperties": false,
"properties": { "maxChars": { "type": "integer", "minimum": 1, "default": 280 } } }and src/index.ts:
import { EXECUTOR_POINTS } from '@neusym/contract-executor';
import { TASKS_POINTS, type TaskCompleteInput } from '@neusym/contract-tasks';
import type { GuardVote, KitDefinition, KitManifest } from '@neusym/sdk';
import kitJson from '../kit.json' with { type: 'json' };
const answerLimit: KitDefinition = {
manifest: kitJson as KitManifest,
contracts: { points: [...TASKS_POINTS, ...EXECUTOR_POINTS] }, // the points it uses
create(_handles, config) {
const maxChars = config.maxChars as number; // already checked against configSchema
return {
collectors: {
'limit-hint': (ctx) => [{
id: 'answer-limit:hint', source: 'system', kind: 'instructions',
tenantId: ctx.tenantId, content: `Answer in at most ${maxChars} characters.`,
}],
},
guards: {
'check-length': (_evalCtx, input: TaskCompleteInput): GuardVote =>
(input.output ?? '').length > maxChars
? { decision: 'deny', code: 'ANSWER_TOO_LONG', reason: `More than ${maxChars} characters.` }
: { decision: 'abstain' },
},
};
},
};
export default answerLimit;Add the two contract packages to dependencies in the kit's package.json: plan reads a kit's contracts from there, and CI allows only declared imports. Keep the contracts field too: without it the kit's own isolation test fails with Z3, because alone it does not know task.complete.
The kits/*/* folders are npm workspaces; add the new folder to the references in the root tsconfig.json so it builds with the rest, since plan refuses a kit that is not built. neusym kit verify kits/safety/answer-limit checks the package name, exports, default export, config defaults and dependencies.
Add "@neusym/kit-answer-limit@0.1.0" to the seven starter kits and answer-limit: { maxChars: 40 } under kitConfigs. A 70-character answer now fails. The trace names the stage that decided, and 1→2 items is the instruction the collector added (lines left out are marked …):
task task_… · run run_… · failed (ANSWER_TOO_LONG)
session ses_…
reason: More than 40 characters.
…
├─ context context.build 1→2 items 4ms
…
└─ guard task.complete deny ANSWER_TOO_LONG by answer-limit:check-length 0msFor a kit that also reads a port, see examples/demo-product/status-report: its guard reads the run through tasks@1 and refuses an answer the tool result does not support.