YURIOS // LAB
The Codex → Part III · Brain Chapter 19 · The YuriOS Architecture

The YuriOS Architecture — Host Services, Self-Modification, and the Thesis

The YuriOS Architecture · Part 3 of 3

The host services

The host exposes six services to every resident engine. Each is a narrow contract; the engine sees an interface, not an implementation.

Card loader (.PNG → spec)

Reads the V3 character card, extracts the embedded JSON (and any extensions.yurios block carrying autonomy/memory config), and instantiates an engine with its seed SOUL and config. This is the load path that connects distribution (→ ch. 07, ch. 33) to runtime: the card boots the brain. On export, the updated editable surfaces can be re-embedded back into a .PNG (see the self-edit flow below).

The loader is also where "signed constitution" stops being an adjective and becomes a check. The CONSTITUTION.md carried in the card is signed by its author's key; the loader verifies that signature at load and records the signing identity in the audit log. A card whose constitution fails verification — tampered in transit, or re-embedded by a runtime that edited what it must not — boots in a quarantined, capability-denied state (or refuses to boot, per host policy) rather than running with a constitution nobody vouched for. This is what makes the immutability claim (§"SOUL", above) enforceable rather than aspirational: the host refuses writes to the constitution at runtime, and the loader refuses to trust one that was changed out of band.

Two more halves of trust the signature alone doesn't carry. Whose key? A signature proves the constitution matches its author's key — not that the author deserves your machine. The model is trust-on-first-use with pinning: the first load records the signing identity, any later key change is flagged rather than silently accepted, and the Lab publishes its own signing key so the canonical cards verify against a known identity instead of a stranger's. And the grants need a consent moment. The constitution's capability grants were declared by whoever wrote the card, so default-deny (→ broker, below) only protects against the ungranted — the granted list itself came from a stranger. On first boot the loader renders that list as a consent sheet — "this character asks for: network egress, workshop execution, …" (Broker.grants() is the render source) — and the user accepts or trims it before the first tick. A downloaded card is a guest arriving with a list of rooms she'd like keys to; the sheet is you reading the list at the door.

Signal bus — the inbound world

Everything that happens to the system arrives here: user messages from any frontend, timers and scheduled wake-ups, filesystem and OS events, body events, and the completions of long-running work (→ ch. 18, "ACT starts work; it never awaits it"). Each lands as a typed, timestamped signal on a durable per-engine queue, and SENSE reads signals only from here — no frontend ever pokes an engine directly. The implementation is deliberately boring and on-brand: an append-only JSONL inbox per engine, consumed by offset; no message broker, no daemon.

Durability is the point, three times over. The tick trace records what was processed; the bus records what arrived — so a message that lands mid-crash is delivered after recovery instead of silently lost, which for a companion is the difference between a bug and a broken promise. Async completions re-enter the loop as ordinary signals instead of callbacks threaded through the tick. And a recorded week of real signals, replayed under a virtual clock, is the engine's regression suite (→ ch. 23, testing an always-on mind).

Model router — local-first, privacy-aware

Not a provider abstraction but a policy router. Its rules are the economic and ethical spine of always-on (→ ch. 18 on cost; ch. 21 on serving):

  • The local model is the default, and the only tier permitted for the every-tick APPRAISE pass. A frontier model on every heartbeat cooks the GPU and the budget.
  • Escalation to a remote model is allowed only for genuinely hard deliberate reasoning inside ACT, and only when the privacy boundary permits — the router classifies and redacts what may leave the machine before any remote call. What happens on the user's box stays on the user's box unless the user's policy says otherwise.
  • Routing decisions honour the card's declared model_routing policy and the global budget governor.
  • When more than one resident is awake, the router is also the point of contention for the one GPU: model calls across all engines serialise through it, so two waking minds queue rather than thrash the device. The scheduling discipline for that shared inference resource is ch. 21's subject (→ ch. 21, serving); here it is enough that the seam exists and that no engine talks to the model except through this router.

Capability / permission broker

The engine touches the world only through the host's broker, which enforces the limits declared in the (immutable) constitution. Five effector classes, in rough ascending order of blast radius (filesystem appears as two scopes because its two homes have opposite trust models, and code execution and OS control are the dangerous tail):

  • Filesystem — the Vault — her own mind: read/write to soul/, memory/, knowledge/, goals.md, but identity writes route through the gated self-edit flow and CONSTITUTION.md is read-only even to her.
  • Filesystem — the Workshop — her scoped, allow-listed project tree (the workspace above), where she writes and runs code freely; broad latitude inside the sandbox, firewalled from the Vault and the host.
  • Network / browser — fetch and browse under an egress policy; this is also the research intake path, and what it pulls is ingested into the knowledge store (above), not left loose in the prompt.
  • Code execution / sandbox — run what she writes, in isolation tiered to the risk: subprocess → per-project container (Docker, the near-term target) → microVM / full VM (the strong-isolation target for untrusted or heavy work; in-spec, out of scope for the first build). Untrusted input — scraped sites, downloaded repos — runs at the strongest tier available. The heavy multi-step work this effector carries is driven by an embedded, swappable OSS coding harness (Pi/OpenCode), not bespoke loop code (→ ch. 17).
  • OS control — sandboxed, with dry-run modes for anything destructive. (Linux and Windows are genuinely different here; plan a capability abstraction rather than assuming one.)
  • Skills / tools (MCP) — a registry usable autonomously, not only inside a chat turn (→ ch. 17).

All five sit behind one narrow contract — and because the broker is the most safety-relevant surface in the system, it earns a contract as explicit as memory's or knowledge's. Every effector call crosses the same four-step gate, in this order, no exceptions:

Broker                            # the host's gate on the world; the engine holds no capability directly

  request(effector, op, args, *, character) -> EffectorResult
      # 1. AUTHORIZE  — is (effector, op) within this character's CONSTITUTION grant?
      #                 deny by default; an ungranted capability is a refusal, not an error
      # 2. CHARGE     — reserve the op's *estimated* cost against the budget governor;
      #                 if even the estimate doesn't fit → refuse (felt as REGULATE
      #                 pressure, → ch. 18)
      # 3. EXECUTE    — run it at the isolation tier the op's risk demands
      #                 (subprocess · container · microVM), untrusted input → strongest tier
      # 4. SETTLE     — reconcile the actual cost and release the unused reservation;
      #                 model calls and workshop tasks have no knowable cost up front,
      #                 and a governor fed estimates it never reconciles is being lied to
      # 5. AUDIT      — append the call, its decision, estimated and actual cost, and
      #                 result, keyed by tick_id so the dashboard can replay "why did she do that?"
      # a denial short-circuits at step 1 or 2 and is logged like any other call

  grants(character) -> list[Grant]  # OBSERVABILITY — exactly what she may touch, read straight from
                                     #                  the constitution; the dashboard renders this,
                                     #                  and so does the first-boot consent sheet (→ card loader)

Two properties make it load-bearing. Default-deny: a capability the constitution does not name is refused, so widening her reach means changing the constitution — which the engine cannot do. She can only request it (a high-risk item that queues for your approval, → below); granting it is you re-signing the constitution, never something the engine can back into. The gate is unskippable because the engine holds no capability directly — it has a handle to the broker, not to the filesystem or the network, which is the runtime expression of the host/engine process split (→ §"Two tiers", above): you cannot bypass a guard you have to call through to reach anything. Autonomous code execution and OS access are real blast radius; sandbox, dry-run, tiered isolation, and capability-gating are not optional polish, they are the price of shipping to anyone but yourself.

Budget governor

Per-hour caps on tokens, compute, and wall-power, enforced across all residents. It prevents the runaway-loop failure that made Auto-GPT a cautionary tale (→ ch. 02 §1, the LLM agent explosion) and it keeps the "just works on someone's computer" promise true. Critically, it feeds back into the loop's REGULATE phase (→ ch. 18): as the engine approaches a cap, cadence slows and the activity state drops toward DORMANT. Cost control is not a monitor bolted on the side; it is wired into the heartbeat.

Audit log & inner-life dashboard

The dashboard surfaces, per character: the journal, recent decisions, file diffs, goals in flight, pending self-edits awaiting approval, and budget/state. It is simultaneously an engineering necessity (you cannot debug an always-on agent you cannot observe) and the product itself — the "she was alive while you slept" surface that converts autonomy from creepy to an inner life you get to witness (→ ch. 18, ch. 28). Because the mind is files, most of the dashboard is a renderer over the Vault and git log; observability is close to free, which is the file-centric bet paying off again.

Crash recovery: waking up where she left off

An always-on agent will be killed mid-tick — by a crash, a reboot, a pulled power cord — and the host is what makes that survivable rather than corrupting. The discipline is the same file-centric bet paying off a third time: the journal and tick trace persist to disk every tick, so they double as the recovery substrate (→ ch. 18, the trace). On restart the host re-instantiates the engine and the engine rehydrates — it reloads its goals (goals.md), any open intentions from the last committed trace, and whatever arrived unprocessed on the signal bus (→ above), rather than waking amnesiac and re-deciding from a blank slate. Two rules keep a torn write from poisoning the mind: Vault state files are written atomically (write-temp-then-rename), and durable changes to the mind land as git commits, which are all-or-nothing — a crash between two writes leaves the last commit intact, never a half-applied identity edit. The Workshop gets no such guarantee and needs none; a half-finished build in the sandbox is exactly the kind of mistake you tear down and redo (→ above). Recovery is therefore a host responsibility — supervise the process, restart it, hand it back its disk — and the engine's only job on wake is to read what it already wrote.

And the machine doesn't only crash — it sleeps. An OS suspend, a closed laptop lid, an overnight shutdown are daily events on the hardware this actually runs on, and they need a third discipline: clock-gap reconciliation. On wake the engine computes the missed window from its injected clock and runs one catch-up appraisal over the whole gap — what fired, what expired, what still matters now — rather than either failure mode: firing every stale timer in sequence (thirty-seven queued "good morning"s), or pretending the gap never happened. The honesty rule extends here too: she is allowed to know and say that the machine slept — which is the engine-side half of the frontend rule that presents an unreachable brain as she's resting, never as a faked presence (→ ch. 27).

Self-modification: the gated edit flow

A companion that grows must be able to change her own editable surfaces — but uncontrolled self-modification is how you get drift, jailbreaks, and a character who is no longer herself. The architecture resolves the tension with a single mechanism: every self-edit is a git-committed, risk-gated diff against an editable file, and the constitution is never in scope.

REFLECT proposes a diff to an editable surface (persona, prefs, partner_model, a skill)
   → write to the Vault, git-commit (versioned, diffable, reversible)
   → risk-gate:  low risk  (a note, a preference)        → auto-applied
                 high risk (persona, a new skill,         → queued for human
                            any capability request)          approval in the dashboard
   → optionally, on export: re-embed updated surfaces into the .PNG card

Git-backing every self-edit is the one decision that makes a self-modifying agent shippable: any drift is visible in the history and revertible with one command. The risk gate is the second: low-stakes learning (she notes that you dislike mornings) applies silently; high-stakes change (a rewrite of her own persona, a new executable skill, a request for broader filesystem access) waits for you. The constitution sits outside this flow entirely — it is the floor the self-edit mechanism stands on, not a surface it can touch.

Metacognition and the System 1 / System 2 split

The cheap-APPRAISE-versus-deliberate-ACT rule of ch. 18 is, named properly, a System 1 / System 2 split: a fast path of embeddings and heuristics that runs every tick, and a slow path of frontier-model reasoning invoked only when the fast path flags something worth the spend. The architecture adds a metacognitive surface on top: confidence estimation, loop detection (am I doing the same thing repeatedly?), and consistency checks between the persona she professes and the behaviour she's producing. REFLECT does not merely journal what happened; it judges it and stores the judgement (the Reflexion pattern, → ch. 02 §4), so the reflections buffer becomes a source of learning rather than a diary she never rereads.

How it maps to the five-layer stack

This whole architecture is the ch. 12 stack, assembled. The mapping is worth making explicit, because it shows the chapter is not a new model but the old one made concrete:

Stack layer (→ ch. 12) Components here
Substrate Model router; the local + remote model tiers (→ ch. 13, ch. 21)
Behavior SOUL (constitution + persona); the card loader; prompt templates
Memory The Vault's memory tiers; the world model (situation, → ch. 18); DREAM consolidation; partner model (→ ch. 15)
Knowledge & tools The knowledge store (RAG, → ch. 16); the workshop + code-execution sandbox; effector/capability broker; MCP skill registry; procedural memory (→ ch. 16, ch. 17)
Orchestration The autonomy engine: tick loop, scheduler, salience filter, budget-fed REGULATE (→ ch. 18)
Cross-cutting Audit log & dashboard; budget governor; the git-backed self-edit flow

The interfaces between these are the leverage (→ ch. 12): swap the local model under the router's contract and nothing above notices; replace the file-Vault with a database under the memory contract and the loop never knows.

One engine, many characters: YuriOS beyond the companion

Everything above describes a companion, but almost none of it is about companionship. Strip the fiduciary framing and what remains is a general shape: a portable character definition (the card) that boots a situated, autonomous mind — one that perceives through senses, acts through gated effectors, and keeps its state in swappable stores. That object is not waifu-specific. It is, near enough, what a game wants from an AI character. The ambition worth naming out loud: YuriOS aims to be to a game's characters what a rendering engine is to its visuals — the general substrate you configure per-title, not rebuild per-title. The companion this book builds is one application of that engine; a game NPC is another. This is not a detour from the thesis; it is the reason the whole chapter insisted on contracts instead of a monolith, and it is why the engine is Apache-2.0 with no CLA (→ ch. 39, ch. 41) — the licence was chosen so a game studio could embed the brain, not just read about it.

It is worth being honest that this category already exists and is no longer speculative. LLM-driven NPCs have crossed from tech demo into shipping product — NVIDIA's ACE stack shipped in KRAFTON's inZOI and is in testing as PUBG AI teammates; Ubisoft has trialled its NEO NPC work in production; and a middleware layer has consolidated around Convai (Unity/Unreal/web SDKs bundling speech, memory, perception, and in-world action-taking) and Inworld (pivoted from a character engine to real-time AI infrastructure). The whole category is, today, cloud-hosted and engine-plugin-shaped, and it is still visibly latency-limited — NPC dialogue "feels laggy" next to scripted lines. That shape is the opening: the thing YuriOS offers that the middleware structurally cannot is a local, ownable, moddable brain — the same properties that matter for a companion (→ ch. 03) turn out to matter for a modder who wants a character that runs on the player's machine and can be inspected, edited, and shipped inside a game they own.

What transfers unchanged is most of the architecture:

  • The card is already an engine-agnostic character asset (→ ch. 07, ch. 33). A .PNG SOUL is a portable character a title imports the way it imports a mesh or an animation set — identity, voice, and behaviour in one signed file.
  • The four store contracts are the engine core. MemoryStore, KnowledgeStore, WorldModelStore, and the Broker are exactly the narrow seams a game binds to; from the engine's side a game is another frontend plus another effector set, not a fork of the mind. And because engine and host are already separate processes talking over IPC (→ §"Two tiers"), these contracts are wire-level by construction — a protocol, not a Python import (yurios-protocol/1). That is the LSP move: language servers existed for decades, but the protocol is what made every editor speak to every language — publish this one and a C++ game engine, a TypeScript desktop shell, and the reference Python host are all just clients of the same mind.
  • The world model is the part that makes an NPC situated rather than a chatbot in a box (→ §"The world model"). A game already owns authoritative world state — entities, positions, events — so feeding those into observe() and letting the character reason over situation() is the NPC problem, and it is precisely the surface that drop-in dialogue middleware tends to lack. This is arguably where YuriOS is best-positioned, not worst.
  • The body subsystems are already effectors behind the broker (→ §"Capability / permission broker"). In a game, the engine's own animation and rendering systems become the avatar effector, and in-world actions ("walk to the forge, hand over the sword") become a new effector class — the "action-taking" the NPC middleware sells — with the broker's authorize→charge→execute→audit gate intact around it.
  • Frontends are thin views (→ §"YuriOS at a glance"). Unity, Unreal, or Godot is simply another host binding onto the same mind.

What does not transfer cleanly is the set of defaults tuned for a single, resident companion — and the honest framing is that a game target is a different profile over the same contracts, not a rewrite:

  • Cadence. The git-backed file-Vault earns its keep because the tick loop runs at human cadence (→ §"The brain is a folder"); a scene with many NPCs at frame rate is a different regime entirely. The contract (MemoryStore, WorldModelStore) survives; the file layout does not — a game profile swaps to a pooled, in-memory or database backend under the same interface.
  • Lifecycle. One always-on supervised process per character is right for a resident you live with and wrong for a crowd of villagers who should be event-driven, pooled, and awake only near the player. The always-on autonomy loop — the companion's whole point — is the first thing a game profile turns off.
  • The fiduciary machinery is companion-shaped and mostly drops away. The immutable constitution, the interrupt-threshold attention policy, the always-on cost/thermal budgeting — an NPC keeps the broker and the stores and needs almost none of the rest.

So the claim is deliberately bounded. YuriOS is not today a game engine, and pretending the always-on, one-resident runtime drops unchanged into a title with fifty NPCs would be the kind of overclaim this book tries to avoid. But the seams are in the right places: the card, the store contracts, the broker, and above all the world model are general-purpose, and the companion is one profile built on them. How far the mind really generalises beyond companionship is an open question worth its own entry (→ ch. 45); the rendering and host targets a game brings are ch. 29's subject; and the market adjacency — a bigger, adjacent buyer for the same engine — is picked up in ch. 04.

You are not inventing this

It is worth saying plainly, because the architecture can look like a lot: almost none of it is novel, and that is a strength. The tick loop is the BDI interpreter cycle (→ ch. 02 §1, BDI and cognitive architectures). The overall decomposition — memory, retrieval, reflection, planning as distinct modules over a language-model core — is CoALA (Cognitive Architectures for Language Agents, → ch. 02 §4). The memory-stream-plus-reflection pattern is Generative Agents; the self-authored, verified skill library is Voyager; the stored verbal self-critique is Reflexion; the overnight consolidation is the Dreaming / hippocampal-replay pattern the labs converged on (→ ch. 02 §4); the world model is the Grounded Situation Model / BDI belief-base, now backed by a temporal knowledge graph (→ ch. 02 §4.8). You are re-implementing forty years of agent theory with a vastly better generator inside it. The original contribution is not any one module; it is the opinionated integration — and specifically the parts the research lineage lacked: activity states with cost/thermal budgets, the capability broker, the immutable-constitution-versus-editable-soul split, the interrupt-threshold attention policy, and the card as the distribution artifact. Those are the companion-specific, fiduciary-specific additions, and they are the moat.

The three hard parts

If you build toward this, three components will consume most of the design risk; budget your attention accordingly (this is the same triage ch. 18 and ch. 35 give, named at the architecture level):

  1. The attention policy (the salience/interrupt model of ch. 18). Starting a loop is easy; making it good — neither a chatterbox nor a ghost — is the hard part, and the difference between "magic" and "annoying slop" lives entirely here. Start with conservative interrupt thresholds and let the journal, not notifications, carry the value.
  2. Always-on cost and thermal control (activity states + budget governor). This shapes the whole scheduler: a cheap-model tick, real sleep states, hard caps wired into REGULATE.
  3. Self-modification drift and autonomous OS access (the self-edit flow + the broker). Git-backed reversibility, an immutable constitution, dry-runs, and capability gating are the price of shipping to anyone but yourself.

This is the thesis, assembled

Chapter 18 made the case that genuine initiative needs a different runtime shape. This chapter is that shape, fully drawn: a mind that is a folder you own, a heartbeat that rests most of the time, a self that can grow but cannot rewrite its own constitution, and a building whose safety machinery holds the floor steady under the resident rather than guarding against her. Build #5 (→ ch. 35) is the smallest honest slice of it you can ship — and the rest of this chapter is the horizon that slice is walking toward.