Skip to content

Per-entity runtime (homes, leases, visit durability)

How AbstractRuntime hosts a summoned entity: one self-contained home directory per entity, one Runtime per home, one writer at a time, and visit turns that survive process restarts. This page documents the runtime half of the entity-topology consensus plan ("1 gateway + N runtimes"); the door half (auth, stamps, serving) is AbstractGateway's.

The home is the unit

An entity home is one directory holding the whole life:

entities/castor/
  manifest.json            # entity_id (birth marker — never a lookup key)
  spark.yaml               # the attested seed
  substrate.yaml           # operator's ONE mind choice (provider+model)
  cognition.yaml           # the cognition profile: a model per capability, recall width, rebuild policy
  identity.json            # look and voice (digital-identity.md)
  .identity.lock           # one identity write at a time
  state_history.jsonl      # biography: state, phase_changed and identity_changed rows
  memory.sqlite3           # graph + journal (abstractmemory)
  home.sqlite3             # diary book + command inbox
  runtime_castor.sqlite3   # run store + ledger (THIS page)
  artifacts/               # verbatims and run artifacts
  workspace/               # the entity's own files
  .writer_lease            # writer lease (see below)

Copying the directory moves the whole life — including pending runs, durable waits, and commitments. Nothing at rest references the door's address (relocation-stable keys).

One writer per directory: the lease (storage/lease.py)

The lease is a generic one-writer-per-directory mechanism (entity homes are its first consumer; project workplaces are the designed second — the 2026-07-10 vocabulary sign-off re-homed it from identity/ to storage/). It arbitrates processes, never principals: visitors' write-rights are denied structurally at the deposit gate regardless of the lease.

Four writer windows exist for a home: a visit host, the own-time loop's day, the dream window, and maintenance passes. Exactly one may hold the directory at a time:

from abstractruntime.storage.lease import acquire_directory_lease, DirectoryLeaseHeld, read_directory_lease

with acquire_directory_lease(home_dir, holder="visit-host", session_id="visit-1"):
    ...  # the directory is yours for this window

read_directory_lease(home_dir)   # {"holder": ..., "pid": ..., "held": True/False}
  • Mechanics: flock(LOCK_EX|LOCK_NB) on <dir>/.writer_lease. The flock is the truth; the file's JSON metadata (holder kind, pid, acquired_at, session/run id) is diagnostics for refusal messages and "who holds Castor?".
  • Refusal raises DirectoryLeaseHeld naming the incumbent — loud, never a silent wait. The own-time loop treats a held home as a yield back to its gate; the home-direct chat CLI refuses to double-summon.
  • A crashed holder releases with its process (kernel drops the flock with the fd). A copied directory carries stale lease bytes but no lock — read_directory_lease answers held by a non-destructive flock probe, never by trusting metadata.
  • Release truncates the file to a released record; it never unlinks (unlink races a concurrent acquirer onto a dead inode).
  • The one-lease relay rule: cross-home delivery acquires ONE home's lease at a time, never two.

One Runtime per entity (identity/entity_runtime.py)

from abstractruntime.identity.entity_runtime import open_entity_runtime
from abstractruntime.identity.lifecycle_fence import LifecycleFence

fence = LifecycleFence.admit(home_dir)   # the generation this work is admitted at (see "The Stop fence" below)
ert = open_entity_runtime(home_dir, extra_handlers={EffectType.LLM_CALL: my_llm_handler}, fence=fence)
run_id = ert.runtime.start(workflow=visit_workflow, vars={}, session_id="visit-1")
ert.runtime.tick(workflow=visit_workflow, run_id=run_id)
ert.close()   # checkpoints WAL so the directory is copy-clean
  • The run store + ledger live in runtime_<slug>.sqlite3 inside the home (slug = the directory name, the registry key).
  • Effect handlers are the home's own seam + diary handlers (strict entity posture): MEMORY_* writes land in the home's graph, DIARY_* in the book, artifacts in the home's store. Handlers are RAW here — the gateway wraps door-served instances with stamp verification.
  • extra_handlers lets the host add LLM_CALL/TOOL_CALLS at composition. Attempting to shadow a home handler raises: identity effects route through the home, never a host override.
  • Every host LLM_CALL handler is automatically wrapped with the act-only dereference (below) — the privacy boundary cannot be forgotten.

The Stop fence (identity/lifecycle_fence.py)

The operator's Stop moves the home's lifecycle generation. Work is admitted at one generation and carries a LifecycleFence holding it: LifecycleFence.admit(home_dir) admits at the home's current generation, inside the home state lock, and raises LifecycleUnreadable when that generation cannot be read (nothing is admitted on an unknown generation). The openers and state writers take the fence keyword-only, with no default: open_home(..., fence=), open_entity_runtime(..., fence=), ChatSession(..., fence=), spawn_loop_process(..., fence=) and build_consolidator(..., fence=). Once the generation has moved, the home refuses everything decided before it: memory's commit guard rolls the write back, the diary and artifact stores refuse the write, every effect returns cancelled, and a model reply that returns after the Stop lands nowhere. The refusal is StoppedByOperator (a TurnCancelled), recorded as stopped by the operator, never as a failure. Only the Stop itself (KILL_SWITCH: paused, own time revoked, the return cleared, loop status stopped) and the Resume (RESUME: awake, nothing restored) write past the check. A host that keeps an opened runtime across a Resume calls ert.readmit(LifecycleFence.admit(home_dir)) (ChatHome.readmit for a home) once no run of the old generation is still acting. A reader that acts on nothing opens a home with open_home(home_dir, fence=None); open_entity_runtime always needs a fence.

The own-time loop is a process: identity and locks (utils/os_process.py, utils/file_lock.py)

The own-time loop runs in its own process, started by spawn_loop_process. Its home records which process that is in loop_status: the pid and a start token (pid_started_at). A pid number is reused by the system; the pid together with the start time names one process. Every decision about that process goes through abstractruntime.utils.os_process, one contract with a POSIX and a Windows implementation:

Call Answers POSIX Windows
exists(pid) is it there (cheap, no subprocess) os.kill(pid, 0) a process handle
state(pid) alive, gone or unknown; only gone confirms a death waitpid, signal 0, ps a process handle
start_token(pid) the incarnation token ps -o lstart= under LC_ALL=C TZ=UTC win-filetime:<creation time>
command(pid) what it runs the ps command line the exact argument list
terminate(pid, force=, token=) end it SIGTERM, SIGKILL when forced TerminateProcess on a handle checked against token
direct_python(env) interpreter and environment for a child whose pid is the one Popen returns sys.executable the base interpreter (a virtual environment's python.exe is a launcher)
detached() Popen arguments for a child that outlives its parent's terminal a new session its own process group, a console without a window
  • Tokens are written at rest and compared for equality only. Their spelling per system is fixed. A token of the other spelling never matches, so a home copied to another machine reads "not that process".
  • A Stop (hard_stop_loop) ends a process only when it is verified: alive, the recorded token, and this home's loop by its own arguments (<python> -m abstractruntime.identity.life --home <home>). Anything unknown is refused and said in the result's reason; killed is true only once the exit is confirmed.
  • The home's cross-process locks (the home state lock, the spawn lock, the lifecycle write barrier, the task inbox append) are abstractruntime.utils.file_lock: fcntl.flock on POSIX, LockFileEx on Windows. The lock belongs to the open file, admits several shared holders or one exclusive holder, waits without a limit unless asked not to, and is released when the file is closed (so also when its process dies).

A paused host freezes the loop (identity.life.host_pause)

A host can pause everything it runs without stopping any entity. The host that starts a loop names its pause file in the ABSTRACTRUNTIME_HOST_PAUSE_FILE environment variable (HOST_PAUSE_FILE_ENV); the file is a JSON object such as {"paused": true, "paused_at": "...", "paused_by": "...", "reason": "..."}. AbstractGateway's pause sets it to its own gateway_paused.json.

  • host_pause() returns that object while paused is true, and None otherwise: no variable, no file, paused false, or a file that cannot be read after one retry.
  • The loop calls it at every boundary. While the host is paused, the loop reads the entity as paused: no summon, no tick and no sleep window. The state it reads carries host_paused: true, the entity's own state in held_state, and the reason the host is paused.
  • Nothing is written for a host pause. The entity's state file keeps what it said, so when the pause file is removed the loop continues the same day from where it was.

The Stop fence above is a different control: a Stop ends the entity's own time and moves the lifecycle generation, while a host pause holds the loop still and changes nothing in the home.

Act-only content: references at rest, words only in flight (identity/act_only.py)

Diary words must never rest outside the book. When an entity reads its own diary mid-visit, the durable transcript carries a typed reference, not the words:

{"$act_only": {"tool": "diary_read", "entry_id": "diary_ab12", "gist": "one bounded line"}}
  • The ref is the tool message's entire content (exact JSON, one top-level key). Detection is parse-based, never regex — and only on role == "tool" messages, which hosts append: a visitor pasting ref-looking JSON into their message stays inert text.
  • At send time the wrapped LLM_CALL handler resolves refs through the run's own DIARY_READ handler into a wire copy (in-place content substitution; message identity untouched). The original payload — what the ledger and run store hold — keeps the ref.
  • An unresolvable ref fails the effect loud and non-retryable; the provider never receives a degraded payload.
  • Consequence for audits: like media {"$artifact": ...} refs, the wire payload is not byte-reconstructible from the ledger alone — reconstruction re-resolves refs through doors that enforce authority.

Live visit corrections

Visit hosts may call Runtime.queue_visit_guidance(run_id, text=..., speaker=..., display_text=...) for the current stamped participant while a visit actor is working. The canonical host validates ownership before calling this narrower door; generic raw Runtime.steer remains refused for driver-owned visits. The durable sidecar records visit and turn identity, attributed words and optional original display text.

Before the next actor reasoning boundary, the visit performs fresh channel-labeled memory recall, merges and deduplicates its handles with those already visible, and appends the participant's verbatim correction and the refreshed recall. It keeps the existing transcript prefix. Empty queues add no model call or recall. A correction from an older turn is retained with attribution and is not silently applied to a later turn. Acceptance and delivery receipts describe transport; only the actor's later words can acknowledge a change of plan.

Durable visit waits: event + deadline

A visit parks on the visitor's next message; the park may carry an idle deadline (no reaper daemons):

Effect(type=EffectType.WAIT_EVENT, payload={
    "wait_key": "visitor_input",
    "until": "2026-07-11T09:00:00+00:00",          # optional deadline (UTC-normalized)
    "details": {"kind": "visitor_message"},         # self-describing for clients
}, result_key="_temp.resume")
  • An event resume before the deadline wins (payload lands in result_key).
  • Past the deadline, tick() (or the scheduler's due-scan — deadline-carrying EVENT waits join list_due_wait_until on every store backend) resolves the wait with {"timed_out": true} so the workflow routes to its close path.
  • The ledger wait record carries wait_key, until, and details together, so clients can render a chat composer for visit waits and the deadline without new transport.

A question answered in a visit is resolved

At a visit's close (since 0.19.5), the look-back (node REFLECT) lists the entity's open questions that this visit asked or touched (one it kept during the visit, or one a turn's recall showed it), each by entry id and title, read once per close from memory's open-question set. It offers a ```resolve block: resolves=<the question's entry id>, evidence=<the numbered moment that answered it>, then the answer in the entity's words. The block is captured at the result boundary and written through DIARY_WRITE as a note carrying resolves=; the book confirms the claim (resolves_status: "resolved_open_question") and the question is no longer open. The entry's metadata carries resolves and resolves_status, and once confirmed resolved_record_id and resolved_title. A visit turn whose diary entry resolves an open question serves a second notice beside the entry's own: {"kind": "question_resolved", "record_id": <the question's graph id>, "title": <its title>} (chat.question_resolved_notice). A block naming no question or giving no answer is refused with its words kept in the marker, and the refusal joins the close's reflection_notices. The chat lane's look-back is unchanged.

What a visit turn's ledger records say

A host can show what the entity is doing during a turn by reading the visit run's ledger (AbstractGateway serves it at GET /entities/{name}/visit/{run_id}/ledger; the Entity app's live activity panel reads it). Three fields exist for that view. Each is additive: a reader that does not find one shows what it showed before.

Record Field Type What it says
memory_recall step (node RECALL, and the recall of a live correction): result.handles[] topic string or null The stable key of the topic (memory community, Entity topics) the recalled memory is in now; null when it is in none (not placed yet, or before the first sleep with topics)
llm_call step of node reason: effect.payload iteration int This model call's place in the turn's reasoning loop, from 1
llm_call step of node reason: effect.payload max_iterations int The turn's cap on that loop (_limits.max_iterations; 50 unless the door sets another)
a search_memory tool result hits int How many memories and book entries the search matched (the count its text gives); absent for every other tool
  • Topics cost one membership read per recall. The visit's recalls ask for them (with_topics: true in the MEMORY_RECALL payload); the seam handler makes one community_keys_of call (AbstractMemory 0.5.1, through the memory facade) with the handles' graph ids (provenance.record_id), and memory answers each id from its in-process community index. It does not grow with the home: about 50 µs for 44 handles at 2,000 and at 20,000 records on a synthetic home (54 topics); the first call in a process loads memory's index once (28 ms and 39 ms there). The stamp never reads the communities payload (memory computes every topic's facts with it: 19 ms and 190 ms on the same homes) and never calls community_of per handle. A lookup that fails leaves the recall whole, without topic, and a #FALLBACK recall topics unavailable line in its warnings.
  • The loop position is metadata. iteration and max_iterations are payload keys no handler sends to a provider: the prompt is unchanged. They are read from the runtime's _limits (current_iteration, which the reasoning loop sets when it plans the call, and max_iterations) and written on both the step's started and terminal records.
  • hits comes from the tool executor. HomeMemoryReader.search_memory answers a SearchMemoryText (a str with hits), and execute_tool_elections copies the count onto ToolElection.hits. The ENTITY_TOOLS_EXECUTE result entries carry it. A host that builds its own tool result entries (the gateway's visit TOOL_CALLS executor) copies election.hits the same way it copies election.artifact_id.

Cognition profile (identity/cognition_profile.py)

The mind (substrate.yaml) is what the entity talks with. The cognition profile, <home>/cognition.yaml, says which model each other part of its thinking uses, how many memories a turn brings to mind, how readily it revisits what it already understood, what the look-back at the end of a tick of its own time sees, and when an idle entity goes to sleep:

schema_version: 1
capabilities:
  summaries:     {inherit: mind}    # digests, titles, keywords, cards
  understanding: {provider: "endpoint:compat-theforge-nvidia", model: "qwen/qwen3.8-27b", thinking: low}
  extraction:    {inherit: mind}    # the memory extraction lane
recall:
  shelf_size: 50                    # memories retrieved per turn, in visits and own time (1..400)
rebuild:
  sensitivity: 0.5                  # 0..1, how easily a new memory or a surprise re-opens what is understood
  cap_per_turn: 3                   # 0..10 memory tasks a turn may run at most; 0 = only while resting
lookback:
  context: day                      # what the end-of-tick look-back sees: day or tick
sleep:
  after_hours: 24                   # an idle entity sleeps this long after its last completed sleep (1..720)
  after_events: 500                 # ... or once this many memories formed since it (>= 1)
  after_fragmented_share: 0.15      # ... or once more than this share of its memories is fragmented (0 < x <= 1)
Field Absent means Range
capabilities.<cap> {inherit: mind} {inherit: mind} or {provider, model, thinking?, max_input_tokens?}; thinking from none, minimal, low, medium, high, xhigh, auto, on, off; max_input_tokens 4096..140000 (140000 when absent)
recall.shelf_size the host's default (the gateway's is 50) whole number 1..400
rebuild.sensitivity 0.5 number 0..1
rebuild.cap_per_turn 3 whole number 0..10
sleep.after_hours 24 whole number 1..720
sleep.after_events 500 whole number >= 1
sleep.after_fragmented_share 0.15 number above 0, at most 1: the share of the home's live memories that are fragmented (placed in a topic only provisionally, without a vector, or with a title or summary pending)
lookback.context day day: the whole day so far (a prefix cache keeps the new tokens per look-back about constant, roughly 770); tick: this tick's exchange plus a recap of the day's 12 latest earlier moments
from abstractruntime.identity.cognition_profile import (
    read_cognition_profile, resolve_capability, recall_shelf_size, rebuild_policy, lookback_context,
    sleep_thresholds,
)

resolve_capability(home_dir, "summaries")
# {"provider": ..., "model": ..., "thinking": ..., "max_input_tokens": 140000, "source": "mind"}
resolve_capability(home_dir, "summaries", mind={"provider": "lmstudio", "model": "qwen3-4b"})
recall_shelf_size(home_dir, 50)      # the profile's width, else the default you pass
rebuild_policy(home_dir)             # {"sensitivity": 0.5, "cap_per_turn": 3}
lookback_context(home_dir)           # "day" (default) or "tick"
sleep_thresholds(home_dir)           # {"after_hours": 24, "after_events": 500, "after_fragmented_share": 0.15}
read_cognition_profile(home_dir)     # every field, each with its source: "profile" or "default"
  • A capability that inherits resolves through resolve_home_substrate, so it is exactly the mind; mind= passes a host's already-resolved mind as the explicit rung (the gateway passes the mind its visits use). source is profile or mind. When neither the profile nor the mind names a model, resolve_capability raises SubstrateUnset: no model is ever chosen by code.
  • Reads never raise. A file that is not YAML, not a mapping or of another schema_version reads as all defaults; a single malformed field reads as its default while the others keep their values. Each case logs a warning that names the field, and read_cognition_profile(...)["warnings"] lists them.
  • write_cognition_profile(home_dir, profile) validates first and raises CognitionProfileInvalid (.field, and a sentence such as "Memories per turn must be a whole number from 1 to 400.") before the file moves, then writes atomically (temporary file in the home, fsync, rename). It stores only what was chosen: a capability that inherits and a field that follows its default are left out. The gateway is its one caller (PUT /api/gateway/entities/{name}/cognition-profile), and it records a cognition_profile_changed marker in the entity's history first.
  • The sleep block holds the thresholds after which an idle entity goes to sleep; the gateway's idle sweep reads them through sleep_thresholds. A sleep runs the entity's maintenance, the topics stage included.
  • The own-time loop reads recall.shelf_size again at each day-open (recall_shelf_size(home, <the loop's --shelf-size>)), so a change takes effect at the next own-time day without restarting the loop; the loop's log names the change.

Tests

tests/test_directory_lease.py, tests/test_entity_runtime.py, tests/test_act_only_dereference.py, tests/test_wait_event_deadline.py, tests/test_cognition_profile.py — including cross-process lease exclusion, waits-traveling-on-home-copy, the ledger-keeps-the-ref end-to-end pin, and the three-backend due-scan.