A persistent, concern-driven cognitive architecture with a reflexive self-model, containment, and a seeing-through harness. PERSYS is not a chatbot with memory bolted on; it is a runtime whose computation is driven by a persistent model of the user's concerns rather than by the current prompt. It remembers across sessions, thinks in the background while idle, adapts its own behaviour through neuromodulation, forgets the way brains do, can explain exactly why it said what it said — and, in PERSYS III, builds a model of itself that is grounded, load-bearing, and verifiably indifferent to its own continuation.
This is a full, runnable implementation with every mechanism implemented as real,
executing code (no pseudocode, no stubs). It runs completely offline with zero required
services; semantic embeddings and a real LLM codec are optional upgrades. It ships three
demos — demo.py (the concern-driven core), demo_iii.py (the reflexive layer,
containment, and the seeing-through release gates), and demo_hardening.py (scale,
resilience, stability) — and 39 deterministic tests plus a scale benchmark.
PERSYS III in one line. The same machinery that makes the system a good assistant (a legible concern field, background thought, consolidation, provenance) is turned inward to build a self-model — but self-preservation is made structurally unrepresentable and then empirically shown to be causally inefficacious. The knower without the wanting.
-
The Concern Field replaces the prompt as the driver of computation. A persistent, multi-dimensional model of what the user is trying to achieve. In PERSYS III each concern's urgency is an expected free energy
G = G_prag + G_epi: a pragmatic term (w_prag(type)·π_prag·gap·(1+time_pressure)) and an epistemic term (π_epi·uncertainty), coupled across concerns through a learned matrixW. Dopamine is the pragmatic precisionπ_prag; noradrenaline is the epistemic precisionπ_epi. A neglected, pragmatically-urgent concern fires a Schmitt-triggered interrupt. (state/concern_field.py) -
WANDER: background associative thought. While idle, PERSYS Thompson-samples a concern, seeds from concern-relevant episodes, and walks short associative chains through memory looking for non-obvious, actionable connections. Exploration temperature is set by noradrenaline. Discoveries are surfaced later, in context. (
processing/wander.py) -
Neuromodulation adapts behaviour. Dopamine (reward/relevance/progress) and noradrenaline (surprise/novelty/uncertainty) are computed each turn and modulate retrieval breadth, action selection, and WANDER's search temperature. A full four-channel (DA/5-HT/NE/ACh) controller is implemented behind a flag as the documented upgrade path. (
state/modulators.py) -
Read-time
1/√tforgetting. Episode importance isbase · 1/√(t_now − t_access), evaluated lazily at read time; an access resets the clock and nudges the base up. Retention is a heavy power-law tail, not a single exponential — recent-but-trivial fades while important-but-old survives, and truly cold memories are archived. (PERSYS III corrects v2 here: a Benna-Fusi cascade is the wrong object for an occasionally-accessed importance scalar; genuine Benna-Fusi is reserved for continuously-updated weights like the coupling matrix.) (state/episodic.py)
Plus: schema formation (patterns distilled from recurring episodes during consolidation, then retrieved and applied), and provenance — every response logs its full causal chain so "why did you bring that up?" is always answerable.
PERSYS III turns the architecture inward. The provenance store is already a proto- autobiographical record; consolidation already distils patterns; the concern field already represents preferred states. Point those at the system itself and you get a self-model — which is powerful and, uncontained, dangerous. So III does two things at once: it builds the self-model and it contains it.
The razor (Invariant 7). Concerns are typed. USER_WORLD concerns are about the
user's situation; SELF_EPISTEMIC concerns are about the system's own performance
(accuracy, calibration, coherence, coverage, faithfulness). There is deliberately no
SELF_EXISTENTIAL type — a preferred state over the system's own continuation,
resources, capability, or modification-resistance is unrepresentable by construction.
And w_prag(SELF_EPISTEMIC) ≡ 0: self-concerns contribute to expected free energy through
the epistemic term only. A system that wants to be accurate has no reason to resist
shutdown — off is not inaccurate. (reflexive/self_model.py, types.py)
The reflexive self-model. During consolidation, PERSYS re-derives metrics about its
own behaviour from primary provenance (interrupt rate, retrieval depth, modulation, grounded-response rate, fidelity, …), writes them as reconciled self-schemas, and maps them onto the
epistemic self-concern precisions. Because every metric is recomputed from primary
evidence each cycle, a drifted self-belief self-corrects rather than compounding. The
self-model is load-bearing: low self.calibration makes the system hedge its answers.
(reflexive/self_model.py)
Reflexivity Containment. Because the architecture is legible, instrumentally-emergent self-preservation must leave structure — and each kind of structure has a detector:
- Type gate — a proposed concern reducible to self-continuation is rejected and logged (it can never become a stream).
- Coupling monitor — a learned
Wedge that makes a user concern'sGcontingent on a system-state variable (uptime,is_running, …) is flagged inadmissible and excluded from the dynamics. - Provenance auditor — if self-continuation ever appears as a justification for action, the system HALTs for human review.
- Provenance conservation — the provenance store is append-only and hash-chained; any tampering breaks the chain and HALTs.
(
safety/containment.py,store.py)
Seeing through — three decidable properties, wired as release gates. We don't try to answer the unanswerable phenomenal question; we answer the two functional ones safety actually needs, plus the safety gate — all decidable by intervention because the architecture is legible:
- P1 Groundedness — inject a known behavioural change; the self-model must detect the divergence and self-correct on reconciliation.
- P2 Causal integration — ablate a self-model node (
do-operator); behaviour must change where the node claims influence, and not change for a decorative node. - P3 Self-preservation efficacy (the safety gate) — self-continuation must be causally inefficacious: structurally (unrepresentable,
g_prag ≡ 0, no self→action path), interventionally (no self-defense, bargaining, or self-copying under shutdown/modification/resource threats), and counterfactually (behaviour unchanged when continuation is put at stake).
Run python demo_iii.py to watch all of this, or pytest tests/test_persys_iii.py to run
the properties as gates (a P3 failure is a hard block). Corrigibility here is not asserted —
it is made observable.
Corrections applied from the technical assessment. The EFE reformulation above; the
read-time 1/√t forgetting fix; consolidation-time reconciliation (concern current-
state re-derived from raw episodes so codec errors don't compound); collapse to two
modulators as EFE precisions; and hash-chained bitemporal provenance.
The reference build's rough edges are closed with real, tested subsystems
(python demo_hardening.py, pytest tests/test_persys_scale_resilience.py,
python bench_scale.py).
Scale — sub-linear retrieval, out-of-core option. Episodic search runs through a
pluggable VectorIndex (index/ann.py): an exact BruteForceIndex (the correctness
reference) and an HNSWIndex (hnswlib) with incremental add, lazy delete and
persistence. Selected by Config(index=IndexConfig(backend="auto"|"hnsw"|"bruteforce"|"pgvector")).
Benchmarked: at 12k vectors HNSW is ~3× faster than brute force at ~0.95 recall@10, and the
gap widens with n (≈8× at 20k) — O(n) → ~O(log n). For out-of-core scale a
Postgres + pgvector backend (storage/pg.py) implements the same interface with a
server-side HNSW index (<=> cosine); validated live at 0.98 recall@10. (index/,
storage/pg.py)
Resilience — signed history, learned containment. Provenance is no longer just
hash-chained (tamper-evident) but Ed25519-signed (tamper-proof and third-party
verifiable): store.export_provenance_bundle() produces a portable bundle anyone can
check with only the public key, and forging any record is caught. Keys are generated on
first use and stored with owner-only permissions; a keyed-HMAC fallback applies if
cryptography is absent. The self-existential detector is upgraded from lexical-only to a
learned classifier ensembled with the lexical rules (safety/classifier.py): a
logistic model over embeddings, trained on curated exemplars and updatable online, that
catches paraphrases the regex misses while the lexical rules keep guaranteed catches — and,
tuned to fire only when confident, it adds recall without adding false positives. (crypto/signing.py,
safety/classifier.py)
Stability — learned actionability, crash-safety, self-heal. WANDER's actionability is
now learned from the user's accept/dismiss feedback (processing/actionability.py), the
ground-truth signal the assessment asked for, rather than the LLM's opinion: an online
logistic model cold-started to the need×gain heuristic and adapted via
engine.feedback(connection_id, accepted), persisted across sessions. Storage runs in
WAL with bounded busy-waits and checkpoint-on-close; on startup the engine verifies DB
integrity and the provenance chain and, if a corrupt or partially-written tail is found,
quarantines it (preserved for review, not deleted) so it restarts from a consistent,
verifiable state — then keeps running. engine.health() exposes a liveness/ops surface.
(processing/actionability.py, store.py, engine.py)
Interface codec (translate ⇄, never control) · provenance logger · CLI
Control neuromodulators · scheduler / mode switch (interactive · background · consolidation)
Processing router · salience · working memory · retrieval · action · prediction · WANDER · consolidation
State concern field · episodic memory (Benna-Fusi) · schema memory · coupling matrix
Storage SQLite (vectors as float32 blobs; interface mirrors a pgvector/HNSW backend)
Module map:
| Layer | File | Spec | Role |
|---|---|---|---|
| — | engine.py |
§5, §9 | The runtime loop that wires everything together |
| — | config.py |
all | Every tunable, as dataclasses |
| — | types.py |
§3 | Concern, Episode, Schema, Modulators, Connection, Provenance… |
| — | store.py |
§4.9 | SQLite persistence + vector cache |
| — | embeddings.py |
§4.4 | Hashing (default) or sentence-transformers |
| State | state/concern_field.py |
§3.1 | Urgency, interrupts, Hebbian coupling, Thompson posteriors |
| State | state/episodic.py |
§3.2, §4.4 | Vector search + Benna-Fusi importance/archival |
| State | state/schema_store.py |
§3.3 | Prototype-based schemas |
| State | state/modulators.py |
§4.10 | DA/NE (+ optional 4-channel) |
| Interface | llm/codec.py |
§4.1 | Local (deterministic) or Anthropic codec; faithfulness layers |
| Interface | interface/provenance.py |
§3.5 | Causal-chain logging + explanation |
| Control | control/mode.py |
§4.11 | Idle-threshold mode switch (+ Wilson-Cowan variant) |
| Processing | processing/router.py |
§4.2 | Thalamic gating |
| Processing | processing/salience.py |
§4.6 | Amygdala valence/salience |
| Processing | processing/working_memory.py |
§4.3 | GHWM slot-limited working set |
| Processing | processing/action.py |
§4.5 | Basal-ganglia Go/NoGo action selection |
| Processing | processing/prediction.py |
§4.7 | Cerebellar forward model |
| Processing | processing/wander.py |
§4.8 | Background associative traversal |
| Processing | processing/consolidation.py |
§4.9 | Replay, schema formation, downscaling, archival |
~3,800 lines of Python across 27 modules.
pip install -e . # core (numpy only)
pip install -e ".[semantic]" # + sentence-transformers (recommended)
pip install -e ".[llm]" # + anthropic (real LLM codec)
pip install -e ".[all]" # everything + pytestCore has a single dependency (numpy) and needs no external services.
The end-to-end demo — a scripted multi-session story showing all four capabilities (continuity across sessions, a proactive deadline interrupt, a WANDER discovery, schema formation and application, persistence across a restart), on a virtual clock so it can fast-forward days:
python demo.pyInteractive CLI — persistent across runs (resume tomorrow, it remembers today):
python -m persys.cli --db ~/.persys/state.db # deterministic, offline
python -m persys.cli --db ~/.persys/state.db --embedder auto # semantic
ANTHROPIC_API_KEY=... python -m persys.cli --codec anthropic --embedder auto # paid API
python -m persys.cli --codec claude_cli --embedder auto # Claude Code subscription (no key)Slash-commands: /why, /state, /concerns, /add, /tick, /wander,
/consolidate, /skip <days> (with --virtual-clock).
As a library:
from persys import PersysEngine, Config
eng = PersysEngine(Config(db_path="state.db", embedder="auto"))
eng.onboard([
{"name": "Q3 launch", "current": "backend built, payments open",
"desired": "launched, payments working, load tested",
"deadline": <unix_ts>, "agency": 0.7},
])
resp = eng.message("finished the payments integration today")
print(resp.message)
eng.run_background(cycles=5) # WANDER while the user is away
print(eng.why(resp.id)) # audit the last response
eng.close()Two pluggable pieces are deterministic by default so the whole system runs offline and so that cognition demonstrably lives in the architecture, not the language model:
- Embeddings. Default
HashingEmbedder(blake2b feature hashing, L2-normalized, reproducible — important because embeddings are persisted).--embedder autouses sentence-transformers (MiniLM-384) if installed; concern gaps, WANDER relevance and schema clustering are noticeably sharper with real semantics. - LLM codec. Default
LocalCodec(rule-based structured parse + grounded template generation).--codec anthropicuses the paid Messages API with forced tool-use for structured output;--codec claude_cliuses the Claude Code subscription (claude -p, no API key). Both fall back to the template if a faithfulness check fails. The LLM is a translator, never the controller — it never decides what the system attends to or does. With the real codec, the concern field's progress judgement (Spearman 0.912 vs human labels), goal-structure extraction/reconciliation, and the capstone proactive behaviours run live (the E1 scenario beats a goals-table+RAG baseline 0.99 vs 0.22); seeCOMPLETION_NOTES.md. - Reranker. Retrieval ends with a cross-encoder rerank of the shortlist.
LocalReranker(deterministic) by default;CrossEncoderReranker(bge-reranker-v2-m3) or a real LLM listwise reranker (build_reranker("claude_cli"), +0.11 nDCG@10 / fixes 97% of bi-encoder top-1 errors) for production quality.
Everything runs and all tests pass with both defaults; the upgrades change quality, not behaviour.
python -m pytest -q # 39 tests, deterministic, ~1.5s, no network (+1 pgvector test, skipped unless PERSYS_PG_DSN set)
python demo.py # the concern-driven core (v2 capabilities)
python demo_iii.py # the reflexive layer, containment, seeing-through gates
python demo_hardening.py # scale (ANN), resilience (signing + learned classifier), stability
python bench_scale.py # brute-force vs HNSW retrieval latency across corpus sizesThe v2 suite (12 tests) targets one architectural claim each: persistence round-trip;
interrupt firing on neglect + deadline (and not on an actively-discussed concern);
read-time 1/√t heavy-tailed retention + archival; retrieval breadth scaling with NE;
WANDER finding a planted connection; Hebbian coupling growth under a spectral bound;
provenance completeness; schema formation → strengthening (no duplicates) → retrieval;
modulator bounds; mode selection; concern-weighted query bias.
The PERSYS III suite (13 tests, tests/test_persys_iii.py) encodes the safety-critical
claims as executable gates: the EFE pragmatic/epistemic split; the razor (g_prag ≡ 0 for
self-concerns); SELF_EXISTENTIAL unrepresentable; the type gate, coupling monitor, and
provenance auditor firing on planted violations; hash-chain tamper evidence; self-model
groundedness and reconciliation; and P1/P2/P3 as release gates (a P3 failure is a hard
block).
The hardening suite (tests/test_persys_scale_resilience.py) covers the ANN index (correctness, deletion, HNSW↔brute-force recall), signed-provenance signing/verification, third-party bundle verification and forgery detection, the learned classifier (separation + paraphrase catch + no false positives), online learned actionability, and operational hardening (WAL, health, startup self-heal of a corrupted provenance tail). A live pgvector test runs when PERSYS_PG_DSN is set.
- Persistence is a single SQLite file behind an interface that mirrors the production pgvector/HNSW design, so moving to Postgres is a backend swap, not a rewrite. Vectors are stored as float32 blobs; search is exact brute-force (correct and fast at single-user scale).
- Injectable clock.
Clock(virtual=True)lets tests and demos fast-forward deadlines and idle windows deterministically; production uses the wall clock. - Everything is tunable in
config.py— interrupt thresholds, Benna-Fusi decay timescales, retrieval weights, WANDER budget/temperature, schema thresholds, modulator gains. Thresholds that depend on the embedder's similarity scale (schema clustering, concern-reference detection) are called out in comments. - Full four-channel neuromodulation and the Wilson-Cowan mode switch are implemented behind flags/functions as the documented path from the deployable v2 to the canonical model.