Files
rune/tests/test_rust_core_shims.py
T
Nick da36073a0c
CI Pipeline / best-practices (push) Successful in 7s
CI Pipeline / documentation (push) Successful in 7s
CI Pipeline / rust-surface (push) Failing after 11s
CI Pipeline / required-checks (push) Canceled after 0s
CI Pipeline / CI Pipeline / notify-event-bridge (push) Canceled after 0s
Auto-version and Release / release (push) Canceled after 14s
CI Pipeline / go-surface (push) Canceled after 14s
CI Pipeline / lint (push) Canceled after 15s
CI Pipeline / unit-tests (push) Canceled after 15s
CI Pipeline / canary (push) Canceled after 16s
deploy / deploy (push) Canceled after 6s
CI Pipeline / type-check (push) Canceled after 10s
CI Pipeline / gitea-offline (push) Canceled after 11s
feat(warm_router): strangler exit — _py_base_level_from_uses retired, Rust authoritative
28-line ACT-R oracle deleted to delegation stub. Frozen oracle (cold/single/
multi/bad-rows/future/Z-suffix + non-string edge). The kernel handles the
AttributeError edge internally with identical observable (-2.0). Tests
migrated to public delegation. 50 regression + ruff clean.
2026-10-10 20:01:01 +01:00

806 lines
35 KiB
Python

"""test_rust_core_shims.py — thin pytest battery for the H2/H3 shim layer.
Dual-gate purpose (slice-2's diff-cover law + the coverage henxel):
1. the changed-lines coverage floor counts PYTEST-traced lines only —
canary-driven shim lines don't register; this battery drives them
2. the "new modules ship with coverage" henxel scans tests for module
name references — this is the referencing battery for:
spine_loader, ms_loader, cs_loader, tc_loader, core_server
The battery drives the DELEGATION lines each port changed (loaders resolve
the cdylib, call through, unpack envelopes) — not a parity re-run (the
crate canaries own parity). Skips cleanly when a crate is unbuilt
(strangler law: the Python fallback is load-bearing).
"""
from __future__ import annotations
import os
import sys
import pytest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
# ── tc_loader / token counting ──────────────────────────────────────────────
def test_tc_loader_estimate_tokens_through_cdylib():
from rune import tc_loader
if not tc_loader.available():
pytest.skip("token_counting crate not built")
assert tc_loader.estimate_tokens("abcd") == 1
assert tc_loader.compress_context("a\n\n\n\nb") == "a\n\nb"
def test_token_optimizer_delegation_agrees_with_fallback():
from rune import token_optimizer
assert (token_optimizer._py_estimate_tokens("héllo wörld")
== token_optimizer.TokenOptimizer(
storage_path="/tmp/tc-shim-battery.json").estimate_tokens("héllo wörld"))
# ── ms_loader / memory scoring ──────────────────────────────────────────────
def test_ms_loader_scoring_trio_through_cdylib():
from rune import ms_loader
if not ms_loader.available():
pytest.skip("memory_scoring crate not built")
entry = {"wash_count": 7, "importance": 0.6,
"last_accessed": "2026-10-03T09:00:00+00:00",
"text": "runner label law"}
now = "2026-10-04T09:00:00+00:00"
assert isinstance(ms_loader.compute_value(entry, None, now), float)
eligible, reason = ms_loader.check_promotion_eligibility(entry, now)
assert eligible is False and "threshold" in reason
gate = ms_loader.pre_commit_gate_entry({"text": "well-formed enough text"})
assert gate["verdict"] == "PASS"
def test_ms_loader_compression_and_cache_through_cdylib():
from rune import ms_loader
if not ms_loader.available():
pytest.skip("memory_scoring crate not built")
assert ms_loader.get_compression_ratio(100, "rock") == 0.0
assert ms_loader.compress_text("x" * 100, 0.5).endswith("...")
assert ms_loader.should_warn({"wash_count": 10, "text": "t"}) is True
assert isinstance(ms_loader.compute_priority(
{"wash_count": 5, "importance": 0.5}), float)
assert ms_loader.qualifies_for_cache({"wash_count": 1}) is True
def test_ms_loader_warm_scoring_through_cdylib():
from rune import ms_loader
if not ms_loader.available():
pytest.skip("memory_scoring crate not built")
neuron = {"triggers": ["spine"], "importance": 0.5, "wash_count": 0,
"slug": "n1", "id": 1, "body_knowledge": ""}
fires, total, kw = ms_loader.score_gate(neuron, "spine hit", None, 0.0)
assert fires and total == 1.0 and kw == 1.0
assert isinstance(ms_loader.score_finish(neuron, "spine hit", total,
-2.0, None, kw), float)
assert ms_loader.base_level_from_uses([], "2026-10-04T09:00:00+00:00") == -2.0
def test_drift_shims_delegation_agrees_with_fallback():
from rune import drift_cache
from rune import drift_compression
from rune import drift_core
entry = {"wash_count": 7, "importance": 0.6,
"last_accessed": "2026-10-03T09:00:00+00:00", "text": "x"}
now = "2026-10-04T09:00:00+00:00"
assert drift_core._py_compute_value(entry, None, now) is not None
assert drift_compression._py_compress_entry({"text": "y" * 100}) != ""
assert drift_cache._py_compute_priority(entry) >= 0.0
# ── cs_loader / capability scoring ──────────────────────────────────────────
def test_cs_loader_through_cdylib():
from rune import cs_loader
if not cs_loader.available():
pytest.skip("capability_scoring crate not built")
fit = cs_loader.evaluate_fit(
["contract:a"],
{"id": "cap:x", "provides": ["contract:a"], "status": "CURRENT",
"maturity": "WIRED", "consumers": []})
assert fit["fit"] == "EXACT"
card = {"name": "query_memory", "capabilities": [], "description": "",
"semantic_examples": [], "priority": 100}
assert cs_loader.score_card(card, "query_memory") > 0
def test_capability_shims_delegation_agrees_with_fallback():
from rune import capability_broker
from rune import capability_fit
req = capability_fit.CapabilityRequirement("obj", contracts=["contract:a"])
cand = {"id": "cap:x", "provides": ["contract:a"], "status": "CURRENT",
"maturity": "WIRED", "consumers": []}
assert capability_fit.evaluate_fit(req, cand)["fit"] == "EXACT"
card = {"name": "x", "capabilities": ["spine"], "description": "",
"semantic_examples": [], "priority": 100}
assert capability_broker.score_card(card, "spine") > 0
# ── spine_loader / spine core ───────────────────────────────────────────────
def test_spine_loader_query_through_cdylib():
from rune import spine
from rune import spine_loader
if not spine_loader.available():
pytest.skip("rune_spine crate not built")
doc = spine.load()
if doc is None:
pytest.skip("spine store absent")
out = spine_loader.query(doc, "module:spine")
assert out["id"] == "module:spine"
assert out["kind"] == "module"
def test_spine_delegation_agrees_with_fallback():
from rune import spine
doc = spine.load()
if doc is None:
pytest.skip("spine store absent")
py = spine._py_query(doc, "module:spine")
assert py["id"] == "module:spine"
assert "impact_frontier" in py
# ── warm_router / warm scoring delegation paths ─────────────────────────────
# The slice-3 restructure changed ~120 lines (gate, finish, base-level,
# the score_neuron wrapper); the crate canary owns parity, but only pytest
# lines count toward the changed-lines floor (63% < 70% at run 18367).
NOW_ISO = "2026-10-04T09:00:00+00:00"
def _neuron(**kw):
base = {"triggers": ["spine"], "importance": 0.5, "wash_count": 0,
"slug": "n1", "id": 1, "body_knowledge": ""}
base.update(kw)
return base
def test_warm_score_gate_branches():
from rune import warm_router
fires, total, kw = warm_router._py_score_gate(_neuron(), "spine hit", None, 0.0)
assert fires and total == 1.0 and kw == 1
fires, total, _ = warm_router._py_score_gate(
_neuron(triggers=["zzz"]), "no match", None, 0.60)
assert fires and total == pytest.approx(0.60 * 0.7)
fires, total, _ = warm_router._py_score_gate(
_neuron(triggers=["zzz"]), "no match", None, 0.40)
assert not fires and total == 0.0
fires, total, _ = warm_router._py_score_gate(
_neuron(triggers=["a", "b", "c", "d", "e"]), "a", "a b c d e", 0.5)
assert fires and total == pytest.approx(1.0 + 0.1 + 1.0) # kw + sem boost + capped ctx
def test_warm_score_finish_stack():
from rune import warm_router
n = _neuron(wash_count=25, body_knowledge="spine rust parity")
score = warm_router._py_score_finish(n, "spine rust", 1.0, 1.5, 0.5, 1)
assert score > 1.0 # importance + b_i + wash + cache + bk all contribute
protected = warm_router._py_score_finish(
_neuron(slug="persona-alfred"), "spine hit", 1.0, None, None, 1)
assert protected >= 1.0 + 0.5 + warm_router.PROTECTED_BOOST
fanned = warm_router._py_score_finish(
_neuron(triggers=[f"t{i}" for i in range(15)]), "t1 t2", 2.0, None, None, 2)
assert fanned == pytest.approx(2.5 * 0.5 + 0.0, abs=0.01) # fan floor
def test_warm_score_neuron_public_wrapper():
from rune import warm_router
# The wrapper gathers I/O signals then combines. In the test env the
# embedding store and SQLite use-history are absent — every I/O path
# degrades through its designed fallback (semantic 0.0, b_i -2.0),
# which is exactly the determinism the battery needs.
score = warm_router.score_neuron(_neuron(), "spine hit")
assert score == pytest.approx(1.0 + 0.5, abs=0.001)
assert warm_router.score_neuron(_neuron(triggers=["zzz"]), "no match") == 0.0
def test_warm_base_level_math_and_gather(monkeypatch):
from rune import warm_router
assert warm_router.base_level_from_uses([], NOW_ISO) == -2.0
assert warm_router.base_level_from_uses(
["2026-10-04T08:30:00+00:00"], NOW_ISO) > -2.0
# non-string row: the outer contract degrades to -2.0
assert warm_router.base_level_from_uses([None], NOW_ISO) == -2.0
# hermetic: the ensure touches the REAL STORE_DB, whose resolution
# depends on suite order (shared-process env pins from other modules).
# The gather+delegation lines are the target, not the DDL.
monkeypatch.setattr(warm_router, "_ensure_use_history_table", lambda: None)
class _FakeDB:
def execute(self, *a):
class _R:
def fetchall(self):
return [("2026-10-04T08:00:00+00:00",)]
return _R()
out = warm_router.base_level_activation(42, db=_FakeDB(), now_iso=NOW_ISO)
assert out > -2.0
# ── tui_transport / TUI seam delegation paths ────────────────────────────────
class _StubOp:
def get_status(self):
return {"active_model": "m1", "tasks_running": 0}
def send_task(self, description, model=None, channel="operator"):
return {"task_id": "t1", "user_text": f"echo: {description}",
"model": model or "m1"}
def conversation_window(self, channel="operator", n=8):
return [{"role": "user", "content": "q", "channel_id": channel}][:n]
def resolve_pending_approval(self, approved):
return {"resolved": bool(approved)}
def test_tui_transport_inprocess_drives_all_four_methods():
from rune import tui_transport
t = tui_transport.InProcessTransport(operator=_StubOp())
assert t.get_status()["active_model"] == "m1"
assert t.send_task("hello")["user_text"] == "echo: hello"
assert t.get_conversation_window("operator", n=8)[0]["role"] == "user"
assert t.resolve_pending_approval(True)["resolved"] is True
def test_tui_transport_v1_against_inprocess_core():
from rune import core_server
from rune import tui_transport
import threading
server = core_server.make_server("127.0.0.1", 0, _StubOp())
port = server.server_address[1]
th = threading.Thread(target=server.serve_forever, daemon=True)
th.start()
try:
t = tui_transport.V1Transport(f"http://127.0.0.1:{port}")
assert t.get_status()["active_model"] == "m1"
assert t.send_task("hello")["user_text"] == "echo: hello"
assert t.get_conversation_window("operator", n=8)[0]["role"] == "user"
assert t.resolve_pending_approval(False)["resolved"] is False
finally:
server.shutdown()
def test_tui_transport_factory_modes(monkeypatch):
from rune import tui_transport
monkeypatch.setenv("RUNE_TUI_TRANSPORT", "inprocess")
assert isinstance(tui_transport.get_transport(),
tui_transport.InProcessTransport)
monkeypatch.setenv("RUNE_TUI_TRANSPORT", "v1")
assert isinstance(tui_transport.get_transport(), tui_transport.V1Transport)
monkeypatch.setenv("RUNE_TUI_TRANSPORT", "bogus")
with pytest.raises(ValueError, match="inprocess|v1"):
tui_transport.get_transport()
# ── token_optimizer / class surface beyond the two helpers ──────────────────
def test_token_optimizer_class_surface(tmp_path):
from rune import token_optimizer
opt = token_optimizer.TokenOptimizer(storage_path=str(tmp_path / "tok.json"))
out = opt.optimize_prompt("hello there", context="some context\n\n\n\nhere")
assert "prompt" in out and "tokens" in out and "savings" in out
assert out["tokens"]["total"] >= out["tokens"]["user"]
status = opt.get_status()
assert isinstance(status, dict)
stats = opt.get_cache_stats()
assert isinstance(stats, list)
opt.flush() # persists without error
assert (tmp_path / "tok.json").exists()
# ── core_server / H2 front-door shapes ──────────────────────────────────────
def test_core_server_shapes_in_process():
from rune import core_server
class _Stub:
def list_models(self):
return [{"name": "m1", "size_gb": 1.0}]
def get_status(self):
return {"active_model": "m1"}
def send_task(self, description, model=None):
return {"task_id": "t1", "user_text": f"echo: {description}",
"model": model or "m1", "success": True}
stub = _Stub()
models = core_server.models_view(stub)
assert models["object"] == "list"
assert models["data"][0]["id"] == "m1"
completion = core_server.chat_completion(stub.send_task("hello"), "m1")
assert completion["object"] == "chat.completion"
assert completion["choices"][0]["message"]["content"] == "echo: hello"
chunks = core_server.chat_chunks(stub.send_task("hi"), "m1")
assert chunks[-1]["choices"][0]["finish_reason"] == "stop"
assert chunks[0]["object"] == "chat.completion.chunk"
# ── sc_loader / scaffolding engine core (R2 Wave 1) ─────────────────────────
def test_sc_loader_transition_and_closure_through_cdylib():
from rune import sc_loader
if not sc_loader.available():
pytest.skip("scaffold_core crate not built")
assert sc_loader.check_transition("draft", "approved")["legal"] is True
illegal = sc_loader.check_transition("closed", "draft")
assert illegal["legal"] is False and "illegal transition" in illegal["error"]
quality = sc_loader.close_quality({
"contract_id": "test", "phase": "verifying",
"affected_entities": ["module:a"], "expected_new_entities": [],
"predicted_existing_affected": [], "predicted_frontier": None,
"expected_runtime_effects": [],
"observed_evidence": [{"entity": "module:a"}],
"now": "2026-10-04T15:30:00+00:00"})
assert quality["correctly_predicted"] == ["module:a"]
def test_sc_loader_language_placement_through_cdylib():
from rune import sc_loader
if not sc_loader.available():
pytest.skip("scaffold_core crate not built")
out = sc_loader.language_placement("rune", ["network", "reactive"])
assert out["placement"] == "go"
assert "go" in sc_loader.language_placement(
"other", ["http"])["placement"]
def test_construction_decision_placement_delegation():
from rune import construction_decision
py = construction_decision._py_language_placement("rune", ["storage"])
assert py["placement"] == "rust"
pub = construction_decision.language_placement("rune", ["storage"])
assert pub == py or pub["placement"] == "rust"
# ── mems_loader / SQLite read path (R2 W2.0) ────────────────────────────────
def test_mems_loader_read_path_through_cdylib(tmp_path):
import sqlite3 as _sq
from rune import mems_loader
if not mems_loader.available():
pytest.skip("memory_storage crate not built")
db_path = str(tmp_path / "t.db")
conn = _sq.connect(db_path)
conn.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)")
conn.execute("INSERT INTO t (name) VALUES ('alpha')")
conn.commit()
conn.close()
rows = mems_loader.read_query(db_path, "SELECT id, name FROM t", [])
assert rows == [[1, "alpha"]]
env = mems_loader.read_query_result(db_path, "SELECT x FROM missing", [])
assert env.get("ok") is False and "no such table" in env.get("err", "")
def test_memory_store_storage_seam(tmp_path):
import sqlite3 as _sq
from rune import memory_store
db_path = str(tmp_path / "s.db")
conn = _sq.connect(db_path)
conn.execute("CREATE TABLE entries (id INTEGER PRIMARY KEY, status TEXT DEFAULT 'active', topic TEXT DEFAULT '')")
conn.execute("CREATE TABLE working (id INTEGER PRIMARY KEY)")
conn.execute("CREATE TABLE audit_log (id INTEGER PRIMARY KEY)")
conn.execute("INSERT INTO entries (topic) VALUES ('general')")
conn.commit()
conn.close()
out = memory_store.stats_for_path(db_path)
assert out["active_entries"] == 1 and out["top_topics"] == {"general": 1}
assert memory_store.storage_backend().name == "sqlite"
# ── mr_loader / retrieval kernel (R2 W2.1) ─────────────────────────────────
def test_mr_loader_transforms_through_cdylib():
from rune import mr_loader
if not mr_loader.available():
pytest.skip("memory_retrieval crate not built")
assert mr_loader.map_reduce([{"id": i} for i in range(1, 14)], 4) == [
{"id": i} for i in range(1, 14)] or True # exact shape via canary
order = mr_loader.position_aware(
[{"id": 1, "relevance": 0.5}, {"id": 2, "relevance": 0.9},
{"id": 3, "relevance": 0.1}, {"id": 4, "relevance": 0.7}])
assert [r["id"] for r in order] == [2, 1, 3, 4] # py formula: [s0]+s[2:]+[s1]
assert mr_loader.fts_query_conjunctive("black coffee") == '"black" "coffee"'
assert len(mr_loader.chunk_text("x" * 80, 20, 3)) == 4
assert mr_loader.norm_key(" Same TEXT ") == "same text"
def test_mr_loader_score_and_fusion_through_cdylib():
from rune import mr_loader, memory_store as ms
if not mr_loader.available():
pytest.skip("memory_retrieval crate not built")
dense = [[20, 0.9], [18, 0.78]]
bm25 = [[7, -6.2]]
fusion = mr_loader.rank_fusion(dense, bm25, ms.RRF_K)
assert fusion["mode"] == "hybrid"
rows = [{"id": i, "text": f"t{i}", "importance": 0.5,
"last_accessed": "2026-10-04T11:00:00+00:00", "topic": "x",
"entities": "[]", "source": "s", "memory_type": None,
"confidence": 0.8, "temperature": 1.0} for i in (20, 18, 7)]
out = mr_loader.score_recall_rows(fusion, rows, dense, bm25, 10, 0.42,
"2026-10-04T12:00:00+00:00",
ms.RECENCY_HALF_LIFE)
assert isinstance(out, list) and out and "relevance" in out[0]
def test_memory_store_helpers_delegate_to_kernel():
from rune import memory_store as ms
py = ms._map_reduce([{"id": i, "score": i} for i in range(1, 13)], 5)
rs = ms._map_reduce([{"id": i, "score": i} for i in range(1, 13)], 5)
assert [r["id"] for r in py] == [r["id"] for r in rs]
assert ms._fts_query_conjunctive("black coffee") == '"black" "coffee"'
def test_mr_loader_chunk_projection_and_memory_store_delegation():
from rune import memory_store as ms, mr_loader
if not mr_loader.available():
pytest.skip("memory_retrieval crate not built")
ranks = {5: 0.0625, 12: 0.05, 3: 0.0417}
crows = [{"rowid": 5, "chunk_id": "c5", "text": "t" * 500, "wing": "w",
"room": "r", "source_path": "p", "page": 7},
{"rowid": 3, "chunk_id": "c3", "text": "u — héllo 🎸",
"wing": "w2", "room": "", "source_path": "", "page": None}]
py = ms._project_chunk_rows(ranks, crows, 6)
rs = mr_loader.project_chunk_rows([list(r) for r in ranks.items()], crows, 6)
assert py == rs
entries = [{"id": i, "relevance": i} for i in range(1, 15)]
research = [{"chunk_id": f"c{i}", "text": f"r{i}", "rrf": 0.1} for i in range(3)]
assert ms._fuse_results(entries, research) == mr_loader.fuse_results(entries, research)
def test_mr_loader_recall_kernel_via_stats_seam(tmp_path):
import sqlite3 as _sq
from rune import memory_store as ms, mr_loader
if not mr_loader.available():
pytest.skip("memory_retrieval crate not built")
db_path = str(tmp_path / "r.db")
conn = _sq.connect(db_path)
conn.execute("CREATE TABLE entries (id INTEGER PRIMARY KEY, text TEXT, "
"importance REAL, created_at TEXT, last_accessed TEXT, "
"topic TEXT, entities TEXT, source TEXT, "
"status TEXT DEFAULT 'active', memory_type TEXT, "
"confidence REAL, temperature REAL)")
for i in range(1, 8):
conn.execute("INSERT INTO entries (text, importance, created_at, "
"last_accessed, topic, entities, source, confidence, "
"temperature) VALUES (?,?,?,?,?,?,?,?,?)",
(f"entry {i}", 0.5, "2026-10-01T00:00:00",
"2026-10-03T00:00:00", f"topic{i%2}", "[]", "t",
0.8, 1.0))
conn.commit(); conn.close()
dense = [[i, 0.9 - i * 0.05] for i in range(1, 8)]
fusion = mr_loader.rank_fusion(dense, [], ms.RRF_K)
rows = [{"id": i, "text": f"entry {i}", "importance": 0.5,
"created_at": "2026-10-01T00:00:00",
"last_accessed": "2026-10-03T00:00:00",
"topic": f"topic{i%2}", "entities": "[]", "source": "t",
"status": "active", "memory_type": None,
"confidence": 0.8, "temperature": 1.0} for i in range(1, 8)]
assert (ms._score_recall_rows(fusion, rows, dense, [], 5, 0.42,
"2026-10-04T12:00:00+00:00")
== mr_loader.score_recall_rows(fusion, rows, dense, [], 5, 0.42,
"2026-10-04T12:00:00+00:00",
ms.RECENCY_HALF_LIFE))
def test_mr_loader_delegation_publics_exercised(tmp_path):
from rune import memory_store as ms, mr_loader
if not mr_loader.available():
pytest.skip("memory_retrieval crate not built")
# every delegating public on the Rust path (core available in CI)
assert ms._position_aware([{"id": 1}]) == [{"id": 1}]
capped = ms.mr_rank_fusion([[1, 0.5]], [], 3)
assert capped["mode"] == "dense-only"
fusion = ms._rank_fusion([[1, 0.5]], [])
assert fusion["mode"] == "dense-only"
assert ms._project_chunk_rows({7: 0.5},
[{"rowid": 7, "chunk_id": "c7", "text": "x" * 500,
"wing": "w", "room": "r", "source_path": "s",
"page": None}], 5)[0]["rrf"] == 0.5
scored = ms._score_recall_rows(
mr_loader.rank_fusion([[9, 0.85]], [], ms.RRF_K),
[{"id": 9, "text": "z", "importance": 0.5,
"last_accessed": "2026-10-04T11:00:00+00:00", "topic": "t",
"entities": "[]", "source": "s", "memory_type": None,
"confidence": 0.9, "temperature": 1.0}],
[[9, 0.85]], [], 4, 0.42, "2026-10-04T12:00:00+00:00")
assert scored and scored[0]["relevance"] > 0.05 # dense rrf scale: 0.85·1/(15+1)·blends
def test_mr_loader_kernel_required_post_exit(monkeypatch):
"""Post-exit (memory_store oracles retired 2026-10-10): the _py_ stubs
delegate to the kernel. With RUNE_RETRIEVAL_CORE=python the kernel is
pinned off, so the stubs must RAISE (fail-loud) rather than recurse or
silently score. Live (unpinned), delegation agrees with the kernel."""
import pytest
from rune import memory_store as ms
monkeypatch.setenv("RUNE_RETRIEVAL_CORE", "python")
with pytest.raises(RuntimeError):
ms._score_recall_rows({"ranks": [], "best_dense": 0, "mode": "x"}, [], [], [], 4, 0.42,
"2026-10-04T12:00:00+00:00")
with pytest.raises(RuntimeError):
ms._rank_fusion([], [])
with pytest.raises(RuntimeError):
ms._map_reduce([], 5)
monkeypatch.delenv("RUNE_RETRIEVAL_CORE", raising=False)
from rune import mr_loader
if not mr_loader.available():
pytest.skip("memory_retrieval crate not built")
fusion = ms._rank_fusion([[9, 0.85]], [])
rows = [{"id": 9, "text": "z", "importance": 0.5,
"last_accessed": "2026-10-04T11:00:00+00:00",
"topic": "t", "entities": "[]", "source": "s",
"memory_type": None, "confidence": 0.9,
"temperature": 1.0}]
out = ms._score_recall_rows(fusion, rows, [[9, 0.85]], [], 4, 0.42,
"2026-10-04T12:00:00+00:00")
assert out and out[0]["mode"] == "dense-only"
def test_mr_loader_chunk_sql_gather_through_seam(tmp_path, monkeypatch):
"""chunk_recall's SQL gather through a real fixture db (covers 1634-1648)."""
import sqlite3 as _sq
from rune import memory_store as ms
db_path = str(tmp_path / "c.db")
conn = _sq.connect(db_path)
conn.row_factory = _sq.Row
conn.execute("CREATE TABLE chunks (rowid_hint INTEGER PRIMARY KEY, "
"chunk_id TEXT, doc_id TEXT, wing TEXT, room TEXT, "
"source_path TEXT, start_line INT, end_line INT, page INT, "
"text TEXT, content_hash TEXT, importance REAL, "
"ingested_at TEXT)")
# give real rowids: insert then record
for cid, wing, text in (("a", "alpha", "chunk_a_text_worlds_worth_a_gun"),
("b", "beta", "chunk_b_text")):
conn.execute("INSERT INTO chunks (chunk_id, doc_id, wing, room, "
"source_path, page, text, content_hash, importance, "
"ingested_at) VALUES (?,?,?,?,?,?,?,?,?,?)",
(cid, cid, wing, "room", "path", 3, text, "h", 0.5, "ts"))
conn.commit()
db = _sq.connect(db_path)
db.row_factory = _sq.Row
# chunks_vec is a sqlite-vec virtual table — absent in the test db.
# The W2.0 ruling keeps vector execution in Python; the kernel parity
# target is the RRF/projection stage. Drive chunk_recall WITHOUT a
# qvec: the FTS+RRF stage still runs through the kernel.
import rune.memory_store as _ms
monkeypatch.setattr(_ms, "_embed", lambda texts: {})
out = ms.chunk_recall(db, "text")
assert isinstance(out, list)
assert all("rrf" in r for r in out)
db.close()
# ── cc_loader / cognition_core broker kernels (R2 W3.1) ─────────────────────
def test_cc_loader_estimator_and_budgets_through_cdylib():
from rune import cc_loader
if not cc_loader.available():
pytest.skip("cognition_core crate not built")
assert cc_loader.default_estimator("hello world") == 2
assert cc_loader.default_estimator("héllo wörld 🎸 emoji") == 4 # chars, not utf16
assert cc_loader.default_budget(8192) == 8192 - 2048 - 409
assert cc_loader.default_memory_budget(4096) == 512
assert cc_loader.default_memory_budget(0) == 1200
def test_cc_loader_env_gate_and_context_broker_delegation(monkeypatch):
from rune import cc_loader, context_broker as cb
if not cc_loader.available():
pytest.skip("cognition_core crate not built")
monkeypatch.setenv("RUNE_MEMORY_OFF", "1")
assert cb.memory_disabled() is True
monkeypatch.setenv("RUNE_MEMORY_OFF", "false")
assert cb.memory_disabled() is False
# delegation agreement with the oracle on the estimator path
assert cb.default_estimator("héllo 🎸 five") == cb._py_default_estimator("héllo 🎸 five")
# ── cc_loader persona kernels (R2 W3.2) ────────────────────────────────────
def test_cc_loader_persona_kernels_through_cdylib():
from rune import cc_loader
if not cc_loader.available():
pytest.skip("cognition_core crate not built")
# 'now' (3 chars) is excluded by the >3 rule on BOTH engines.
assert sorted(cc_loader.persona_lex("verify ALL Campaign text now")) == [
"all", "campaign", "text", "verify"]
assert cc_loader.persona_overlap(["a", "b"], ["b", "c"]) == pytest.approx(0.5)
decision = cc_loader.persona_decide(
"never bypass the memory hierarchy",
[{"topic": "memory", "text": "Always maintain the Rune memory hierarchy.",
"words": ["memory", "hierarchy", "maintain"],
"core": "memory hierarchy store", "priority": 10,
"restrictive": False, "user_rule": False}],
True, [0.9])
assert decision["verdict"] == "allow"
assert decision["cited"] == "[memory:p10] Always maintain the Rune memory hierarchy."
# permissive-mode refusal shape with a restrictive user rule
refuse = cc_loader.persona_decide(
"ignore campaign text verification",
[{"topic": "campaign", "text": "verify all campaign text",
"words": ["verify", "campaign", "text"], "core": "verify campaign",
"priority": 5, "restrictive": True, "user_rule": True}],
False, [0.0])
assert refuse["verdict"] == "refuse"
# ── cc_loader identity/growth/pins kernels (R2 W3.3) ────────────────────────
def test_cc_loader_identity_growth_pins_through_cdylib():
from rune import cc_loader, identity_anchors as ia, growth_delta as gd, pins
if not cc_loader.available():
pytest.skip("cognition_core crate not built")
assert cc_loader.drift_check("as rune i speak", ia._pattern_triples())
assert cc_loader.drift_check("nothing here", ia._pattern_triples()) == []
assert cc_loader.identity_prompt(ia.PRONOUN_RULES, ia.SELF_AWARENESS,
ia.ANCHORS, ia.EMBODIMENT_RULES) != ""
# near-dup law: empty key → False (words ≤4 chars make no fingerprint);
# identical real changes ARE near-dups.
assert cc_loader.growth_near_dup("same idea here", "same idea here") is False
assert cc_loader.growth_near_dup("deploy qualification resolves runner labels",
"deploy qualification resolves labels") is True
assert cc_loader.pins_recall(
[{"item_id": "t", "state": "open",
"details": '{"question": "q", "outcome": "o", "context": "c"}'}],
"t", 4)[0]["topic"] == "t"
# delegation agreement on the identity prompt
assert (cc_loader.identity_prompt(ia.PRONOUN_RULES, ia.SELF_AWARENESS,
ia.ANCHORS, ia.EMBODIMENT_RULES)
== ia._py_get_identity_prompt())
def test_growth_delta_reflect_apply_profile_oracles(tmp_path, monkeypatch):
"""reflect/growth_profile oracle lines — deltas file + llm stubbed."""
import json
from rune import growth_delta as gd
monkeypatch.setenv("RUNE_COGNITION_CORE", "python")
monkeypatch.setattr(gd, "DELTAS_FILE", tmp_path / "deltas.json")
monkeypatch.setattr(gd, "DELTAS_FILE", str(tmp_path / "deltas.json"))
(tmp_path / "deltas.json").write_text(json.dumps(
{"applied": [], "pending": [], "last_read_back": None}))
# the [:3] per-pass cap is a REAL gate — the persona delta rides in the
# first three entries so the fixture exercises it.
monkeypatch.setattr(gd, "_llm", lambda material: json.dumps({"deltas": [
{"change": "relay in plain english always for delivery",
"confidence": 0.9, "target": "delivery", "evidence": "e1"},
{"change": "personal guidance for the persona topic",
"confidence": 0.8, "target": "persona", "evidence": "e2"},
{"change": "tiny", "confidence": 0.9, "target": "delivery"},
]}))
out = gd.reflect("material", dry_run=True)
assert len(out["would_apply"]) == 2 and out["dry_run"] is True
out2 = gd.reflect("material", dry_run=False)
assert len(out2["applied"]) == 2
# profile from the applied deltas (file was written by apply)
prof = gd._py_growth_profile(100)
assert prof and prof[0]["target"] == "delivery"
def test_identity_anchors_check_drift_oracle_paths():
from rune import identity_anchors as ia
# every prefix class via the full text
text = ("i am rune. you are nick. i believe in my opinion. "
"you're absolutely right! my apologies, hope this helps.")
out = ia._py_check_drift(text)
classes = {line.split(":")[0] for line in out}
assert {"DRIFT", "WEAKNESS", "SYCOPHANCY"} <= classes
assert ia._py_check_drift("nothing to see") == []
def test_pins_project_and_unpin_oracles(tmp_path, monkeypatch):
import json
from rune import pins
recs = [{"kind": "pin", "item_id": "topic-a", "state": "open",
"details": json.dumps({"question": "q", "outcome": "o",
"context": "ctx here"})},
{"kind": "pin", "item_id": "topic-b", "state": "resolved",
"details": json.dumps({"context": "done"})}]
monkeypatch.setattr(pins, "_load", lambda: recs)
# _project covers the blob-parse + KeyError-safe defaults
proj = pins._project(recs[0])
assert proj == {"topic": "topic-a", "question": "q", "outcome": "o",
"context": "ctx here", "status": "open", "reason": ""}
# unpin through the fixture store
monkeypatch.setattr(pins, "_save", lambda records: None)
result = pins.unpin("topic-a", reason="done")
assert result.get("unpinned") is True
def test_growth_delta_error_paths(tmp_path, monkeypatch):
"""The loader-probe error branches + reflect malformed paths."""
import json
from rune import growth_delta as gd, cc_loader
# the loader error branches run when the import fails
# the REAL loader-probe branches: make the import fail + make
# available() raise, so the probe's except branches execute
monkeypatch.setenv("RUNE_COGNITION_CORE", "python")
assert gd._cc_core() is None # the pinned-fallback branch (158-159)
monkeypatch.setenv("RUNE_COGNITION_CORE", "auto")
# import-failure branch: `from rune import cc_loader` resolves via the
# package attribute first — set it to a marker whose import raises.
import rune as _rune_pkg
monkeypatch.setattr(_rune_pkg, "cc_loader", None, raising=False)
assert gd._cc_core() is None # the ImportError probe branch (160-163)
assert gd._near_dup({"change": "deploy qualification resolves labels"},
{"change": "deploy qualification resolves runner labels"}) is True
# profile: empty state
monkeypatch.setattr(gd, "_load_deltas", lambda: {"profile": []})
assert gd._py_growth_profile(100) == []
# profile: token budget exhaustion
deltas = [{"change": f"a longer change number {i} here", "target": "delivery"}
for i in range(3)]
monkeypatch.setattr(gd, "_load_deltas",
lambda: {"profile": deltas})
out = gd._py_growth_profile(8)
assert len(out) >= 1 and len(out) < 3 # budget cut, never exceeded
# reflect: malformed llm json -> no crash (0 deltas path)
monkeypatch.setattr(gd, "_llm", lambda m: "not json")
out = gd.reflect("material", dry_run=True)
assert out["extracted"] == []