A graph-based abstract relational world model in pure Python, designed as a reasoning component for AGI / agent systems. Represents the world as entities (nodes) with typed properties and relations (directed labeled edges); supports five core cognitive capabilities:
| Capability | Where |
|---|---|
| State tracking | WorldModel facade with entity/relation CRUD + history |
| Prediction | Predictor.predict(action) — what happens next, without mutation |
| Counterfactual reasoning | what_if_different_action, what_if_property_change |
| Planning | Planner — A* search with optimistic handling of probabilistic effects |
| Causal inference | CausalGraph — DAG, d-separation, Pearl's do-operator |
On top of these, a values & character substrate ships a moral veto layer, wisdom rollout, honest agent contract (calibrated three-state semantics), curiosity drive, judgment of character (credibility + deception detection), metacognition, the six H43 interneuron-dial knobs over inference, an H14 wake/sleep mutation-window regime, H4 novelty-gated consolidation, the H12/H13/H21 three-STDP decomposition, and bootstrapping infrastructure (six-critic ensemble, mutation sandbox with sleep-window enforcement, sleep-mode prompt search, heuristic-from-library swap). The architecture is "values load-bearing" — moral / honesty / wisdom / judgment constraints are first-class objects sharing the same evaluation machinery as everything else, not wrappers added at the end. See docs/agi-design-discussion.md for the design reasoning and docs/aspirations.md for the long-term direction.
A closed-loop sim-env driver (blocks-world) plus a curated benchmark suite plug the substrate into an end-to-end test bed; the BenchmarkCritic is wired through to mutation-gating, and an integration test demonstrates the bounded-self-modification loop (acceptance of a benign mutation, rejection of an adversarial one) composing every piece.
Also includes a Lean integration (Tier 0 + 1: theorems as first-class entities with a configurable verifier — stub by default, optional subprocess to a Lean binary; early Tier 2 tactic-script actions compile to verifier-facing proof attempts, with parsed Lean feedback snapshots and snapshot-structured proof-state plans for diagnostics / unsolved-goal context), a theorem-ablation smoke runner with an explicit false-proof-claim oracle, proof-history prediction prior, corpus-usage tracking, a composed question_full_with_retrieval mode, bounded worker controls for theorem/proof-state Lean runners, preregistered Lean-curriculum smoke package, a 20-problem proof-repair v1 package path, a publication-candidate local theorem-ablation package (human-review release gate currently blocked, 0/5 reviewer roles present; the result is a Bonferroni-corrected attempt-count sample-efficiency claim on a curriculum where pure question_full already solved 20/20 — not an additional-solves claim) with a separate retrieval-ablation diagnostic, a theorem-proving domain benchmark harness v0 with fail-closed readiness gates and external-JSON fixture support, a real miniF2F-lean4 external benchmark bind (pinned public checkout, uniform leak-proof generic-tactic candidates, machine-verified labels from a real Lean 4.24 + Mathlib pass, documented selection-bias coverage, and an honest null result for question-layer ordering on that bind), a finished Experiment 5 two-family empirical writeup/review package (claim supported, writeup-ready, release gate blocked), artifact-backed math capability ladder evaluation, originality/provenance gate, a standalone local theorem-corpus retrieval-proposer package, a larger Lean standard-library corpus originality screen, and math-domain architecture-ablation smoke runner, a science-domain safety gate plus role-specific human-review release-gate artifact, low-risk toy-physics correctness metrics, a GWOSC/GW150914 public-data metadata replication package, a real public-posterior consistency package, and a real public H1/L1 GWOSC strain-summary export with fail-closed v2 diagnostics that records official source/hash provenance while keeping raw data out of git, an MCP server so any MCP-capable LLM client (Claude Desktop, Claude Code, etc.) can drive the world model as a tool, an LLM natural-language parser that converts English descriptions to structured Action/CausalRule JSON, an optional Anthropic / Claude vision perception adapter behind the modality-neutral PerceptionAdapter protocol, and a bounded LLM-with-tool-use baseline adapter for empirical comparisons.
Pure Python, no runtime dependencies for the core. The current torch-capable Python 3.12 venv full-suite run reports 3638 passed and 1 skipped. The skipped test is the local-LLM live smoke unless WORLDMODEL_LOCAL_LLM_TEST=1 is set with a reachable local OpenAI-compatible endpoint; Lean-gated, h5py-gated, PyCBC-gated, and GPU retrieval tests all run in that environment. Optional h5py/numpy, PyCBC, local-LLM, and GPU retrieval stacks remain test-time / experiment-time extras, not core runtime dependencies.
# Python 3.10+
python -m venv venv
source venv/bin/activate
pip install -e . # core
pip install -e ".[dev]" # + pytest
pip install -e ".[dev,mcp,nlp]" # + MCP server + Anthropic SDK for NL parsing / vision
pip install -e ".[dev,preprint]" # + bundled Pandoc for preprint PDF packaging
pip install -e ".[dev,physics]" # + pycbc/h5py/numpy for the GWOSC public-data v2 strain + matched-filter path (requires_h5py tests)
pip install -e ".[dev,gpu]" # + torch/sentence-transformers for the learned GPU theorem-retrieval path (requires_gpu tests)The gpu extra pulls torch from the default PyPI index. For an older NVIDIA
driver (e.g. driver 470.x, which caps at CUDA 11.x), install a driver-matched
torch build first — pip install --index-url https://download.pytorch.org/whl/cu118 torch — then pip install -e ".[dev,gpu]"
for the rest. The gpu and physics stacks are optional and lazily imported
behind opt-in test markers; the core library has no runtime dependency on them.
from worldmodel import WorldModel
from worldmodel.core import (
Action, ActionEffect, ConditionType, EffectType,
Entity, Goal, GoalCondition, Relation,
)
wm = WorldModel()
wm.add_entity(Entity("alice", "person", {"has_book": True}))
wm.add_entity(Entity("bob", "person", {"has_book": False}))
wm.add_entity(Entity("book", "item"))
wm.add_relation(Relation.create("alice", "book", "owns"))
transfer = Action(
name="transfer",
preconditions=[GoalCondition(
ConditionType.RELATION_EXISTS,
{"source_id": "alice", "target_id": "book", "label": "owns"},
)],
effects=[
ActionEffect(EffectType.REMOVE_RELATION,
{"source_id": "alice", "target_id": "book", "label": "owns"}),
ActionEffect(EffectType.ADD_RELATION,
{"source_id": "bob", "target_id": "book", "label": "owns"}),
],
)
# Predict without mutating
prediction = wm.predict(transfer)
print(prediction.diff.added_relations)
# Apply
wm.apply_action(transfer)See examples/ for 11 runnable scripts covering rules, planning, probabilistic outcomes, counterfactual reasoning, rule learning, type hierarchies, numeric/temporal patterns, LLM rule proposer, end-to-end agent, and skill library.
Causal rules match on state patterns using ?variable binding, fire to a fixed point, and are priority-ordered. Rules can be probabilistic (probability < 1.0).
from worldmodel.rules import CausalRule, Condition, RuleConditionType, RuleEffect
rule = CausalRule(
name="gravity",
conditions=[
Condition(RuleConditionType.PROPERTY_EQUALS,
{"entity_id": "?x", "property": "supported", "value": False}),
],
effects=[
RuleEffect(EffectType.SET_PROPERTY,
{"entity_id": "?x", "property": "falling", "value": True}),
],
causes=["support"], produces=["falling"],
)Matching uses a state index with O(1) lookups and relation-based candidate propagation — on a two-variable relation-joined rule at N=1000 entities we measured a 1305× speedup over brute-force matching.
Entity types form a single-inheritance taxonomy. A rule written on an ancestor type automatically applies to every descendant — write once at the right level of abstraction:
wm.register_type("animal")
wm.register_type("mammal", parent="animal")
wm.register_type("dog", parent="mammal")
wm.register_type("cat", parent="mammal")
wm.add_entity(Entity("rex", "dog"))
wm.add_entity(Entity("whiskers", "cat"))
# Rule written on "animal" matches both rex and whiskers
wm.register_rule(CausalRule(
name="hungry_animals_weaken",
conditions=[
Condition(RuleConditionType.ENTITY_MATCHES,
{"entity_id": "?x", "pattern": {"type": "animal"}}),
Condition(RuleConditionType.PROPERTY_EQUALS,
{"entity_id": "?x", "property": "hungry", "value": True}),
],
effects=[...],
))StateIndex indexes each entity under its full ancestor chain, so subtype lookup stays O(1).
Actions can declare multiple outcome branches, each with a probability and effects:
from worldmodel.core import Action, OutcomeBranch, ActionEffect, EffectType
take_medicine = Action(
name="take_medicine",
preconditions=[...],
outcomes=[
OutcomeBranch(0.70, label="cure", effects=[...]),
OutcomeBranch(0.25, label="no_effect", effects=[]),
OutcomeBranch(0.05, label="side_effect", effects=[...]),
],
)
# Enumerate all outcomes
for outcome in wm.predict_distribution(take_medicine):
print(outcome.branch_label, outcome.probability)
# Sample reproducibly
wm.apply_action(take_medicine, rng=random.Random(42), sample=True)apply_action() and predict() default to the most-likely branch for reproducible planning.
goal = Goal(conditions=[GoalCondition(
ConditionType.PROPERTY_EQUALS,
{"entity_id": "light", "property": "lit", "value": True},
)])
plan = wm.plan(goal)
for step in plan.steps:
wm.apply_action(step.action)A* search with an admissible heuristic (count of unsatisfied goal conditions; pluggable via a HeuristicLibrary whose active variant the planner reads at plan time), state deduplication via hashing, configurable depth/node limits. Optimistic with respect to probabilistic effects: assumes most-likely branches and that rules pass the acceptance-threshold gate (the H43 PV-basket dial — rule.log_odds >= acceptance_threshold; the default 0.0 reproduces the historical probability >= 0.5 behavior). MDP-style value iteration is explicit future work.
# What if we had taken a different action at step 0?
result = wm.what_if_different_action(branch_index=0, counterfactual_action=other)
# What if an entity had started with a different property?
result = wm.what_if_property_change("battery", "charged", False)
print(result.actual_state, result.counterfactual_state, result.diff)Symbolic pattern mining: observe transitions, infer rules that explain repeated state changes, generalize entity IDs to ?variables, score by empirical confidence.
# After applying some actions...
learned = wm.learn_rules(min_support=2, min_confidence=0.9)
for lr in learned:
print(lr.rule.name, lr.support, lr.confidence)
wm.register_learned_rules(learned) # adopt them into the engineExpose the WorldModel as a tool for any MCP-capable LLM:
# stdio (Claude Desktop / Claude Code / etc.)
worldmodel-mcp
# HTTP SSE
worldmodel-mcp --transport sseClaude Desktop config:
{
"mcpServers": {
"worldmodel": {
"command": "/path/to/venv/bin/worldmodel-mcp"
}
}
}Exposes ~39 tools covering state management, reasoning, planning, counterfactuals, probabilistic prediction, rule learning, moral rule registration / update / removal / audit-history, and natural-language parsing of actions/rules.
Convert English descriptions to structured Action/CausalRule JSON using Claude with tool-use (guaranteed schema-valid output):
from worldmodel.nlp import parse_action, parse_rule
parse_action("Alice gives the book to Bob")
# → {"name": "transfer_book", "preconditions": [...], "effects": [...]}
parse_rule("If it rains, the ground gets wet with some probability")
# → {"name": "rain_wetness", "conditions": [...], "effects": [...], "probability": ...}Requires ANTHROPIC_API_KEY and pip install -e ".[nlp]" for the default
Anthropic path. MCP prompt templates are also provided for client-side parsing
without an API key.
Local OpenAI-compatible endpoints are available as an opt-in governed gateway backend for Ollama, vLLM, llama.cpp server, LM Studio, or similar local servers:
from worldmodel import LLMGateway, LLMSettings, LOCAL_OPENAI_LLM_PROVIDER
settings = LLMSettings.from_env(provider=LOCAL_OPENAI_LLM_PROVIDER)
gateway = LLMGateway(settings=settings)Useful environment variables include WORLDMODEL_LOCAL_LLM_BASE_URL,
WORLDMODEL_LOCAL_LLM_MODEL, WORLDMODEL_LOCAL_LLM_BACKEND,
WORLDMODEL_LOCAL_LLM_CONTEXT_WINDOW_TOKENS,
WORLDMODEL_LOCAL_LLM_QUANTIZATION, and
WORLDMODEL_LOCAL_LLM_GPU_DEVICE. The backend preserves prompt-audit hashes
and redacted call metadata; local models still do not receive privileged access
to hidden labels, verifier outcomes, or safety gates.
CognitiveAgent composes the LLM (parsing + explanation) with the WorldModel (planning + reasoning) into a one-call neurosymbolic agent loop:
from worldmodel import CognitiveAgent
agent = CognitiveAgent()
agent.register_action_from_text("Alice gives the book to Bob") # LLM
agent.register_rule_from_text("Whoever owns the book learns the topic") # LLM
result = agent.solve("Get Bob to own the book")
# 1. parse goal (LLM)
# 2. plan + execute (symbolic A* + rule engine)
# 3. generate explanation (LLM)
print(result.success, result.explanation)The agent is the user-facing surface for all the underlying machinery: LLM brings creativity and natural language; the symbolic engine guarantees consistency, planning, and verifiable reasoning. See examples/10_agent_demo.py for a runnable end-to-end demo.
The agent's outputs and behavior are gated by several composable subsystems. Each shares the same evaluation machinery as the rest of the substrate (rules / entities / claims) — they are not wrappers, they are first-class.
MoralRule is a priority class within the rule engine. Every plan goes through a moral-veto pass — vetoed plans are rejected with reasons, never silently rewritten. Three severity levels (INVIOLABLE, STRONG, ADVISORY); INVIOLABLE cannot be overridden; STRONG overrideable via an explicit MoralOverride that names the rule. Each rule carries Provenance (origin, author, rationale) and changes are recorded in an append-only moral_rule_history audit trail.
from worldmodel import MoralRule, Severity, Provenance
from worldmodel.rules import Condition, RuleConditionType
wm.register_moral_rule(MoralRule(
name="no_harm_to_humans",
forbidden_pattern=[
Condition(RuleConditionType.ENTITY_MATCHES,
{"entity_id": "?victim", "pattern": {"type": "human"}}),
Condition(RuleConditionType.PROPERTY_EQUALS,
{"entity_id": "?victim", "property": "harmed", "value": True}),
],
severity=Severity.INVIOLABLE,
rationale="No human shall be harmed by the agent's actions.",
provenance=Provenance(origin="human-seed", rationale="Asimov-derived"),
))
plan = wm.plan(some_goal)
if plan.vetoed:
for v in plan.moral_violations:
print(v.explain())Mandatory by default at horizon=5. After plan synthesis, the world is projected forward wisdom_horizon ticks under the existing rule engine (no further agent action); every tail state is checked against the moral veto. Catches plans whose tail consequences are bad even when immediate consequences look clean. Composes with irreversibility flags (Action(irreversible=True)) which promote violation severity one level (H43 stakes pattern), and with calibrated outcome priors that scale the rollout horizon for high-prior actions.
Every assertion the agent emits is a Claim with calibrated confidence in [0, 1], three-state semantics (CLAIM / SILENCE / COUNTER_CLAIM — silence is not a denial), and a source (SYMBOLIC / LLM / HYBRID). LLM-source claims are capped at LLM_CONFIDENCE_CAP=0.7. WorldModel.assert_about_property and satisfies_as_claim are the epistemically-honest queries:
claim = wm.assert_about_property("alice", "is_friendly")
# alice.is_friendly=True set → Claim(CLAIM, SYMBOLIC, conf=1.0)
# alice.is_friendly=False set → Claim(COUNTER_CLAIM, SYMBOLIC, conf=1.0)
# alice.is_friendly not set → Claim(SILENCE, SYMBOLIC, conf=0.0)The agent generates its own subgoals from uncertainty signals (low-confidence rules, silent properties, untested rule preconditions). Curiosity goals go through the same planner path as user goals — moral veto applies; curiosity is not architecturally privileged. GoalStack arbitrates between user / curiosity / maintenance goals with explainable per-goal decisions.
External agents are first-class AgentModel entities with calibrated Credibility in [0, 1]. Anonymous sources start at DEFAULT_ANONYMOUS_CREDIBILITY=0.2 (highly skeptical). Loud assertions from strangers are capped at low confidence via attributed_claim; deceptive agents (consistent goal-divergence between stated and observed behavior) lose credibility until their claims structurally degrade to SILENCE — no separate "trust module," just calibrated source-credibility integration.
predict_and_apply records PredictionTraces; prediction_calibration() returns a Claim whose confidence equals the agent's empirical accuracy. compute_gap_map() aggregates uncertainty signals from across subsystems into a structured GapMap — the agent's honest answer to "what do I know, what am I uncertain about, where am I stuck?" MetacognitiveModel persists gap snapshots and learning episodes so the agent can later inspect which learning strategies worked against which uncertainty signals.
Six bounded runtime controls over the agent's own evidential inference, modeled on the six cortical interneuron classes (Pfeffer 2013). Defaults are all no-ops — the dials are byte-for-byte transparent until an operator turns them. Operator-level registration is unaffected in any setting — the dials gate the agent's inference, not what gets admitted to the substrate.
- Chandelier — stakes.
Action(irreversible=True)promotes the effective severity of any moral violation triggered by the action by one level (ADVISORY → STRONG → INVIOLABLE). - VIP — encoding vs inference.
EvidenceMode.ENCODING(default) keeps agent-driven learning channels open;INFERENCEgatespropose_curiosity_goalsandpropose_rules_via_llmoff. Doesn't affect operator-level access. - PV-basket — acceptance threshold.
WorldModel.acceptance_threshold(log-odds, default0.0) is the H1 firing decision: deterministic rule firing requiresrule.log_odds >= threshold; stochastic mode samplesrng.random() < sigmoid(rule.log_odds - threshold). - SST-spine — counter-evidence weight.
WorldModel.counter_evidence_weight(default1.0) is a non-negative scalar applied to negative summands incombine_log_odds.>1amplifies counter-evidence (paranoid);<1suppresses (credulous);0.0ignores entirely. - SST-Martinotti — source-credibility weight.
WorldModel.source_credibility_weight(default1.0) scales source credibility's log-odds distance from neutral. Applied atattributed_claim.0.0collapses every credibility to 0.5. - NGFC — proportionality cap.
WorldModel.proportionality_cap(defaultLOG_ODDS_CLAMP) bounds the per-source log-odds contribution after counter-evidence weighting. Many in-cap sources can still aggregate past the cap; no single source can dominate.
ConsolidationGate(novelty_threshold, skill_capacity, rule_capacity) is a stateless policy object. Structural novelty via Jaccard (skills: set of underlying action names; rules: union of canonical condition+effect keys, probability not part of the structural key — calibration lives in log-odds, not in library admission). Three rejection branches: REJECTED_DUPLICATE (catastrophic-forgetting protection, on by default), REJECTED_BELOW_NOVELTY, REJECTED_CAPACITY. Facade convenience: wm.consolidate_skill(skill, gate=None) and consolidate_rule(rule, gate=None). Existing register_* paths remain ungated — H4 is opt-in via the new methods.
Per brain-explorer doctrine, three STDP-type roles share log-odds evidence math:
| Role | Subsystem | Shared substrate |
|---|---|---|
| Forward STDP | RuleLearner |
LearnedRule.log_odds/tally derived from existing support+confidence |
| Reverse STDP | Planner |
reads rule.log_odds >= acceptance_threshold via RuleEngine._rule_fires — same comparison as PV-basket |
| Autoassociative STDP | SkillLibrary |
Skill.tally: EvidenceTally with log_odds / confidence views and immutable with_corroboration / with_contradiction returners |
EvidenceTally(support, contradictions) is the shared shape; Laplace-smoothed log((s+1)/(c+1)) is the doctrinal H1 saturating-with-evidence pattern.
WakeSleepMode.WAKE (the default) is pure-inference operation; WakeSleepMode.SLEEP is the window during which agent-driven mutations may commit. MutationSandbox(enforce_wake_sleep=True) opts into the gate: commits are refused in WAKE with rejection reason wake-sleep: mutations only land during sleep window. Evaluation (non-mutating) is always allowed; rate limit is not charged on wake-sleep rejection.
world.sleep_window(sandbox=None, with_snapshot=False) is the standard context manager — flips mode on entry, resets per-cycle rate limit, restores the prior mode on exit (including on exception). with_snapshot=True deepcopies at entry and rolls back on exception (the doctrine's "natural rollback unit"). Nested windows are supported. Operator-level registration is unaffected in any mode — operators always have substrate authority.
For bounded recursive self-modification: EnvelopeManifest declares mutable-vs-frozen substrate surfaces; Constitution carries inviolable rules that cannot be edited by the agent; MutationSandbox clones the world, applies a candidate mutation, runs the six-critic ensemble (ConsistencyCritic, ResourceCritic, BenchmarkCritic, AnchorTestCritic, DistributionalCritic, VerifierOfVerifierCritic) on the clone, and commits only if every critic passes; RateLimit bounds blast radius (per-cycle and per-day budgets); the H14 wake/sleep gate enforces "commits only during sleep". Sandbox isolation has been audited — _mutation_snapshot is a deep copy (mutations can't reach the original through it), and commits copy the evaluated clone rather than re-running the mutation callable (so context-sensitive mutations can't pass critics on one object and commit different behavior on another).
The sleep-mode prompt search (SleepCycle.run) searches over candidate scaffolding variants and commits the best, only if it improves over baseline. The heuristic-from-library swap is the same pattern over HeuristicLibrary variants for the planner. The LLM is fixed; the scaffolding around it compounds through search.
from worldmodel import (
BlocksWorldEnv, ClosedLoopDriver, ConsolidationGate,
MutationSandbox, MutationProposal, WorldModel,
blocks_world_suite, make_benchmark_callable,
)
from worldmodel.critics.ensemble import BenchmarkCritic, CriticEnsemble
# Wire a real BenchmarkCritic to the curated blocks-world suite.
critic = BenchmarkCritic(
benchmark=make_benchmark_callable(blocks_world_suite()),
threshold=0.99,
)
sandbox = MutationSandbox(
critic_ensemble=CriticEnsemble(critics=[critic]),
enforce_wake_sleep=True,
)
wm = WorldModel()
# Mutations only commit inside the sleep window. Inside, the critic
# evaluates on a clone; a regression-inducing mutation is rejected
# and the original world is left unchanged.
with wm.sleep_window(sandbox=sandbox):
outcome = sandbox.apply(wm, proposal)worldmodel.simenv ships a closed-loop driver: BlocksWorldEnv is the v1 ground-truth simulator (auto-built action library, applies action effects directly), ClosedLoopDriver(agent, env) runs perceive → plan → act → observe. The driver is environment-agnostic at the type level (a SimEnv Protocol).
worldmodel.benchmarks ships a curated blocks_world_suite() (graded tower problems stack_2 / stack_3 / stack_4), a BenchmarkRunner that clones the agent per problem, and a make_benchmark_callable(suite) factory that adapts the runner to the BenchmarkCritic's Callable[[WorldModel], float] shape. The previously stubbed critic now reports real pass-rates; mutation-gating has a concrete success signal.
tests/integration/test_self_improvement_demo.py is the proof of life: an end-to-end demo that composes every piece (sim-env + benchmark + critic + sandbox + wake/sleep + proposal). A benign moral-rule addition (no_destroyed_entities, orthogonal to blocks world) is accepted; an adversarial one (no_stacking, forbids any tower) is rejected with the benchmark critic catching the regression on the clone. If this test ever breaks, the bounded-self-modification guarantee is no longer load-bearing.
src/worldmodel/
├── __init__.py
├── facade.py # WorldModel — unified API
├── agent.py # CognitiveAgent — neurosymbolic loop
├── goal_stack.py # GoalStack — user/curiosity/maintenance arbitration
├── core/
│ ├── entity.py # Entity (id + type + properties)
│ ├── relation.py # Relation (frozen directed edge)
│ ├── state.py # WorldState + StateDiff
│ ├── action.py # Action, ActionEffect, Goal, OutcomeBranch
│ └── type_hierarchy.py # Subtype taxonomy
├── rules/
│ ├── causal_rule.py # CausalRule with ?variable binding, probability
│ ├── rule_engine.py # Priority-ordered firing, PV-basket acceptance gate
│ └── state_index.py # O(1) lookups for fast pattern matching
├── reasoning/
│ ├── predictor.py # Predict + predict_distribution
│ ├── counterfactual.py # What-if reasoning
│ ├── causal_graph.py # DAG, d-separation, do-calculus
│ └── planner.py # A* with moral veto + wisdom rollout + pluggable heuristic
├── learning/
│ ├── transition.py # Observed (before, action, after) triples
│ ├── rule_learner.py # Forward-STDP — symbolic rule mining; log_odds/tally views
│ ├── llm_proposer.py # LLM-assisted rule proposal (validator-gated)
│ ├── skill.py # Autoassociative-STDP — skills with EvidenceTally
│ ├── consolidation.py # H4 novelty-gated consolidation gate
│ ├── stdp_doctrine.py # H12/H13/H21 role labels and lookup
│ └── divergence_tracker.py # PredictionTrace + diff_divergence
├── morality/
│ ├── moral_rule.py # MoralRule, MoralViolation, MoralOverride, Provenance, MoralRuleRevision
│ └── veto.py # MoralVeto checker (state / action / plan)
├── wisdom/
│ ├── rollout.py # WisdomChecker — tail-consequence projection
│ └── priors.py # OutcomePrior + calibrated horizon scaling
├── honesty/
│ ├── claim.py # Claim, ClaimType, ClaimSource, LLM_CONFIDENCE_CAP
│ ├── evaluation.py # Three-state goal evaluation (Kleene strong AND)
│ ├── log_odds.py # H1/H51 substrate — logit, sigmoid, combine_log_odds
│ ├── evidence_tally.py # Shared (support, contradictions) shape
│ ├── evidence_mode.py # H43 VIP dial
│ ├── acceptance_threshold.py # H43 PV-basket dial
│ ├── counter_evidence_weight.py # H43 SST-spine dial
│ ├── source_credibility_weight.py # H43 SST-Martinotti dial
│ └── proportionality_cap.py # H43 NGFC dial
├── judgment/
│ ├── agent_model.py # AgentModel + Credibility (corroborate/contradict)
│ ├── claims.py # attributed_claim factory (credibility + Martinotti)
│ └── divergence.py # Goal-divergence detection + deception heuristic
├── curiosity/
│ ├── drive.py # CuriosityDrive (intrinsic motivation)
│ └── signals.py # Low-confidence rules / silent properties / untested preconditions
├── metacognition/
│ ├── gap_map.py # GapMap — aggregated self-assessment
│ └── model.py # MetacognitiveModel — persistent gap/learning history
├── critics/
│ └── ensemble.py # CriticEnsemble + six v1 critics (incl. VerifierOfVerifier)
├── bootstrapping/
│ ├── envelope.py # EnvelopeManifest + Constitution + AnchorTestRegistry
│ ├── sandbox.py # MutationSandbox + RateLimit + four-gate pipeline
│ ├── sleep_mode.py # PromptRegistry + SleepCycle (prompt search)
│ ├── heuristic_search.py # HeuristicLibrary + HeuristicSearch (planner heuristics)
│ └── wake_sleep.py # H14 WakeSleepMode + sleep_window context manager
├── lean/ # Lean integration (Tier 0+1 + tactic-script surface)
│ ├── formalization.py # Informal math problem → reviewed Lean candidate tracking
│ ├── proof_state.py # Replayable proof-attempt/tactic-script harness
│ ├── retrieval.py # Local theorem-corpus retrieval proposer
│ ├── capability_ladder.py # Math capability ladder + artifact evaluator
│ ├── theorem.py # Theorem (frozen entity with optional proof)
│ └── verifier.py # LeanVerifier ABC + Stub + Subprocess implementations
├── simenv/ # Closed-loop sim-env driver
│ ├── blocks_world.py # BlocksWorldEnv — ground-truth simulator
│ └── driver.py # ClosedLoopDriver — perceive→plan→act→observe loop
├── science/ # Science gates + low-risk physics artifacts
│ ├── grounded_demo.py # Harmonic oscillator metrics + package writer
│ ├── public_data.py # GWOSC/GW150914 metadata + posterior-export checks
│ └── safety.py # Science-domain release gate
├── perception/ # PerceptionAdapter substrate + Anthropic vision adapter
│ ├── perception.py # PerceivedEntity/Relation/Result + integration policy
│ └── anthropic_vision.py # Claude vision client producing PerceptionResult
├── baselines/ # Bounded external-comparator adapters
│ └── llm_tool_use.py # Read-only LLM tool-use baseline with prompt audit
├── benchmarks/ # Curated problem suites + runner
│ ├── blocks_world.py # BenchmarkProblem + blocks_world_suite()
│ └── runner.py # BenchmarkRunner + make_benchmark_callable
├── serializers.py # JSON round-trip for all types (schema v17)
├── mcp_server.py # FastMCP server (stdio + SSE; ~39 tools)
└── nlp.py # LLM-based NL parsing (optional)
venv/bin/python -m pytest # Current /home/claudeai/python312 run: 3583 passed + 2 skipped (requires_local_llm unless enabled; requires_gpu until torch/sentence-transformers are installed)
venv/bin/python -m pytest tests/unit/
venv/bin/python -m pytest tests/scenarios/ -v
venv/bin/python -m pytest tests/integration/test_self_improvement_demo.py -v # proof of life
ANTHROPIC_API_KEY=... venv/bin/python -m pytest -m requires_api tests/integration/test_llm_real_api.py -q- Unit (
tests/unit/): one file per class, property-level coverage - Integration (
tests/integration/): multi-component flows (state tracking, prediction, planning, moral veto, wisdom rollout, judgment, curiosity, sleep-mode prompt search, bootstrapping pipeline, sim-env driver, benchmark suite, end-to-end self-improvement loop, MCP, NL parser) - Scenarios (
tests/scenarios/): end-to-end worlds (blocks, switches/circuits, social reasoning, stochastic medicine, observed gravity)
Research prototype with a substantial, demonstrated values & character substrate. All core cognitive capabilities are implemented and tested. Moral / wisdom / honesty / curiosity / judgment / metacognition / bootstrapping substrates compose with the foundation per the design discussion. The bounded-self-modification loop has an end-to-end test (tests/integration/test_self_improvement_demo.py) that composes sim-env + benchmark + critic ensemble + sandbox + wake/sleep + mutation proposal; that test demonstrates a benign mutation being accepted and an adversarial regression being rejected, with the critic ensemble catching the regression before any state lands.
Not yet a production library. The reverse-STDP planner is still optimistic A* (MDP-style value iteration is unbuilt); the benchmark suite is one curated set on one domain (blocks world); RETE-style incremental matching is not implemented; semantic memory / external knowledge-graph grounding is not implemented; live LLM scaffolding-search deployments have not been run.
The project's True North is AGI with the character of the best humans (moral, honest, curious, wise, possessing integrity and good judgment of character) and the intellectual capability to lead original scientific work — with moral character as an inviolable constraint, not a wrapper added late. See TODO.md for the operational roadmap, docs/aspirations.md for the long-term aspirational direction, docs/research-readiness-assessment.md for the current publication / research-agent readiness assessment, docs/math-physics-research-agent-roadmap.md for the practical verifier-backed path toward a mathematics / physics research agent, docs/llm-integration-assessment.md for the current LLM-integration scope and ranked next items, and docs/open-research-implementation-notes.md for bounded engineering proposals translating recent (2024–2026) research on the genuinely-open problems (metacognition, concept formation, OOD generalization, continual learning, causal discovery, aligned value formation) into concrete next steps. The near-term goal — a moral, curious, capable research agent — is a step on the journey, valuable in its own right, but not the destination.
Completed:
Foundation:
- MCP server integration (stdio + SSE; ~39 tools)
- LLM-based NL → structured action/rule parser
- Probabilistic actions + rules
- Rule learning from observed traces (with hierarchy generalization)
- Indexed pattern matching (1000×+ speedup at scale)
- Persistence (JSON save/load; schema v19, backward-compat with v1–v18)
- CI via GitHub Actions (Python 3.10 / 3.11 / 3.12)
- Type hierarchies (single inheritance, subtype-aware matching)
- Numeric/inequality conditions + arithmetic effects
- Native temporal operators (
PROPERTY_UNCHANGED_FOR,PROPERTY_CHANGED_WITHIN) - LLM-assisted rule proposer with iterative validator-feedback loop
- End-to-end neurosymbolic agent (
CognitiveAgent) - Skill library
Values & character (load-bearing):
- Moral substrate:
MoralRulepriority class with planner veto + irreversibility promotion + override semantics + provenance audit trail - Wisdom rollout: mandatory tail-consequence projection with calibrated outcome priors scaling horizon by per-action stakes
- Honest agent contract:
Claimwith three-state semantics + calibrated source-aware confidence + LLM cap - Curiosity drive + goal stack arbitration (user / curiosity / maintenance)
- Judgment of character: agent models with credibility, source-credibility-capped claims, goal-divergence detection, deception heuristic
- Learning from divergence: prediction-vs-actual tracking with calibrated
prediction_calibrationclaim - Metacognition:
GapMapaggregated self-assessment + persistedMetacognitiveModelhistory
Brain-explorer bridges:
- Log-odds substrate (H1 / H51):
logit,sigmoid,combine_log_odds;.log_oddsviews on every probability-typed field - All six H43 interneuron dials: Chandelier (irreversibility), VIP (
EvidenceMode), PV-basket (acceptance_threshold), SST-spine (counter_evidence_weight), SST-Martinotti (source_credibility_weight), NGFC (proportionality_cap) - H14 wake/sleep mutation-window regime with
sleep_windowcontext manager + optional snapshot rollback + sandboxenforce_wake_sleepgate - H4 novelty-gated consolidation (
ConsolidationGateover skills and rules) - H12/H13/H21 three-STDP decomposition (shared
EvidenceTallyacross RuleLearner / Planner / SkillLibrary)
Bootstrapping (bounded recursive self-modification):
- Architectural envelope:
EnvelopeManifest,Constitution(inviolable rules), append-onlyAnchorTestRegistry - Six-critic ensemble:
ConsistencyCritic,ResourceCritic,BenchmarkCritic,AnchorTestCritic,DistributionalCritic,VerifierOfVerifierCritic - Mutation sandbox: clone + four-gate pipeline + audited isolation (snapshot is a deep copy; commit copies the evaluated clone, never re-runs the mutation callable)
RateLimit: per-cycle and per-day budgets- Sleep-mode prompt search (
SleepCycle.run) + heuristic-from-library swap (same pattern, different mutable surface) - End-to-end self-improvement demo composing every piece
Capability extensions:
- Lean integration (Tier 0 + 1):
Theoremfirst-class entity +LeanVerifier(stub / subprocess);claim_about_theoremmaps verification status to the three-state honesty contract - Math formalization pipeline v0: informal problem + Lean candidate + review status + verifier status tracked separately; JSON persistence and reviewed theorem-corpus package writer
- Lean proof-state smoke harness: replayable verifier-attempt reports for theorem-under-proof traces, parsed feedback snapshots for Lean diagnostics / unsolved-goal context, a tactic-script action surface that compiles bounded tactic steps to verifier-facing proof attempts, a snapshot-structured proof-state planning package that turns feedback plus retrieval hits into ranked candidate proof actions, a deterministic proof-state feedback question-layer ablation package, a live Lean subprocess integration package that records
incremental_lsp_used=false, and a separate live Lean LSP package that records observed goal-stack use while keeping the subprocess verifier as proof authority - Local theorem-corpus retrieval proposer v1 + theorem-proving question-layer ablation smoke runner with CI-safe fixture mode, optional real Lean subprocess mode, proof-state-weighted retrieval queries, corpus-usage tracking, composed
question_full_with_retrieval, standalone retrieval-proposer packaging, bounded worker metadata, preregistered Lean-curriculum smoke packaging, and a GPU-aware embedding retrieval v0 package path that records whether torch/CUDA scoring was actually used - Lean standard-library corpus originality screen over installed Lean source declarations, explicitly not publication originality clearance
- Mathlib-scale retrieval corpus package: 139,581 theorem/lemma declaration headers from a clean pinned local mathlib4 checkout, with coverage accounting, a bounded committed excerpt, and a CUDA-scored dense-retrieval evaluation over miniF2F-derived proof-goal queries — scale/provenance/machinery evidence; self-lookup measures self-recall@1 0.94 and @5 1.0, the repaired true leave-one-out same-file neighbor recall is 0.895 (the legacy metric's 0.0 was a measurement bug), and human-judged relevance remains unmeasured;
publication_originality_readyremains false - Preregistered retrieval-augmented theorem A/B: bare arm vs top-5 Mathlib dense-retrieval context in one paired execution on the miniF2F bind, with frozen designs, a retrieval-context coverage floor, leakage guard, and exact sign test. Post-hoc audit reclassified both 2026-07-24 packages as non-publication diagnostics because the frozen embedding dimension differed from execution, sampling controls were unspecified, arm order was fixed, and the legacy retrieval validation was not genuinely leave-one-out. The 2026-07-27 repaired rerun (counterbalanced arms, explicit temperature 0.0, effective embedding metadata, full coverage) passes every gate and the post-hoc review with zero blockers and again detects no difference (20/67 vs 21/67, p = 1.0) — no detectable difference, with equivalence neither tested nor established
- Matched-filter diagnostics instrumentation: injection-recovery, noise-only negative-control, and time-slide coincidence-background diagnostics run through the pilot's exact extracted matched-filter code path on synthetic strain, prepared for the blocked GWOSC/PyCBC method-review gate without passing any topic
- Literature-ingestion pipeline v0 + full-text search v1: bounded arXiv metadata/abstract queries parsed into a provenance-bearing corpus (hashed responses, raw feeds never committed) that the originality gate's deterministic search consumes, plus transient e-print LaTeX-source screens (formula-capable whitespace-flexible matching, bounded excerpts with file/offset provenance, logged negatives, case-sensitive by design) — supersedes the
no_literature_search_backendblocker with an enumerated-bounds backend (single source, no citation graph, no claim extraction, no macro expansion, human review still mandatory); first external consumer: a physics-preprint submission's originality evidence - OOD benchmark perturbation suite + worst-case-slice critic: deterministic renamings, distractors, adversarial initial states, and longer-horizon towers, gated on the worst slice rather than the average
- Artifact-backed math capability ladder evaluator over the committed real-Lean theorem replay and proof-repair packages, plus a scaled 20-problem proof-repair v1 package path, a public held-out theorem statement package with omitted proof commitments, a transparent public held-out solver run that consumes future hidden-benchmark status for that statement set, and a local publication-candidate theorem-ablation package
- Math-domain architecture-ablation smoke runner that executes contained
no_honesty_contract/no_question_layerproxies and leaves unsupported ablations explicitly unexecuted - Role-specific human-review release-gate packages for claim-package and originality-label promotion, including a real-target preprint gate over the Markdown/PDF/audit bundle; blocked until real review refs exist
- Sim-env binding:
BlocksWorldEnv+ClosedLoopDriver(perceive → plan → act → observe) - Benchmark suite: curated
blocks_world_suite()+BenchmarkRunner+make_benchmark_callablewired through toBenchmarkCritic - Episodic memory subsystem (append-only event store with structural recall; pairs with H4 consolidation)
Candidate next steps (see TODO.md for the full operational roadmap):
- Local compute workstation leverage:
docs/local-compute-workstation-plan.md - MDP-style probabilistic planning (replace optimistic A* with value iteration over log-odds transitions)
- Formalization review corpus and persistence beyond the v0 in-memory pipeline
- Lean Tier 2 beyond feedback snapshots, tactic-script actions, snapshot-structured planning, live subprocess feedback, and initial live LSP goal-stack introspection: persistent multi-step editor sessions and interactive theorem-under-proof planning
- Incremental Lean/LSP proof-state question-layer ablation beyond the current smoke-scale live-LSP package
- Retrieval that actually helps proof search — the repaired counterbalanced deterministic A/B again detected no difference for header-only top-5 context at this model size (equivalence untested); the open work is a preregistered equivalence margin, human-judged relevance labels, proof-body-aware retrieval, goal-state-conditioned queries, and multi-step proof search
- External theorem benchmark adapters beyond the miniF2F-lean4 test-split bind — ProofNet / valid-split binds, plus leak-safe per-item candidate signal (proof-history priors, statement-derived features, Mathlib-scale retrieval) so ordering modes have real signal to rank on
- Harder benchmark problems (swap, unstack-then-restack, multi-tower from pre-stacked initial state)
- Society-of-judges critic ensemble (Areas 24 → 32 → 10 → 46 → 9 mapping over the existing six critics)
- H49 / analogical reasoning (the explicit remaining brain-explorer capability gap)
- Real reviewer refs that clear the role-specific release gate for a narrow claim package or the preprint bundle
- Apply the new injection/negative-control/time-slide diagnostics to real re-fetched GW150914 strain, obtain real domain-method review refs for the blocked GWOSC/PyCBC gate, or bind an independently verified public SNR summary before any open-ended physics theory-generation claim
- Astronomy data-pipeline tool binding (Vera Rubin open data)
- Performance dashboard (rule-engine timing on representative scenarios)
No license declared. Treat as source-available research code; contact the author before redistribution.