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
DirectoryLeaseHeldnaming 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_leaseanswersheldby 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>.sqlite3inside 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_handlerslets the host addLLM_CALL/TOOL_CALLSat composition. Attempting to shadow a home handler raises: identity effects route through the home, never a host override.- Every host
LLM_CALLhandler 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'sreason;killedis 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.flockon POSIX,LockFileExon 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 whilepausedis true, andNoneotherwise: no variable, no file,pausedfalse, 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 carrieshost_paused: true, the entity's own state inheld_state, and the reasonthe 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 onrole == "tool"messages, which hosts append: a visitor pasting ref-looking JSON into their message stays inert text. - At send time the wrapped
LLM_CALLhandler resolves refs through the run's ownDIARY_READhandler 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 joinlist_due_wait_untilon 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, anddetailstogether, 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: truein theMEMORY_RECALLpayload); the seam handler makes onecommunity_keys_ofcall (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 callscommunity_ofper handle. A lookup that fails leaves the recall whole, withouttopic, and a#FALLBACK recall topics unavailableline in itswarnings. - The loop position is metadata.
iterationandmax_iterationsare 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, andmax_iterations) and written on both the step's started and terminal records. hitscomes from the tool executor.HomeMemoryReader.search_memoryanswers aSearchMemoryText(astrwithhits), andexecute_tool_electionscopies the count ontoToolElection.hits. TheENTITY_TOOLS_EXECUTEresult entries carry it. A host that builds its own tool result entries (the gateway's visitTOOL_CALLSexecutor) copieselection.hitsthe same way it copieselection.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).sourceisprofileormind. When neither the profile nor the mind names a model,resolve_capabilityraisesSubstrateUnset: no model is ever chosen by code. - Reads never raise. A file that is not YAML, not a mapping or of another
schema_versionreads 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, andread_cognition_profile(...)["warnings"]lists them. write_cognition_profile(home_dir, profile)validates first and raisesCognitionProfileInvalid(.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 acognition_profile_changedmarker in the entity's history first.- The
sleepblock holds the thresholds after which an idle entity goes to sleep; the gateway's idle sweep reads them throughsleep_thresholds. A sleep runs the entity's maintenance, the topics stage included. - The own-time loop reads
recall.shelf_sizeagain 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.