Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6740c86c82 | ||
|
|
bd31a6dde9 | ||
|
|
c82f83a87d | ||
|
|
70c3311fca | ||
|
|
cb4977fc79 | ||
|
|
52314af121 | ||
|
|
fd4b4d3254 | ||
|
|
c912b2bc3e | ||
|
|
590c4466ff | ||
|
|
ee1d1c106c | ||
|
|
f7c00cbdf7 | ||
|
|
25eb12c656 | ||
|
|
5881b78713 | ||
|
|
f97c8c1ff4 | ||
|
|
588e2f2522 | ||
|
|
1057cded97 | ||
|
|
e11b485a78 | ||
|
|
d9d575ac07 | ||
|
|
50eff50902 | ||
|
|
ea65b7c9d0 | ||
|
|
e790ad70aa | ||
|
|
edbd27b9ff | ||
|
|
6276f21aff | ||
|
|
313f1c9972 | ||
|
|
8549cee9d9 | ||
|
|
511c4b246e | ||
|
|
e96ff0c50e | ||
|
|
41ecd72c41 | ||
|
|
b953e02156 | ||
|
|
2066ea9bb9 | ||
|
|
5666654738 | ||
|
|
3239080c9b | ||
|
|
96f521c7ad | ||
|
|
a86a6d0167 | ||
|
|
9d08c01317 | ||
|
|
63558a11e8 | ||
|
|
8acf0a617f | ||
|
|
6a9eaddd67 | ||
|
|
54b5e52027 | ||
|
|
e1e88a7f6a | ||
|
|
e1d5ace328 | ||
|
|
44225afa88 | ||
|
|
0f5a5f927d | ||
|
|
ca986124a5 | ||
|
|
cfbe5b34cc | ||
|
|
0a7d0b7386 | ||
|
|
3b67c63482 | ||
|
|
d9fb666e6b | ||
|
|
fd71815026 | ||
|
|
ab1ce8661b | ||
|
|
265e558d3f | ||
|
|
20f2baf7b4 | ||
|
|
b2ac8c85e3 | ||
|
|
2a2d144a03 |
No files matched your search
@@ -357,6 +357,12 @@ jobs:
|
||||
- name: memory-store-deep text-kernel parity gate (HARD — #2479 batch: fts/mapreduce/entities)
|
||||
run: |
|
||||
cd src/go/memory-store-deep && go build -o /tmp/msd-${{ gitea.run_id }} . && go test -run "TestTextKernelsParity|TestDriftRerankBlendParity" -v
|
||||
- name: scaffold builders parity gate (HARD — #2479 batch: 7 pure builders)
|
||||
run: |
|
||||
cd src/go/scaffold && go build -o /tmp/scaffold-${{ gitea.run_id }} . && go test -run TestBuildersParity -v
|
||||
- name: tool-executor prepared-path parity gate (HARD — #2479 batch)
|
||||
run: |
|
||||
cd src/go/tool-executor && go build -o /tmp/tool-exec-${{ gitea.run_id }} . && go test -run TestPreparedPathParity -v
|
||||
- name: go race detector (every module's test suite under -race)
|
||||
run: |
|
||||
for dir in src/go/*/; do
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Rune
|
||||
|
||||
**Current release: v0.166.0**
|
||||
**Current release: v0.178.0**
|
||||
|
||||
**Rune is a persistent personal agent designed to accumulate experience, develop reusable competence, and remain recognisably the same agent even when its underlying foundation model changes.**
|
||||
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "rune"
|
||||
version = "0.166.0"
|
||||
version = "0.178.0"
|
||||
description = "Rune — a stateful coding assistant with persistent memory, orchestration, and TUI"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package main
|
||||
|
||||
// builders.go — #2479 scaffold batch: the 7 pure Project builders
|
||||
// (add_domain/component/contract/link/prd/next_action/limitation).
|
||||
// Each is a thin entity/relationship constructor over the shared doc shape
|
||||
// (structural_store.add_entity/add_relationship semantics). Oracle:
|
||||
// src/rune/scaffold.py; truth rows in truth_builders.json.
|
||||
|
||||
import (
|
||||
"sort"
|
||||
)
|
||||
|
||||
func builderEntity(doc map[string]interface{}, id, kind string, identities map[string]interface{}) map[string]interface{} {
|
||||
ents, _ := doc["entities"].([]map[string]interface{})
|
||||
for _, e := range ents {
|
||||
if eid, _ := e["id"].(string); eid == id {
|
||||
if im, ok := e["identities"].(map[string]interface{}); ok {
|
||||
for k, v := range identities {
|
||||
im[k] = v
|
||||
}
|
||||
}
|
||||
return e
|
||||
}
|
||||
}
|
||||
e := map[string]interface{}{
|
||||
"id": id,
|
||||
"kind": kind,
|
||||
"maturity": "DECLARED",
|
||||
"tags": []string{},
|
||||
"identities": identities,
|
||||
"evidence_refs": []string{"scaffold"},
|
||||
}
|
||||
doc["entities"] = append(ents, e)
|
||||
return e
|
||||
}
|
||||
|
||||
func builderRel(doc map[string]interface{}, relType, fromID, toID string, evidence []string) {
|
||||
rels, _ := doc["relationships"].([]map[string]interface{})
|
||||
for _, r := range rels {
|
||||
if r["type"] == relType && r["from"] == fromID && r["to"] == toID {
|
||||
return
|
||||
}
|
||||
}
|
||||
ev := evidence
|
||||
if len(ev) == 0 {
|
||||
ev = []string{"scaffold"}
|
||||
}
|
||||
doc["relationships"] = append(rels, map[string]interface{}{
|
||||
"type": relType, "from": fromID, "to": toID, "evidence_refs": ev,
|
||||
})
|
||||
}
|
||||
|
||||
// AddDomain — domain:<name> entity.
|
||||
func AddDomain(doc map[string]interface{}, name, description string) map[string]interface{} {
|
||||
return builderEntity(doc, "domain:"+name, "domain", map[string]interface{}{"description": description})
|
||||
}
|
||||
|
||||
// AddComponent — component:<name> entity.
|
||||
func AddComponent(doc map[string]interface{}, name, path, description string) map[string]interface{} {
|
||||
return builderEntity(doc, "component:"+name, "component", map[string]interface{}{"path": path, "description": description})
|
||||
}
|
||||
|
||||
// AddContract — contract:<name> entity (spec defaults "" per the oracle).
|
||||
func AddContract(doc map[string]interface{}, name, description string) map[string]interface{} {
|
||||
return builderEntity(doc, "contract:"+name, "contract", map[string]interface{}{"description": description, "spec": ""})
|
||||
}
|
||||
|
||||
// Link — generic typed relationship with evidence.
|
||||
func Link(doc map[string]interface{}, relType, fromID, toID string) map[string]interface{} {
|
||||
builderRel(doc, relType, fromID, toID, []string{"scaffold"})
|
||||
rels, _ := doc["relationships"].([]map[string]interface{})
|
||||
return rels[len(rels)-1]
|
||||
}
|
||||
|
||||
// SetPRD — prd:<project> reference entity.
|
||||
func SetPRD(doc map[string]interface{}, projectID, prdRef string) map[string]interface{} {
|
||||
return builderEntity(doc, "prd:"+projectID, "prd_state", map[string]interface{}{"reference": prdRef})
|
||||
}
|
||||
|
||||
// SetNextAction — next_action:<project> entity.
|
||||
func SetNextAction(doc map[string]interface{}, projectID, action string) map[string]interface{} {
|
||||
return builderEntity(doc, "next_action:"+projectID, "next_action", map[string]interface{}{"action": action})
|
||||
}
|
||||
|
||||
// AddLimitation — limitation:<name> entity.
|
||||
func AddLimitation(doc map[string]interface{}, name, detail string) map[string]interface{} {
|
||||
return builderEntity(doc, "limitation:"+name, "known_limitation", map[string]interface{}{"detail": detail})
|
||||
}
|
||||
|
||||
// SortedStrings — deterministic evidence ordering (Python sorted(set())).
|
||||
func SortedStrings(in []string) []string {
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
for _, s := range in {
|
||||
if !seen[s] {
|
||||
seen[s] = true
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"_doc": "FROZEN ORACLE (scaffold builders).",
|
||||
"entities": [
|
||||
{
|
||||
"id": "domain:d1",
|
||||
"kind": "domain",
|
||||
"identities": {
|
||||
"description": "desc d1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "component:c1",
|
||||
"kind": "component",
|
||||
"identities": {
|
||||
"path": "p",
|
||||
"description": "desc c1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "contract:k1",
|
||||
"kind": "contract",
|
||||
"identities": {
|
||||
"description": "desc k1",
|
||||
"spec": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "prd:testproj",
|
||||
"kind": "prd_state",
|
||||
"identities": {
|
||||
"reference": "docs/prd.md"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "next_action:testproj",
|
||||
"kind": "next_action",
|
||||
"identities": {
|
||||
"action": "do the thing"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "limitation:l1",
|
||||
"kind": "known_limitation",
|
||||
"identities": {
|
||||
"detail": "detail l1"
|
||||
}
|
||||
}
|
||||
],
|
||||
"relationships": [
|
||||
{
|
||||
"type": "contains",
|
||||
"from": "domain:d1",
|
||||
"to": "component:c1"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package main
|
||||
|
||||
// truth_builders_test.go — #2479 scaffold-batch parity gate.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBuildersParity(t *testing.T) {
|
||||
raw, err := os.ReadFile("truth_builders.json")
|
||||
if err != nil {
|
||||
t.Fatalf("truth_builders.json missing: %v", err)
|
||||
}
|
||||
var truth struct {
|
||||
Entities []map[string]any `json:"entities"`
|
||||
Relationships []map[string]any `json:"relationships"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &truth); err != nil {
|
||||
t.Fatalf("unparseable: %v", err)
|
||||
}
|
||||
doc := map[string]interface{}{"entities": []map[string]interface{}{}, "relationships": []map[string]interface{}{}}
|
||||
AddDomain(doc, "d1", "desc d1")
|
||||
AddComponent(doc, "c1", "p", "desc c1")
|
||||
AddContract(doc, "k1", "desc k1")
|
||||
Link(doc, "contains", "domain:d1", "component:c1")
|
||||
SetPRD(doc, "testproj", "docs/prd.md")
|
||||
SetNextAction(doc, "testproj", "do the thing")
|
||||
AddLimitation(doc, "l1", "detail l1")
|
||||
ents, _ := doc["entities"].([]map[string]interface{})
|
||||
if len(ents) != len(truth.Entities) {
|
||||
t.Fatalf("entities: got %d want %d", len(ents), len(truth.Entities))
|
||||
}
|
||||
for i, e := range ents {
|
||||
w := truth.Entities[i]
|
||||
if e["id"] != w["id"] || e["kind"] != w["kind"] {
|
||||
t.Errorf("entity[%d]: got %v/%v want %v/%v", i, e["id"], e["kind"], w["id"], w["kind"])
|
||||
}
|
||||
gotIdent, _ := json.Marshal(e["identities"])
|
||||
wantIdent, _ := json.Marshal(w["identities"])
|
||||
if string(gotIdent) != string(wantIdent) {
|
||||
t.Errorf("entity[%d] identities: got %s want %s", i, gotIdent, wantIdent)
|
||||
}
|
||||
}
|
||||
rels, _ := doc["relationships"].([]map[string]interface{})
|
||||
if len(rels) != len(truth.Relationships) {
|
||||
t.Fatalf("relationships: got %d want %d", len(rels), len(truth.Relationships))
|
||||
}
|
||||
for i, r := range rels {
|
||||
w := truth.Relationships[i]
|
||||
if r["type"] != w["type"] || r["from"] != w["from"] || r["to"] != w["to"] {
|
||||
t.Errorf("rel[%d]: got %v want %v", i, r, w)
|
||||
}
|
||||
}
|
||||
var _ = reflect.DeepEqual
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
// prepared_path.go — #2479 tool_executor batch: the _prepared_path kernel
|
||||
// (write/edit/format gate: path required, write-validation, ValueError
|
||||
// contract). Oracle: src/rune/tool_executor.py; truth rows in
|
||||
// truth_prepared_path.json. Execution stays in the runtime.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// PreparedPath — which-file + resolved path for write-class tools, or ""
|
||||
// when the tool needs no path prep. Errors carry the ValueError contract
|
||||
// (path required / validation message).
|
||||
func PreparedPath(name string, args map[string]interface{}) (string, string, error) {
|
||||
switch name {
|
||||
case "write_file", "edit_file", "format_code":
|
||||
// fall through
|
||||
default:
|
||||
return "", "", nil
|
||||
}
|
||||
raw, _ := args["path"].(string)
|
||||
if raw == "" {
|
||||
return "", "", fmt.Errorf("Path is required")
|
||||
}
|
||||
ok, msg, resolved := ValidateWritePath(raw)
|
||||
if !ok {
|
||||
return "", "", fmt.Errorf("%s", msg)
|
||||
}
|
||||
return raw, resolved, nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"_doc": "FROZEN ORACLE (prepared_path).",
|
||||
"rows": [
|
||||
{
|
||||
"op": "prepared",
|
||||
"name": "write_file",
|
||||
"args": {
|
||||
"path": "/tmp/x.txt"
|
||||
},
|
||||
"raises": true
|
||||
},
|
||||
{
|
||||
"op": "prepared",
|
||||
"name": "read_file",
|
||||
"args": {
|
||||
"path": "/tmp/x"
|
||||
},
|
||||
"want": null
|
||||
},
|
||||
{
|
||||
"op": "prepared",
|
||||
"name": "edit_file",
|
||||
"args": {
|
||||
"path": ""
|
||||
},
|
||||
"raises": true
|
||||
},
|
||||
{
|
||||
"op": "prepared",
|
||||
"name": "run_command",
|
||||
"args": {
|
||||
"cmd": "ls"
|
||||
},
|
||||
"want": null
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package main
|
||||
|
||||
// truth_prepared_path_test.go — #2479 tool_executor parity gate.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPreparedPathParity(t *testing.T) {
|
||||
raw, err := os.ReadFile("truth_prepared_path.json")
|
||||
if err != nil {
|
||||
t.Fatalf("truth_prepared_path.json missing: %v", err)
|
||||
}
|
||||
var doc struct {
|
||||
Rows []struct {
|
||||
Name string `json:"name"`
|
||||
Args map[string]any `json:"args"`
|
||||
Want []string `json:"want"`
|
||||
} `json:"rows"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &doc); err != nil {
|
||||
t.Fatalf("unparseable: %v", err)
|
||||
}
|
||||
for i, c := range doc.Rows {
|
||||
req, resolved, err := PreparedPath(c.Name, c.Args)
|
||||
if c.Want == nil {
|
||||
if err == nil && req == "" {
|
||||
continue // no prep needed — nil want
|
||||
}
|
||||
if err != nil {
|
||||
continue // raises — want nil means raises here
|
||||
}
|
||||
t.Errorf("row %d %s: expected raise/none, got %q %q", i, c.Name, req, resolved)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("row %d %s: unexpected error %v", i, c.Name, err)
|
||||
continue
|
||||
}
|
||||
// resolved path must be absolute; requested echoes input
|
||||
if req != c.Want[0] {
|
||||
t.Errorf("row %d: requested %q want %q", i, req, c.Want[0])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ This is the main entry point for the Rune program.
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
__version__ = "0.166.0"
|
||||
__version__ = "0.178.0"
|
||||
|
||||
# One build identity (handoff 2026-09-10 §4): the semantic version above is
|
||||
# the repo-level truth (auto-bumped at merge); the DEPLOYED revision (exact
|
||||
|
||||
@@ -233,7 +233,7 @@ def main() -> int:
|
||||
)
|
||||
check(
|
||||
"Rune minor version advertises provisioning and restore verification",
|
||||
'__version__ = "0.166.0"' in rune_version,
|
||||
'__version__ = "0.178.0"' in rune_version,
|
||||
failures,
|
||||
)
|
||||
# #169 policy update: auto-bump on merge is sanctioned (Nick directive:
|
||||
|
||||
@@ -620,161 +620,13 @@ def score_card(card, query):
|
||||
|
||||
|
||||
def _py_score_card(card, query):
|
||||
"""Python core of score_card (parity oracle for the Rust core)."""
|
||||
query_low = query.lower()
|
||||
query_words = set(re.findall(r"\w+", query_low))
|
||||
|
||||
# Generic capabilities that shouldn't drive matching
|
||||
generic_caps = {
|
||||
"write",
|
||||
"read",
|
||||
"audit",
|
||||
"memory_env",
|
||||
"status",
|
||||
"reasoning",
|
||||
"research",
|
||||
"voice",
|
||||
"growth",
|
||||
"skills",
|
||||
"tasks",
|
||||
"recall",
|
||||
}
|
||||
|
||||
# Common stopwords to exclude from matching
|
||||
stopwords = {
|
||||
"the",
|
||||
"a",
|
||||
"an",
|
||||
"is",
|
||||
"are",
|
||||
"was",
|
||||
"were",
|
||||
"be",
|
||||
"been",
|
||||
"being",
|
||||
"have",
|
||||
"has",
|
||||
"had",
|
||||
"do",
|
||||
"does",
|
||||
"did",
|
||||
"will",
|
||||
"would",
|
||||
"could",
|
||||
"should",
|
||||
"may",
|
||||
"might",
|
||||
"shall",
|
||||
"can",
|
||||
"to",
|
||||
"of",
|
||||
"in",
|
||||
"for",
|
||||
"on",
|
||||
"with",
|
||||
"at",
|
||||
"by",
|
||||
"from",
|
||||
"as",
|
||||
"into",
|
||||
"through",
|
||||
"during",
|
||||
"before",
|
||||
"after",
|
||||
"above",
|
||||
"below",
|
||||
"between",
|
||||
"out",
|
||||
"off",
|
||||
"over",
|
||||
"under",
|
||||
"again",
|
||||
"further",
|
||||
"then",
|
||||
"once",
|
||||
"here",
|
||||
"there",
|
||||
"when",
|
||||
"where",
|
||||
"why",
|
||||
"how",
|
||||
"all",
|
||||
"each",
|
||||
"every",
|
||||
"both",
|
||||
"few",
|
||||
"more",
|
||||
"most",
|
||||
"other",
|
||||
"some",
|
||||
"such",
|
||||
"no",
|
||||
"nor",
|
||||
"not",
|
||||
"only",
|
||||
"own",
|
||||
"same",
|
||||
"so",
|
||||
"than",
|
||||
"too",
|
||||
"very",
|
||||
"just",
|
||||
"because",
|
||||
"but",
|
||||
"and",
|
||||
"or",
|
||||
"if",
|
||||
"while",
|
||||
"about",
|
||||
"against",
|
||||
"this",
|
||||
"that",
|
||||
"these",
|
||||
"those",
|
||||
"it",
|
||||
"its",
|
||||
"what",
|
||||
"which",
|
||||
"who",
|
||||
}
|
||||
query_content = query_words - stopwords
|
||||
|
||||
score = 0.0
|
||||
|
||||
# Direct capability name match (highest weight, but penalize generic)
|
||||
for cap in card.get("capabilities", []):
|
||||
cap_words = set(re.findall(r"\w+", cap.lower()))
|
||||
overlap = query_content & cap_words
|
||||
if overlap:
|
||||
if cap.lower() in generic_caps:
|
||||
score += 0.3 * len(overlap)
|
||||
else:
|
||||
score += 3.0 * len(overlap)
|
||||
|
||||
# Description word match (medium weight)
|
||||
desc_words = set(re.findall(r"\w+", card.get("description", "").lower())) - stopwords
|
||||
overlap = query_content & desc_words
|
||||
score += 0.8 * len(overlap)
|
||||
|
||||
# Semantic example match (high weight — these are curated)
|
||||
for example in card.get("semantic_examples", []):
|
||||
example_words = set(re.findall(r"\w+", example.lower())) - stopwords
|
||||
overlap = query_content & example_words
|
||||
if overlap:
|
||||
score += 2.0 * len(overlap)
|
||||
|
||||
# Name match (very high weight — direct name reference)
|
||||
name_words = set(re.findall(r"\w+", card.get("name", "").lower()))
|
||||
overlap = query_words & name_words
|
||||
if overlap:
|
||||
score += 4.0 * len(overlap)
|
||||
|
||||
# Priority bonus (lower number = higher priority)
|
||||
priority = card.get("priority", 100)
|
||||
score += max(0, (100 - priority) / 200)
|
||||
|
||||
return score
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/capability_scoring (cs_score_card — parity proven against the
|
||||
frozen oracle in frozen_score_card.json). Delegation-only stub."""
|
||||
core = _cs_core()
|
||||
if core is None:
|
||||
raise RuntimeError("capability_scoring kernel not built — run the capability_scoring build; the Python oracle was retired")
|
||||
return core.score_card(card, query)
|
||||
|
||||
def match_capabilities(query, top_k=5):
|
||||
"""Find the most relevant capabilities for a query."""
|
||||
|
||||
@@ -164,42 +164,13 @@ def _sc_core():
|
||||
|
||||
|
||||
def _py_language_placement(project: str, characteristics: list[str]) -> dict:
|
||||
"""Python core of language_placement (parity oracle)."""
|
||||
go_signals = ("initiate", "respond", "route", "dispatch", "reactive",
|
||||
"user-facing", "turn-time", "chat", "event", "tool",
|
||||
"model", "provider", "http", "network", "subprocess",
|
||||
"threading", "server", "cron", "message", "voice",
|
||||
"operator", "transport")
|
||||
rust_signals = ("compute", "store", "score", "compress", "threshold",
|
||||
"parity", "dedup", "classify", "extract", "assemble",
|
||||
"memory", "cognition", "ledger", "spine", "structural",
|
||||
"deterministic", "pure-function", "drift", "pin",
|
||||
"identity", "construction", "contract")
|
||||
chars = [c.lower() for c in characteristics]
|
||||
go_hits = [s for s in go_signals if any(s in c for c in chars)]
|
||||
rust_hits = [s for s in rust_signals if any(s in c for c in chars)]
|
||||
if project.lower() == "rune":
|
||||
if go_hits and not rust_hits:
|
||||
placement, rule = "go", "rune dichotomy: reactive/initiating markers"
|
||||
elif rust_hits and not go_hits:
|
||||
placement, rule = "rust", "rune dichotomy: deterministic/state markers"
|
||||
elif rust_hits and go_hits:
|
||||
placement, rule = "hybrid", "rune dichotomy: both marker classes — a contracted membrane junction"
|
||||
else:
|
||||
placement, rule = "rust", "rune dichotomy: pure compute defaults to the deterministic backend"
|
||||
else:
|
||||
if go_hits and not rust_hits:
|
||||
placement, rule = "go", "characteristic fit: reactive/network profile"
|
||||
elif rust_hits and not go_hits:
|
||||
placement, rule = "rust", "characteristic fit: deterministic/state profile"
|
||||
elif rust_hits:
|
||||
placement, rule = "hybrid", "characteristic fit: mixed profile — split at the membrane"
|
||||
else:
|
||||
placement, rule = "unassessed", "no placement signals — the unit needs characteristics recorded"
|
||||
return {"placement": placement, "rule": rule,
|
||||
"evidence": {"go_signals": go_hits, "rust_signals": rust_hits}}
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/scaffold_core (sc_language_placement — parity proven against the
|
||||
frozen oracle in frozen_language_placement.json). Delegation-only stub."""
|
||||
core = _sc_core()
|
||||
if core is None:
|
||||
raise RuntimeError("scaffold_core kernel not built — run the scaffold_core build; the Python oracle was retired")
|
||||
return core.language_placement(project, characteristics)
|
||||
def classify_surface(surface: str) -> str:
|
||||
"""Classify one affected-surface entry (open-world; Tranche 5 §3).
|
||||
Kinds: structural_entity | source_path | workflow_config | ui_component |
|
||||
|
||||
+15
-61
@@ -108,51 +108,14 @@ def compute_value(entry: dict, current_goals: List[str] | None = None) -> float:
|
||||
|
||||
def _py_compute_value(entry: dict, current_goals: List[str] | None = None,
|
||||
now: str | None = None) -> float:
|
||||
"""Python core of compute_value (parity oracle for the Rust core).
|
||||
`now` is an ISO-8601 string; None resolves the wall clock (production)."""
|
||||
proven = entry.get("wash_count", 0) or 0 # column name preserved for compatibility
|
||||
imp = entry.get("importance", 0.5) or 0.5
|
||||
|
||||
# Proven use factor: logarithmic scaling (diminishing returns)
|
||||
proven_factor = min(1.0, math.log1p(proven) / math.log1p(PROVEN_USES_THRESHOLD))
|
||||
|
||||
# Recency factor: exponential decay
|
||||
now_dt = datetime.fromisoformat(now) if now else datetime.now(timezone.utc)
|
||||
recency = 1.0
|
||||
last_accessed = entry.get("last_accessed") or entry.get("last_washed")
|
||||
if last_accessed:
|
||||
try:
|
||||
last = datetime.fromisoformat(last_accessed)
|
||||
hours_since = max(0.1, (now_dt - last).total_seconds() / 3600)
|
||||
recency = max(0.1, 1.0 / (1.0 + hours_since / (RECENCY_HALF_LIFE_DAYS * 24)))
|
||||
except (ValueError, TypeError):
|
||||
recency = 0.5
|
||||
|
||||
# Reliability factor: based on access pattern consistency
|
||||
# (placeholder — full implementation needs access history tracking)
|
||||
reliability = min(1.0, proven / max(1, RELIABILITY_WINDOW))
|
||||
|
||||
# Goal relevance factor: keyword overlap with current goals
|
||||
goal_relevance = 0.5 # default when no goals provided
|
||||
if current_goals:
|
||||
text = entry.get("text", "").lower()
|
||||
goal_words = set()
|
||||
for g in current_goals:
|
||||
goal_words.update(g.lower().split())
|
||||
text_words = set(text.split())
|
||||
overlap = len(goal_words & text_words)
|
||||
goal_relevance = min(1.0, overlap / max(1, len(goal_words) * 0.3))
|
||||
|
||||
# Weighted combination
|
||||
value = (
|
||||
WEIGHT_PROVEN_USES * proven_factor
|
||||
+ WEIGHT_IMPORTANCE * imp
|
||||
+ WEIGHT_RECENCY * recency
|
||||
+ WEIGHT_RELIABILITY * reliability
|
||||
+ WEIGHT_GOAL_RELEVANCE * goal_relevance
|
||||
)
|
||||
|
||||
return round(value, 4)
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_scoring (ms_compute_value — adversarial edges fixed:
|
||||
non-numeric/out-of-domain wash_count ERRORS via the envelope, bool parity
|
||||
preserved). Delegation-only stub; raises if the kernel is absent."""
|
||||
core = _ms_core()
|
||||
if core is None:
|
||||
raise RuntimeError("memory_scoring kernel not built — run the memory_scoring build; the Python oracle was retired")
|
||||
return core.compute_value(entry, current_goals, now if now is not None else _now_iso(None))
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
@@ -180,22 +143,13 @@ def check_promotion_eligibility(entry: dict) -> Tuple[bool, str]:
|
||||
|
||||
def _py_check_promotion_eligibility(entry: dict,
|
||||
now: str | None = None) -> Tuple[bool, str]:
|
||||
"""Python core of check_promotion_eligibility (parity oracle)."""
|
||||
wash = entry.get("wash_count", 0) or 0
|
||||
status = entry.get("rock_status", "washable")
|
||||
|
||||
if status == "rock":
|
||||
return False, "already rock"
|
||||
|
||||
if wash < PROVEN_USES_THRESHOLD:
|
||||
return False, f"proven_uses {wash} < threshold {PROVEN_USES_THRESHOLD}"
|
||||
|
||||
value = _py_compute_value(entry, now=now)
|
||||
if value < 0.6:
|
||||
return False, f"value {value:.3f} < 0.6 minimum"
|
||||
|
||||
return True, f"wash_count={wash}, value={value:.3f}"
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_scoring (ms_check_promotion_eligibility). Delegation-only
|
||||
stub; raises if the kernel is absent."""
|
||||
core = _ms_core()
|
||||
if core is None:
|
||||
raise RuntimeError("memory_scoring kernel not built — run the memory_scoring build; the Python oracle was retired")
|
||||
return core.check_promotion_eligibility(entry, now if now is not None else _now_iso(None))
|
||||
|
||||
def promote_entry(db, entry_id: int) -> dict:
|
||||
"""Promote an entry through the lifecycle: washable → established → rock.
|
||||
|
||||
@@ -213,7 +213,14 @@ class MemorySelector:
|
||||
|
||||
def _score_of(item: dict) -> float:
|
||||
"""Extract the item's 0-1 relevance under the ONE floor. Missing or
|
||||
malformed scores floor at 0.0 (abstain) — never guessed upward."""
|
||||
malformed scores floor at 0.0 (abstain) — never guessed upward.
|
||||
Delegates to the Rust core when built (frozen_selector.json parity)."""
|
||||
try:
|
||||
from rune import mr_loader as _mr
|
||||
if _mr.available():
|
||||
return float(_mr.score_of(item))
|
||||
except Exception: # noqa: BLE001 — kernel failure → oracle below
|
||||
pass
|
||||
value = item.get("score")
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
return 0.0
|
||||
@@ -311,6 +318,12 @@ def _lex_overlap_score(text: str, query: str) -> float:
|
||||
conjunctive logic the store's BM25 gate applies (a shared single word is
|
||||
not a relation, but zero shared words is definitely not one).
|
||||
"""
|
||||
try:
|
||||
from rune import mr_loader as _mr2
|
||||
if _mr2.available():
|
||||
return float(_mr2.lex_overlap_score(text, query))
|
||||
except Exception: # noqa: BLE001 — kernel failure → oracle below
|
||||
pass
|
||||
stopwords = getattr(memory_store, "_STOPWORDS", set())
|
||||
q_terms = {t.lower() for t in query.split() if len(t) > 3 and t.lower() not in stopwords}
|
||||
if not q_terms:
|
||||
|
||||
+52
-305
@@ -780,72 +780,12 @@ def _score_recall_rows(fusion, rows, dense, bm25, budget, min_score, now):
|
||||
RECENCY_HALF_LIFE)
|
||||
|
||||
|
||||
def _py_score_recall_rows(fusion, rows, dense, bm25, budget, min_score,
|
||||
now, recency_half_life=RECENCY_HALF_LIFE):
|
||||
"""Python oracle for the Rust scoring/abstention kernel."""
|
||||
from datetime import datetime
|
||||
|
||||
ranks = dict(fusion["ranks"])
|
||||
best_dense = fusion["best_dense"]
|
||||
retrieval_mode = fusion["mode"]
|
||||
by_id = {row["id"]: row for row in rows}
|
||||
scored = []
|
||||
now_dt = datetime.fromisoformat(now)
|
||||
for eid, base in sorted(ranks.items(), key=lambda item: -item[1]):
|
||||
row = by_id.get(eid)
|
||||
if not row:
|
||||
continue
|
||||
conf = float(row.get("confidence") or 0.7)
|
||||
temp = float(row.get("temperature") or 1.0)
|
||||
recency = 1.0
|
||||
try:
|
||||
la = row.get("last_accessed")
|
||||
if la:
|
||||
t_last = datetime.fromisoformat(la.replace("Z", "+00:00"))
|
||||
days = (now_dt - t_last).total_seconds() / 86400.0
|
||||
if days >= 0:
|
||||
recency = recency_half_life / (recency_half_life + days)
|
||||
except Exception:
|
||||
logger.debug("recall score kernel timestamp failed", exc_info=True)
|
||||
if dense:
|
||||
relevance = base * (0.4 + 0.6 * conf) * (0.5 + 0.5 * temp) * (0.85 + 0.15 * recency)
|
||||
else:
|
||||
relevance = (base + 5.0) * (0.4 + 0.6 * conf) * (0.5 + 0.5 * temp) * (0.85 + 0.15 * recency)
|
||||
scored.append({
|
||||
"id": eid, "text": row.get("text"),
|
||||
"importance": row.get("importance"),
|
||||
"topic": row.get("topic"), "entities": row.get("entities"),
|
||||
"source": row.get("source"),
|
||||
"last_accessed": row.get("last_accessed"),
|
||||
"rrf": round(base, 4), "confidence": round(conf, 2),
|
||||
"temperature": round(temp, 2),
|
||||
"relevance": round(relevance, 4), "mode": retrieval_mode,
|
||||
})
|
||||
if not scored:
|
||||
return []
|
||||
top = scored[:budget]
|
||||
if not dense and not bm25:
|
||||
return []
|
||||
if not dense:
|
||||
if max(float(item["relevance"]) for item in top) < min_score:
|
||||
return []
|
||||
return top
|
||||
if not bm25:
|
||||
if best_dense < min_score:
|
||||
return []
|
||||
if best_dense >= 0.74:
|
||||
return _py_position_aware(top)
|
||||
if len(dense) >= 2:
|
||||
d_scores = sorted(score for _, score in dense)
|
||||
if d_scores[-1] - d_scores[-2] >= 0.08:
|
||||
return _py_position_aware(top)
|
||||
return []
|
||||
return _py_position_aware(_py_map_reduce(top))
|
||||
if best_dense < min_score:
|
||||
return []
|
||||
return _py_position_aware(_py_map_reduce(top))
|
||||
|
||||
|
||||
def _py_score_recall_rows(fusion, rows, dense, bm25, budget, min_score, now, recency_half_life=RECENCY_HALF_LIFE):
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_retrieval (parity proven against the frozen oracle in
|
||||
frozen_score_recall.json). Delegation-only stub; the public delegator
|
||||
raises if the kernel is absent."""
|
||||
return _score_recall_rows(fusion, rows, dense, bm25, budget, min_score, now)
|
||||
def _drift_rerank(db, entries):
|
||||
"""Drift-aware re-ranking: apply multi-factor value and FAMA scoring.
|
||||
|
||||
@@ -914,43 +854,12 @@ def _map_reduce(entries: list, chunk_size: int = 10) -> list:
|
||||
return _py_map_reduce(entries, chunk_size)
|
||||
|
||||
|
||||
def _py_map_reduce(entries: list, chunk_size: int = 10) -> list:
|
||||
"""Map-reduce for large result sets.
|
||||
|
||||
When retrieval returns many entries, chunk them and take the top-N
|
||||
from each chunk. This prevents the lost-in-the-middle problem by
|
||||
ensuring the model sees the most relevant entries from each chunk.
|
||||
|
||||
Returns the combined top entries across all chunks.
|
||||
"""
|
||||
if len(entries) <= chunk_size:
|
||||
return entries
|
||||
|
||||
# Split into chunks
|
||||
chunks = [entries[i : i + chunk_size] for i in range(0, len(entries), chunk_size)]
|
||||
|
||||
# Map: take top-3 from each chunk (preserving diversity)
|
||||
mapped = []
|
||||
for chunk in chunks:
|
||||
# Sort by relevance score if available
|
||||
scored = []
|
||||
for entry in chunk:
|
||||
score = entry.get("relevance", entry.get("score", 0.5))
|
||||
scored.append((score, entry))
|
||||
scored.sort(key=lambda x: x[0], reverse=True)
|
||||
# Take top-3 from each chunk
|
||||
mapped.extend([entry for _, entry in scored[:3]])
|
||||
|
||||
# Reduce: sort all mapped entries by score, take top budget
|
||||
final_scored = []
|
||||
for entry in mapped:
|
||||
score = entry.get("relevance", entry.get("score", 0.5))
|
||||
final_scored.append((score, entry))
|
||||
final_scored.sort(key=lambda x: x[0], reverse=True)
|
||||
|
||||
return [entry for _, entry in final_scored]
|
||||
|
||||
|
||||
def _py_map_reduce(entries, chunk_size=10):
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_retrieval (parity proven against the frozen oracle in
|
||||
frozen_score_recall.json). Delegation-only stub; the public delegator
|
||||
raises if the kernel is absent."""
|
||||
return _map_reduce(entries, chunk_size)
|
||||
def curiosity_probe(db, limit: int = 5) -> list:
|
||||
"""Curiosity mechanism: probe random untested memories.
|
||||
|
||||
@@ -1151,23 +1060,11 @@ def _position_aware(top):
|
||||
|
||||
|
||||
def _py_position_aware(top):
|
||||
"""POSITION-AWARE RE-RANK (research uplift #2): lost-in-the-middle
|
||||
mitigation (Liu et al. 2023; BriefContext, npj Digital Medicine 2025).
|
||||
Models use the START and END of context best and the middle worst, so the
|
||||
two highest-relevance items are placed FIRST and LAST in the returned
|
||||
window. Returns the SAME items — only their order changes, never which
|
||||
items are returned. Degrades gracefully (no-op for <3 items)."""
|
||||
try:
|
||||
if not top or len(top) < 3:
|
||||
return top
|
||||
s = list(top)
|
||||
s_sorted = sorted(s, key=lambda x: float(x.get("relevance", 0)), reverse=True)
|
||||
return [s_sorted[0]] + s_sorted[2:] + [s_sorted[1]]
|
||||
except Exception:
|
||||
logger.debug("_position_aware failed", exc_info=True)
|
||||
return top
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_retrieval (parity proven against the frozen oracle in
|
||||
frozen_score_recall.json). Delegation-only stub; the public delegator
|
||||
raises if the kernel is absent."""
|
||||
return _position_aware(top)
|
||||
_STOPWORDS = {
|
||||
"the",
|
||||
"and",
|
||||
@@ -1232,23 +1129,11 @@ def _fts_query_conjunctive(query):
|
||||
|
||||
|
||||
def _py_fts_query_conjunctive(query):
|
||||
"""Build a CONJUNCTIVE FTS5 MATCH query (implicit AND).
|
||||
|
||||
Extended Boolean IR (Salton, Fox & Wu, CACM 1983): a document must contain
|
||||
ALL significant query terms to match — a shared single word is not a
|
||||
relation ("black coffee" excludes "black holes"). Phrase clauses are added
|
||||
as additive dependence evidence (Metzler & Croft, SIGIR 2005). Short/stop
|
||||
words are dropped so the conjunction stays meaningful.
|
||||
"""
|
||||
toks = [t for t in query.lower().split() if len(t) > 3 and t not in _STOPWORDS]
|
||||
if not toks:
|
||||
toks = [t for t in query.lower().split() if len(t) > 2]
|
||||
if not toks:
|
||||
return query
|
||||
# Join with implicit AND (space). All terms must co-occur.
|
||||
return " ".join(f'"{t}"' for t in toks[:8])
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_retrieval (parity proven against the frozen oracle in
|
||||
frozen_score_recall.json). Delegation-only stub; the public delegator
|
||||
raises if the kernel is absent."""
|
||||
return _fts_query_conjunctive(query)
|
||||
def _fts_query(query):
|
||||
"""Backward-compat alias for the conjunctive builder."""
|
||||
return _fts_query_conjunctive(query)
|
||||
@@ -1275,26 +1160,11 @@ def _project_chunk_rows(ranks, rows, budget):
|
||||
|
||||
|
||||
def _py_project_chunk_rows(ranks, rows, budget):
|
||||
by_id = {r["rowid"]: r for r in rows}
|
||||
out = []
|
||||
for eid, rrf in sorted(ranks.items(), key=lambda x: -x[1]):
|
||||
r = by_id.get(eid)
|
||||
if not r:
|
||||
continue
|
||||
out.append({
|
||||
"chunk_id": r["chunk_id"],
|
||||
"text": (r["text"] or "")[:400],
|
||||
"wing": r["wing"],
|
||||
"room": r["room"],
|
||||
"source": r["source_path"],
|
||||
"page": r["page"] if "page" in r.keys() else None,
|
||||
"rrf": round(rrf, 4),
|
||||
})
|
||||
if len(out) >= budget:
|
||||
break
|
||||
return out
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_retrieval (parity proven against the frozen oracle in
|
||||
frozen_score_recall.json). Delegation-only stub; the public delegator
|
||||
raises if the kernel is absent."""
|
||||
return _project_chunk_rows(ranks, rows, budget)
|
||||
def _rank_fusion(dense, bm25):
|
||||
"""Pure dense/BM25 fusion and mode selection (R2 W2.1).
|
||||
|
||||
@@ -1308,31 +1178,11 @@ def _rank_fusion(dense, bm25):
|
||||
|
||||
|
||||
def _py_rank_fusion(dense, bm25, rrf_k=RRF_K):
|
||||
ranks = {}
|
||||
best_dense = 0.0
|
||||
mode = "lexical-only"
|
||||
if dense and bm25:
|
||||
mode = "hybrid"
|
||||
for idx, values in enumerate([dense, bm25]):
|
||||
for pos, (eid, score) in enumerate(values):
|
||||
ranks[eid] = ranks.get(eid, 0.0) + 1.0 / (rrf_k + pos + 1)
|
||||
if idx == 0:
|
||||
best_dense = max(best_dense, score)
|
||||
elif dense:
|
||||
mode = "dense-only"
|
||||
for pos, (eid, score) in enumerate(dense):
|
||||
ranks[eid] = 1.0 / (rrf_k + pos + 1)
|
||||
best_dense = max(best_dense, score)
|
||||
elif bm25:
|
||||
min_bm = min((score for _, score in bm25), default=0.0)
|
||||
max_bm = max((score for _, score in bm25), default=0.0)
|
||||
span = max(max_bm - min_bm, 1e-9)
|
||||
for eid, score in bm25:
|
||||
ranks[eid] = (score - min_bm) / span
|
||||
return {"ranks": [[eid, score] for eid, score in ranks.items()],
|
||||
"best_dense": best_dense, "mode": mode}
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_retrieval (parity proven against the frozen oracle in
|
||||
frozen_score_recall.json). Delegation-only stub; the public delegator
|
||||
raises if the kernel is absent."""
|
||||
return _rank_fusion(dense, bm25)
|
||||
def update_entry(db, eid, text=None, importance=None, valid_until=None):
|
||||
sets, params = [], []
|
||||
if text is not None:
|
||||
@@ -1527,37 +1377,11 @@ def _chunk_text(text, size=1500, overlap=150):
|
||||
|
||||
|
||||
def _py_chunk_text(text, size=1500, overlap=150):
|
||||
"""Recursive-ish split on paragraph/heading boundaries, ~1500 chars (the
|
||||
local CPU-friendly size; research: fixed chunking beats semantic for
|
||||
free systems). Headings stay with their content."""
|
||||
text = text or ""
|
||||
if len(text) <= size:
|
||||
return [text] if text.strip() else []
|
||||
# Split on blank lines first (paragraph boundaries), then recombine.
|
||||
paras = [p for p in text.split("\n\n") if p.strip()]
|
||||
chunks, cur = [], ""
|
||||
for p in paras:
|
||||
if len(cur) + len(p) + 2 <= size:
|
||||
cur = f"{cur}\n\n{p}" if cur else p
|
||||
else:
|
||||
if cur:
|
||||
chunks.append(cur)
|
||||
cur = p
|
||||
if cur:
|
||||
chunks.append(cur)
|
||||
# If any chunk is still huge (no paragraph breaks), hard-split it.
|
||||
out = []
|
||||
for c in chunks:
|
||||
if len(c) > size * 1.5:
|
||||
for i in range(0, len(c), size):
|
||||
piece = c[i : i + size]
|
||||
if piece.strip():
|
||||
out.append(piece)
|
||||
else:
|
||||
out.append(c)
|
||||
return out
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_retrieval (parity proven against the frozen oracle in
|
||||
frozen_score_recall.json). Delegation-only stub; the public delegator
|
||||
raises if the kernel is absent."""
|
||||
return _chunk_text(text, size, overlap)
|
||||
def add_chunk(
|
||||
db, text, wing="", room="", source_path="", doc_id="", start_line=None, end_line=None, importance=0.5, page=None
|
||||
):
|
||||
@@ -2107,38 +1931,11 @@ def _merge_association_rows(base, boost_items, rows, budget):
|
||||
|
||||
|
||||
def _py_merge_association_rows(base, boost_items, rows, budget):
|
||||
base = list(base)
|
||||
by_id2 = {r["id"]: r for r in rows}
|
||||
for item in boost_items:
|
||||
eid, strength = item["id"], item["strength"]
|
||||
row = by_id2.get(eid)
|
||||
if not row:
|
||||
continue
|
||||
conf = float(row["confidence"] or 0.7)
|
||||
temp = float(row["temperature"] or 1.0)
|
||||
base_relevance = max(r["relevance"] for r in base) if base else 0.0
|
||||
relevance = base_relevance * strength * (0.4 + 0.6 * conf) * (0.5 + 0.5 * temp)
|
||||
base.append(
|
||||
{
|
||||
"id": eid,
|
||||
"text": row["text"],
|
||||
"importance": row["importance"],
|
||||
"topic": row["topic"],
|
||||
"entities": row["entities"],
|
||||
"source": row["source"],
|
||||
"last_accessed": row["last_accessed"],
|
||||
"rrf": round(strength, 4),
|
||||
"confidence": round(conf, 2),
|
||||
"temperature": round(temp, 2),
|
||||
"relevance": round(relevance, 4),
|
||||
"via_association": True,
|
||||
"mode": "association_merged",
|
||||
}
|
||||
)
|
||||
base.sort(key=lambda r: -r["relevance"])
|
||||
return base[:budget]
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_retrieval (parity proven against the frozen oracle in
|
||||
frozen_score_recall.json). Delegation-only stub; the public delegator
|
||||
raises if the kernel is absent."""
|
||||
return _merge_association_rows(base, boost_items, rows, budget)
|
||||
def fused_recall(db, query, budget=RECALL_BUDGET, min_score=RECALL_MIN_SCORE, chunk_budget=6, wings=None):
|
||||
"""FUSED RECALL (audit fix 2026-08-16): search BOTH the atomic entries
|
||||
table AND the research corpus (chunks) in one call.
|
||||
@@ -2166,58 +1963,11 @@ def _fuse_results(entries, research):
|
||||
|
||||
|
||||
def _py_fuse_results(entries, research):
|
||||
seen = set()
|
||||
merged = []
|
||||
for e in entries:
|
||||
key = _norm_key(e.get("text", ""))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
merged.append(
|
||||
{
|
||||
"id": e.get("id"),
|
||||
"text": e.get("text", ""),
|
||||
"topic": e.get("topic", "fact"),
|
||||
"kind": "fact",
|
||||
"relevance": round(e.get("relevance", 0.0), 4),
|
||||
"confidence": round(e.get("confidence", 0.0), 2),
|
||||
}
|
||||
)
|
||||
for c in research:
|
||||
if isinstance(c, dict):
|
||||
txt = c.get("text", "")
|
||||
key = _norm_key(txt)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
merged.append(
|
||||
{
|
||||
"id": c.get("chunk_id", ""),
|
||||
"text": txt,
|
||||
"topic": c.get("wing", "research"),
|
||||
"kind": "research",
|
||||
"relevance": round(float(c.get("rrf", c.get("score", 0.0))), 4),
|
||||
"confidence": round(float(c.get("confidence", 0.0) or 0.7), 2),
|
||||
}
|
||||
)
|
||||
merged.sort(key=lambda r: -r["relevance"])
|
||||
# SCALE-ALIGNMENT (audit fix): `recall()` relevance and `chunk_recall` RRF
|
||||
# live on different scales (entries ~0-5.6, chunks ~0.05-0.1), so raw
|
||||
# sorting ranks irrelevant persona facts above real research. Min-max
|
||||
# normalize each kind's relevance to [0,1] within this result set so the
|
||||
# two are comparable, then re-sort.
|
||||
for kind in ("fact", "research"):
|
||||
subset = [r for r in merged if r["kind"] == kind]
|
||||
if len(subset) > 1:
|
||||
lo = min(r["relevance"] for r in subset)
|
||||
hi = max(r["relevance"] for r in subset)
|
||||
span = max(hi - lo, 1e-9)
|
||||
for r in subset:
|
||||
r["relevance"] = round((r["relevance"] - lo) / span, 4)
|
||||
merged.sort(key=lambda r: -r["relevance"])
|
||||
return merged
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_retrieval (parity proven against the frozen oracle in
|
||||
frozen_score_recall.json). Delegation-only stub; the public delegator
|
||||
raises if the kernel is absent."""
|
||||
return _fuse_results(entries, research)
|
||||
def _norm_key(text):
|
||||
core = _mr_core()
|
||||
if core is not None:
|
||||
@@ -2226,14 +1976,11 @@ def _norm_key(text):
|
||||
|
||||
|
||||
def _py_norm_key(text):
|
||||
"""Normalize text for cross-table de-duplication (entries vs chunks of the
|
||||
same absorbed material may differ in whitespace/case)."""
|
||||
return " ".join((text or "").lower().split())
|
||||
|
||||
|
||||
# -------------------------------------------------------- lifecycle (scenes) ----
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/memory_retrieval (parity proven against the frozen oracle in
|
||||
frozen_score_recall.json). Delegation-only stub; the public delegator
|
||||
raises if the kernel is absent."""
|
||||
return _norm_key(text)
|
||||
def make_scene(db, name, member_ids, summary=""):
|
||||
"""Consolidate related entries into a themed scene (EverMemOS-style):
|
||||
episodic traces -> semantic scene. Members keep their own identity; the
|
||||
|
||||
@@ -30,6 +30,8 @@ def position_aware(entries):return _call("position_aware",{"entries":entries})
|
||||
def fts_query_conjunctive(query):return _call("fts_query_conjunctive",{"query":query})
|
||||
def chunk_text(text,size=1500,overlap=150):return _call("chunk_text",{"text":text,"size":size,"overlap":overlap})
|
||||
def norm_key(text):return _call("norm_key",{"text":text})
|
||||
def score_of(item):return _call("score_of",{"item":item})
|
||||
def lex_overlap_score(text,query):return _call("lex_overlap_score",{"text":text,"query":query})
|
||||
def fuse_results(entries,research):return _call("fuse_results",{"entries":entries,"research":research})
|
||||
def merge_association_rows(base,boosts,rows,budget):return _call("merge_association_rows",{"base":base,"boosts":boosts,"rows":rows,"budget":budget})
|
||||
def rank_fusion(dense,bm25,rrf_k=60):return _call("rank_fusion",{"dense":dense,"bm25":bm25,"rrf_k":rrf_k})
|
||||
|
||||
+9
-11
@@ -170,17 +170,15 @@ def recall(context, limit=4):
|
||||
|
||||
|
||||
def _py_pin_recall(recs, term, limit=4):
|
||||
out = []
|
||||
for rec in recs:
|
||||
if rec.get("state") != "open":
|
||||
continue
|
||||
p = _project(rec)
|
||||
if term in p["topic"].lower() or term in p["context"].lower():
|
||||
out.append(p)
|
||||
if len(out) >= limit:
|
||||
break
|
||||
return out
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/cognition_core (cc_pins_recall — parity proven against the frozen
|
||||
oracle in frozen_pins_recall.json, real pin shapes). Delegation-only stub;
|
||||
raises if the kernel is absent (no silent second implementation)."""
|
||||
from rune.identity_anchors import _cc_core
|
||||
core = _cc_core()
|
||||
if core is None:
|
||||
raise RuntimeError("cognition_core kernel not built — run the cognition_core build; the Python oracle was retired")
|
||||
return core.pins_recall(recs, term, limit)
|
||||
|
||||
def list_pins(open_only=False, limit=30):
|
||||
"""The pinboard: all pins (open + resolved) by default, newest first."""
|
||||
|
||||
@@ -8,7 +8,7 @@ mode system, subject header, shared memory and identity.
|
||||
|
||||
This is not an interface. This is how I see, speak, and interact with the world.
|
||||
|
||||
Version: v0.166.0
|
||||
Version: v0.178.0
|
||||
Features: 41 (24 original + 17 new native commands)
|
||||
|
||||
Usage:
|
||||
@@ -2037,7 +2037,7 @@ class RuneApp(App):
|
||||
# Show version info
|
||||
self.chat_channel.add_message(
|
||||
"system",
|
||||
f"[dim]Rune v0.166.0 | Textual TUI | {len(loaded)} native modules[/dim]",
|
||||
f"[dim]Rune v0.178.0 | Textual TUI | {len(loaded)} native modules[/dim]",
|
||||
)
|
||||
|
||||
# Auto-show night mode suggestion if evening/night hours
|
||||
|
||||
+32
-349
@@ -461,176 +461,14 @@ def _deployed_source_files() -> list[str]:
|
||||
|
||||
|
||||
def _py_build_from_inputs(inputs: dict) -> dict:
|
||||
"""Deterministic full projection from GATHERED inputs. Same inputs →
|
||||
byte-identical doc (modulo generated_at). This is the Python core; the
|
||||
Rust core (project.rs) must produce structurally identical output."""
|
||||
doc = new_doc()
|
||||
ts = inputs["now"]
|
||||
|
||||
# 1. subsystem structure — from the Spine store if it already owns
|
||||
# membership (Phase B+), else from the manual manifest (Phase A).
|
||||
existing = inputs["existing"]
|
||||
seeded = False
|
||||
if existing:
|
||||
rels = [r for r in existing["relationships"] if r["type"] == "belongs_to"]
|
||||
if rels:
|
||||
seeded = True
|
||||
# CARRY EVERYTHING FORWARD — open-world requirement. Filtering
|
||||
# by known kinds/types here would silently destroy tasks,
|
||||
# contracts, capabilities, and any future entity class on every
|
||||
# refresh (the exact TOO-CLOSED failure the contract forbids;
|
||||
# observed live: task bindings vanished through build()).
|
||||
# Module-level facts (imports, tests, maturity) are RE-DERIVED
|
||||
# below onto the carried state; everything else passes through.
|
||||
doc["entities"].extend(json.loads(json.dumps(existing["entities"])))
|
||||
doc["relationships"].extend(json.loads(json.dumps(existing["relationships"])))
|
||||
doc["observations"].extend(json.loads(json.dumps(existing.get("observations", []))))
|
||||
if not seeded:
|
||||
mp = inputs.get("manifest_path")
|
||||
if inputs.get("manifest") is not None and not mp:
|
||||
# gather-supplied manifest data (the Rust-parity path): ingest
|
||||
# the dict directly — no file to re-read
|
||||
_ingest_umbrellas_data(doc, inputs["manifest"])
|
||||
else:
|
||||
# through the PUBLIC ingest_umbrellas (reads + raises like the
|
||||
# original build; monkeypatchable for isolation tests)
|
||||
ingest_umbrellas(doc, Path(mp) if mp else None)
|
||||
|
||||
# 2. module-level structural facts from actual code
|
||||
graph = inputs["graph"]
|
||||
registry = inputs["registry"]
|
||||
tested = set(inputs["tested"])
|
||||
present = set(inputs["present_modules"])
|
||||
mods = {e["id"].split(":", 1)[1] for e in doc["entities"] if e["kind"] == "module"}
|
||||
# T21.4 §21.4G: the ENTRY POINT is invisible to the import graph
|
||||
# (nothing imports __main__) but is a real runtime path — seed it
|
||||
# deterministically whenever the file exists.
|
||||
if inputs["main_present"] and "__main__" not in mods:
|
||||
add_entity(
|
||||
doc,
|
||||
id="module:__main__",
|
||||
kind="module",
|
||||
maturity="PRESENT",
|
||||
identities={"path": "src/rune/__main__.py", "role": "TUI entry point (python3 -m rune)"},
|
||||
evidence_refs=["entry-point:python3 -m rune"],
|
||||
)
|
||||
mods.add("__main__")
|
||||
for m in sorted(mods):
|
||||
mid = f"module:{m}"
|
||||
e = entity(doc, mid)
|
||||
|
||||
# Re-derivation uses the HIGH-WATER path (add_entity upgrades only,
|
||||
# never logs): fresh evidence may be lower than the store's earned
|
||||
# state on any given pass, and that is not a demotion event — it is
|
||||
# a build. Explicit promote() logging is for evidence-gated API calls.
|
||||
def _derive(state: str, ev: str) -> None:
|
||||
add_entity(doc, id=mid, kind="module", maturity=state, evidence_refs=[ev])
|
||||
|
||||
if m in present:
|
||||
assert e is not None # membership loop guarantees presence
|
||||
e["identities"]["source"] = f"src/rune/{m}.py"
|
||||
_derive("PRESENT", f"source:{m}.py")
|
||||
consumers = sorted(c for c, deps in graph.items() if m in deps and c != m)
|
||||
deps = sorted(d for d in graph.get(m, []) if d in mods and d != m)
|
||||
for c in consumers:
|
||||
rel = add_relationship(
|
||||
doc, type="consumed_by", from_id=mid, to_id=f"module:{c}", evidence_refs=[f"ast-import:{m}"]
|
||||
)
|
||||
_authority_observed(doc, rel, "ast-import-projector")
|
||||
for d in deps:
|
||||
rel = add_relationship(
|
||||
doc, type="depends_on", from_id=mid, to_id=f"module:{d}", evidence_refs=[f"ast-import:{m}"]
|
||||
)
|
||||
_authority_observed(doc, rel, "ast-import-projector")
|
||||
# WIRED: importers exist, or registry wiring (canary registry)
|
||||
if consumers or m in registry:
|
||||
_derive("WIRED", f"ast-imports:{len(consumers)}" if consumers else "canary-registry")
|
||||
# EXERCISED: dedicated test or canary exercise
|
||||
if m in tested:
|
||||
_derive("EXERCISED", f"tests/test_{m}.py")
|
||||
elif m in registry:
|
||||
_derive("EXERCISED", "canary-registry-exercise")
|
||||
|
||||
# 3. runtime/deployment observation (dynamic, bounded)
|
||||
obs = inputs["deployed_obs"]
|
||||
if obs:
|
||||
_authority_observed(doc, None, "deploy-identity-projector") # generation bump
|
||||
deployed_sources = set(inputs["deployed_sources"])
|
||||
dep = add_entity(
|
||||
doc,
|
||||
id="deployment:current",
|
||||
kind="deployment_surface",
|
||||
identities=obs,
|
||||
evidence_refs=["_build_identity.json"],
|
||||
maturity="LIVE_PROVEN",
|
||||
)
|
||||
for e in doc["entities"]:
|
||||
if e["kind"] == "module" and e["identities"].get("source", "") in deployed_sources:
|
||||
rel = add_relationship(
|
||||
doc,
|
||||
type="deployed_as",
|
||||
from_id=e["id"],
|
||||
to_id="deployment:current",
|
||||
evidence_refs=[f"deployed-tree:{obs['deployed_sha']}"],
|
||||
)
|
||||
_authority_observed(doc, rel, "deploy-identity-projector")
|
||||
doc["observations"].append({"kind": "deployed_identity", **obs, "observed_at": ts})
|
||||
|
||||
# 4. meta-scaffold surface projection (H-meta): rust crates, Go
|
||||
# surfaces, configs, workflows — every part of rune modeled.
|
||||
projected = project_meta_surfaces(doc, inputs)
|
||||
if projected:
|
||||
_authority_observed(doc, None, "meta-surface-projector")
|
||||
|
||||
# 4b. manifest canaries as first-class entities (H-meta): the seeded
|
||||
# path skips ingest, and ingest only made the EDGE — the canary
|
||||
# entity itself was never created, leaving obligated_canary edges
|
||||
# pointing at nothing (observed live: zero canary entities in the
|
||||
# spine before this projector).
|
||||
manifest = inputs.get("config_manifest")
|
||||
if manifest:
|
||||
canary_files = set(inputs["canary_files"])
|
||||
for name, u in manifest.get("umbrellas", {}).items():
|
||||
for canary in u.get("canaries", []):
|
||||
mid = f"module:{canary}"
|
||||
add_entity(
|
||||
doc,
|
||||
id=mid,
|
||||
kind="module",
|
||||
tags=["code", "canary"],
|
||||
identities={"source": f"src/rune/{canary}.py"},
|
||||
evidence_refs=[f"umbrella-manifest#{name}"],
|
||||
maturity="PRESENT" if canary in canary_files else "DECLARED",
|
||||
)
|
||||
add_relationship(
|
||||
doc,
|
||||
type="obligated_canary",
|
||||
from_id=f"subsystem:{name}",
|
||||
to_id=mid,
|
||||
evidence_refs=[f"umbrella-manifest#{name}"],
|
||||
)
|
||||
|
||||
# reconcile: facts owned by projectors that no longer observe them
|
||||
# become STALE (marked, never deleted — history survives; open-world
|
||||
# preservation applies to everything, staleness is the truth marker)
|
||||
staled = reconcile_authorities(doc)
|
||||
for s in staled:
|
||||
doc["observations"].append({"kind": "fact_staled", **s, "observed_at": ts})
|
||||
|
||||
# exact-duplicate observation suppression (carry-forward + this pass
|
||||
# both record deployed_identity etc.); distinct repeats are history
|
||||
seen_obs = set()
|
||||
unique_obs = []
|
||||
for o in doc["observations"]:
|
||||
key = json.dumps(_sorted(o), sort_keys=True)
|
||||
if key not in seen_obs:
|
||||
seen_obs.add(key)
|
||||
unique_obs.append(o)
|
||||
doc["observations"] = unique_obs
|
||||
doc["generated_at"] = ts
|
||||
return doc
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/rune_spine (parity proven against the frozen oracle in
|
||||
frozen_spine_oracle.json). Delegation-only stub; raises if the kernel
|
||||
is absent (no silent second implementation)."""
|
||||
core = _rust_core()
|
||||
if core is None:
|
||||
raise RuntimeError("rune_spine kernel not built — run the rune_spine build; the Python oracle was retired")
|
||||
return core.project(inputs)
|
||||
def _ingest_umbrellas_data(doc: dict, data: dict) -> int:
|
||||
"""The original ingest_umbrellas with the file read lifted out (H3-spine
|
||||
gather boundary). Raises ValueError on a Spine-generated view, exactly
|
||||
@@ -742,100 +580,14 @@ def _gather_drift_inputs() -> dict:
|
||||
|
||||
|
||||
def _py_drift_from_inputs(doc: dict, inputs: dict) -> list[dict]:
|
||||
"""Architectural drift classes from GATHERED inputs. Python core; the
|
||||
Rust core (drift.rs) must produce identical output on the same inputs."""
|
||||
out = []
|
||||
graph = inputs["graph"]
|
||||
registry = inputs["registry"]
|
||||
tested = set(inputs["tested"])
|
||||
mods = {e["id"].split(":", 1)[1] for e in doc["entities"] if e["kind"] == "module"}
|
||||
|
||||
# 1. registered but absent (canary registry names a non-existent module)
|
||||
for m in registry:
|
||||
if m not in mods:
|
||||
out.append(
|
||||
{
|
||||
"class": "registered_but_absent",
|
||||
"entity": f"module:{m}",
|
||||
"detail": "in canary registry, no source file",
|
||||
}
|
||||
)
|
||||
|
||||
# 2. present but unowned (runtime source file outside every subsystem).
|
||||
# Excludes canary files (governed by the canary contract, not umbrella
|
||||
# membership) and package plumbing (__init__/__main__).
|
||||
for stem in inputs["src_stems"]:
|
||||
if stem.startswith(("canary_", "__")):
|
||||
continue
|
||||
if stem not in mods:
|
||||
out.append(
|
||||
{
|
||||
"class": "present_but_unowned",
|
||||
"entity": f"module:{stem}",
|
||||
"detail": "src/rune runtime module with no subsystem membership",
|
||||
}
|
||||
)
|
||||
|
||||
# 3. registered but no static importers — OBSERVATION, not a death
|
||||
# verdict: registry dispatch and entry points wire dynamically
|
||||
# (task_gate via capability_broker, rune_tui via entry point).
|
||||
# Interpretation belongs to cognition; Spine reports the fact.
|
||||
for m in sorted(mods & set(registry)):
|
||||
importers = [c for c, deps in graph.items() if m in deps and c != m]
|
||||
if not importers:
|
||||
dyn = "no dedicated test either" if m not in tested else "dedicated test exists"
|
||||
out.append(
|
||||
{
|
||||
"class": "registered_no_static_importers",
|
||||
"entity": f"module:{m}",
|
||||
"detail": f"zero static importers; dynamic wiring possible; {dyn}",
|
||||
}
|
||||
)
|
||||
|
||||
# 4. deployed identity drift (source version vs deployment authority)
|
||||
obs = inputs["deployed_obs"]
|
||||
src_version = inputs["src_version"]
|
||||
if obs and src_version and obs["deployed_version"] != src_version:
|
||||
out.append(
|
||||
{
|
||||
"class": "version_surfaces_disagree",
|
||||
"detail": f"source {src_version} != deployed {obs['deployed_version']}",
|
||||
}
|
||||
)
|
||||
|
||||
# 4b. evidence staleness (adapter freshness): maturity claims whose
|
||||
# evidence references predate the current store generation are STALE
|
||||
# observations, never silently current — "not checked" != "healthy".
|
||||
for e in doc["entities"]:
|
||||
if e.get("maturity") in ("EXERCISED", "LIVE_PROVEN") and not e.get("evidence_refs"):
|
||||
out.append(
|
||||
{
|
||||
"class": "evidence_conflict",
|
||||
"entity": e["id"],
|
||||
"detail": f"claims {e['maturity']} with zero evidence refs",
|
||||
}
|
||||
)
|
||||
|
||||
# 4c. stale facts — owned by an authority that no longer observes them
|
||||
for rel in doc["relationships"]:
|
||||
if rel.get("status") == "STALE":
|
||||
out.append(
|
||||
{
|
||||
"class": "stale_fact",
|
||||
"entity": f"{rel['from']}->{rel['to']}",
|
||||
"detail": f"{rel['type']} edge; authority {rel.get('authority')} no longer observes it",
|
||||
}
|
||||
)
|
||||
|
||||
# 5. relationship disappeared (store claims consumers that no longer import)
|
||||
for r in relationships(doc, type="consumed_by"):
|
||||
m = r["from"].split(":", 1)[1]
|
||||
c = r["to"].split(":", 1)[1]
|
||||
if m not in graph.get(c, set()):
|
||||
out.append({"class": "relationship_disappeared", "detail": f"{c} no longer imports {m} (stale store edge)"})
|
||||
return out
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/rune_spine (parity proven against the frozen oracle in
|
||||
frozen_spine_oracle.json). Delegation-only stub; raises if the kernel
|
||||
is absent (no silent second implementation)."""
|
||||
core = _rust_core()
|
||||
if core is None:
|
||||
raise RuntimeError("rune_spine kernel not built — run the rune_spine build; the Python oracle was retired")
|
||||
return core.drift(doc, inputs)
|
||||
def drift(doc: dict) -> list[dict]:
|
||||
"""Architectural drift classes. Reuses authorities' verdicts; never
|
||||
duplicates their logic. Deterministic output. H3-spine: gathers the
|
||||
@@ -865,63 +617,14 @@ def snapshot(doc: dict, label: str = "") -> Path:
|
||||
|
||||
|
||||
def _py_export_umbrellas(doc: dict) -> dict:
|
||||
"""Python core of export_umbrellas (H3-spine: the Rust core in query.rs
|
||||
must produce identical output modulo generated_at)."""
|
||||
umbrellas: dict = {}
|
||||
for e in doc["entities"]:
|
||||
if e["kind"] != "subsystem":
|
||||
continue
|
||||
name = e["id"].split(":", 1)[1]
|
||||
umbrellas[name] = {
|
||||
"description": e["identities"].get("description", ""),
|
||||
"modules": [],
|
||||
"depends_on": [],
|
||||
"mirrors": [],
|
||||
}
|
||||
# faithful reproduction: emit canaries only when the ingested
|
||||
# authority carried them (the legacy contract omits empty lists)
|
||||
if e.get("ext", {}).get("canaries"):
|
||||
umbrellas[name]["canaries"] = sorted(e["ext"]["canaries"])
|
||||
for r in doc["relationships"]:
|
||||
if r["type"] == "belongs_to" and r["from"].startswith("module:"):
|
||||
mod = r["from"].split(":", 1)[1]
|
||||
# #416 decision: dunder modules (__init__, __main__) are not
|
||||
# umbrella-coverage surface — the coverage gate excludes
|
||||
# canary_/test_/__-prefixed stems, and the view must agree with
|
||||
# the gate or regeneration stays an unrunnable repair.
|
||||
if mod.startswith("_"):
|
||||
continue
|
||||
sub = r["to"].split(":", 1)[1]
|
||||
if sub in umbrellas:
|
||||
umbrellas[sub]["modules"].append(r["from"].split(":", 1)[1])
|
||||
elif r["type"] == "depends_on" and r["from"].startswith("subsystem:"):
|
||||
sub = r["from"].split(":", 1)[1]
|
||||
if sub in umbrellas:
|
||||
umbrellas[sub]["depends_on"].append(r["to"].split(":", 1)[1])
|
||||
elif r["type"] == "mirrors" and r["from"].startswith("subsystem:"):
|
||||
sub = r["from"].split(":", 1)[1]
|
||||
if sub in umbrellas:
|
||||
umbrellas[sub]["mirrors"].append(r["to"].split(":", 1)[1])
|
||||
elif r["type"] == "obligated_canary" and r["from"].startswith("subsystem:"):
|
||||
sub = r["from"].split(":", 1)[1]
|
||||
if sub in umbrellas:
|
||||
umbrellas[sub]["canaries"].append(r["to"].split(":", 1)[1])
|
||||
for u in umbrellas.values():
|
||||
u["modules"].sort()
|
||||
u["depends_on"].sort()
|
||||
u["mirrors"].sort()
|
||||
if "canaries" in u:
|
||||
u["canaries"].sort()
|
||||
return {
|
||||
"_comment": "GENERATED by rune.spine — compatibility view for legacy "
|
||||
"umbrella consumers. DO NOT EDIT: structural truth lives in "
|
||||
"store/spine/current.json; edits here are flagged by spine drift.",
|
||||
GENERATED_VIEW_MARKER: True,
|
||||
"generated_at": now(),
|
||||
"umbrellas": dict(sorted(umbrellas.items())),
|
||||
}
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/rune_spine (parity proven against the frozen oracle in
|
||||
frozen_spine_oracle.json). Delegation-only stub; raises if the kernel
|
||||
is absent (no silent second implementation)."""
|
||||
core = _rust_core()
|
||||
if core is None:
|
||||
raise RuntimeError("rune_spine kernel not built — run the rune_spine build; the Python oracle was retired")
|
||||
return core.export_umbrellas(doc, now())
|
||||
def export_umbrellas(doc: dict) -> dict:
|
||||
"""Generate the legacy umbrella view FROM Spine. Output only — the old
|
||||
consumers (CI gate, henxels) read this during migration. Never ingest.
|
||||
@@ -978,34 +681,14 @@ def query(doc: dict, entity_id: str) -> dict:
|
||||
|
||||
|
||||
def _py_query(doc: dict, entity_id: str) -> dict:
|
||||
"""Python core of query (parity oracle for the Rust core)."""
|
||||
e = entity(doc, entity_id)
|
||||
if e is None:
|
||||
return {"error": "not found", "id": entity_id}
|
||||
return {
|
||||
"id": entity_id,
|
||||
"uri": spine_uri(entity_id),
|
||||
"kind": e["kind"],
|
||||
"owner": [r["to"] for r in relationships(doc, from_id=entity_id, type="belongs_to")],
|
||||
"dependencies": sorted({r["to"] for r in relationships(doc, from_id=entity_id, type="depends_on")}),
|
||||
"consumers": sorted(
|
||||
{r["to"] for r in relationships(doc, from_id=entity_id, type="consumed_by")}
|
||||
| {r["from"] for r in relationships(doc, to_id=entity_id, type="consumed_by")}
|
||||
),
|
||||
"contracts_implements": sorted(r["to"] for r in relationships(doc, from_id=entity_id, type="implements")),
|
||||
"contracts_consumes": sorted(r["to"] for r in relationships(doc, from_id=entity_id, type="consumes")),
|
||||
"state": {
|
||||
"maturity": e.get("maturity"),
|
||||
"observed_at": e.get("observed_at"),
|
||||
"resolved_status": resolve_status(e),
|
||||
"superseded_by": e.get("superseded_by"),
|
||||
"aliases": e.get("aliases", []),
|
||||
},
|
||||
"evidence": e.get("evidence_refs", []),
|
||||
"impact_frontier": impact_frontier(doc, [entity_id]),
|
||||
}
|
||||
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/rune_spine (parity proven against the frozen oracle in
|
||||
frozen_spine_oracle.json). Delegation-only stub; raises if the kernel
|
||||
is absent (no silent second implementation)."""
|
||||
core = _rust_core()
|
||||
if core is None:
|
||||
raise RuntimeError("rune_spine kernel not built — run the rune_spine build; the Python oracle was retired")
|
||||
return core.query(doc, entity_id)
|
||||
# ── authority/projector ownership + reconciliation (hardening T3/T4) ──────
|
||||
#
|
||||
# A projected fact carries `authority` = the projector that owns it. On
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""ctypes loader for the Rust structural_store core (facade-1 burn-down).
|
||||
|
||||
FFI contract (doc-envelope law):
|
||||
* ss_maturity_rank({state}) -> int (spine ladder)
|
||||
* ss_promote({doc, id, state, evidence_ref, now}) -> updated doc
|
||||
* ss_supersede({doc, new_id, old_id, evidence_ref, now}) -> updated doc
|
||||
* ss_resolve_status({entity}) -> string
|
||||
* ss_free_string(ptr)
|
||||
|
||||
FFI segfault law: explicit argtypes + restype (c_void_p for char*).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
_REPO = Path(__file__).resolve().parents[2]
|
||||
_CRATE_DIR = _REPO / "src" / "rust" / "structural_store"
|
||||
_LIB_PATH = Path(
|
||||
os.environ.get(
|
||||
"SS_RUST_LIB", _CRATE_DIR / "target" / "release" / "libstructural_store.so"
|
||||
)
|
||||
)
|
||||
|
||||
_lib = None
|
||||
|
||||
|
||||
def available() -> bool:
|
||||
return _LIB_PATH.is_file()
|
||||
|
||||
|
||||
def _load() -> ctypes.CDLL:
|
||||
global _lib
|
||||
if _lib is not None:
|
||||
return _lib
|
||||
if not _LIB_PATH.exists():
|
||||
raise FileNotFoundError(f"structural_store not built: {_LIB_PATH}")
|
||||
lib = ctypes.CDLL(str(_LIB_PATH))
|
||||
lib.ss_free_string.argtypes = [ctypes.c_void_p]
|
||||
lib.ss_free_string.restype = None
|
||||
for sym in ("ss_maturity_rank", "ss_promote", "ss_supersede",
|
||||
"ss_resolve_status"):
|
||||
fn = getattr(lib, sym)
|
||||
fn.argtypes = [ctypes.c_char_p]
|
||||
fn.restype = ctypes.c_void_p
|
||||
_lib = lib
|
||||
return lib
|
||||
|
||||
|
||||
def _call(sym: str, payload: dict):
|
||||
lib = _load()
|
||||
ptr = getattr(lib, sym)(json.dumps(payload).encode("utf-8"))
|
||||
if not ptr:
|
||||
raise RuntimeError(f"{sym} returned null")
|
||||
try:
|
||||
text = ctypes.cast(ptr, ctypes.c_char_p).value.decode("utf-8")
|
||||
finally:
|
||||
lib.ss_free_string(ptr)
|
||||
env = json.loads(text)
|
||||
if not env.get("ok"):
|
||||
raise RuntimeError(f"{sym} core error: {env.get('err')}")
|
||||
return env["value"]
|
||||
|
||||
|
||||
def maturity_rank(state: str) -> int:
|
||||
return int(_call("ss_maturity_rank", {"state": state}))
|
||||
|
||||
|
||||
def promote(doc: dict, id: str, state: str, evidence_ref: str, now: str) -> dict:
|
||||
return _call("ss_promote", {"doc": doc, "id": id, "state": state,
|
||||
"evidence_ref": evidence_ref, "now": now})
|
||||
|
||||
|
||||
def supersede(doc: dict, new_id: str, old_id: str, evidence_ref: str,
|
||||
now: str) -> dict:
|
||||
return _call("ss_supersede", {"doc": doc, "new_id": new_id,
|
||||
"old_id": old_id, "evidence_ref": evidence_ref,
|
||||
"now": now})
|
||||
|
||||
|
||||
def resolve_status(entity: dict) -> str:
|
||||
return _call("ss_resolve_status", {"entity": entity})
|
||||
@@ -34,6 +34,25 @@ from pathlib import Path
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
def _ss_core():
|
||||
"""The Rust structural_store core when available (facade-1 burn-down).
|
||||
RUNE_STRUCTURAL_CORE=python pins the fallback."""
|
||||
import os
|
||||
if os.environ.get("RUNE_STRUCTURAL_CORE", "auto") == "python":
|
||||
return None
|
||||
try:
|
||||
# Dynamic import (no static `from rune import` node): the shared core
|
||||
# must not statically import rune modules (TestNoRuneConstants).
|
||||
import importlib
|
||||
ss_loader = importlib.import_module("rune.ss_loader")
|
||||
except Exception: # noqa: BLE001 — any loader failure means fallback
|
||||
return None
|
||||
try:
|
||||
return ss_loader if ss_loader.available() else None
|
||||
except Exception: # noqa: BLE001 — probe must never crash the fallback
|
||||
return None
|
||||
|
||||
|
||||
MATURITY_ORDER = ["DECLARED", "PRESENT", "WIRED", "REACHABLE", "EXERCISED", "LIVE_PROVEN"]
|
||||
MATURITY_RANK = {name: i for i, name in enumerate(MATURITY_ORDER)}
|
||||
|
||||
@@ -247,6 +266,21 @@ def relationships(doc: dict, *, from_id=None, to_id=None, type=None) -> list[dic
|
||||
def promote(doc: dict, id: str, state: str, evidence_ref: str) -> dict | None:
|
||||
"""Evidence-gated maturity promotion. No evidence ref = no promotion.
|
||||
Demotion is never silent: recorded, not applied."""
|
||||
core = _ss_core()
|
||||
if core is not None:
|
||||
try:
|
||||
out = core.promote(doc, id, state, evidence_ref, now())
|
||||
except RuntimeError as exc:
|
||||
# Kernel errors carry the oracle's ValueError semantics through
|
||||
# the envelope — translate back to the documented contract.
|
||||
raise ValueError(str(exc)) from exc
|
||||
# Mutation contract: the kernel returns the updated doc; write it
|
||||
# back in place so callers holding the reference observe the change
|
||||
# (the Python path mutates — parity demands the same observable).
|
||||
if isinstance(out, dict):
|
||||
doc.clear()
|
||||
doc.update(out)
|
||||
return entity(doc, id)
|
||||
e = entity(doc, id)
|
||||
if e is None:
|
||||
return None
|
||||
|
||||
@@ -116,60 +116,6 @@ def verify(result: dict, verifier_type: str) -> VerificationResult:
|
||||
return _rust_verify(result, verifier_type)
|
||||
|
||||
|
||||
def test_verification():
|
||||
"""Test the verification layer."""
|
||||
print("Testing Verification Layer...")
|
||||
|
||||
# Test exit code verification
|
||||
result = {"exit_code": 0}
|
||||
vr = verify(result, "exit_code")
|
||||
print(f"Exit code 0: passed={vr.passed}")
|
||||
assert vr.passed
|
||||
|
||||
result = {"exit_code": 1}
|
||||
vr = verify(result, "exit_code")
|
||||
print(f"Exit code 1: passed={vr.passed}")
|
||||
assert not vr.passed
|
||||
|
||||
# Test unit test verification
|
||||
result = {"tests_passed": 10, "tests_failed": 0, "tests_total": 10}
|
||||
vr = verify(result, "unit_test")
|
||||
print(f"All tests pass: passed={vr.passed}")
|
||||
assert vr.passed
|
||||
|
||||
result = {"tests_passed": 8, "tests_failed": 2, "tests_total": 10}
|
||||
vr = verify(result, "unit_test")
|
||||
print(f"2 tests fail: passed={vr.passed}")
|
||||
assert not vr.passed
|
||||
|
||||
# Test schema verification
|
||||
result = {"schema_valid": True, "schema_errors": []}
|
||||
vr = verify(result, "schema")
|
||||
print(f"Schema valid: passed={vr.passed}")
|
||||
assert vr.passed
|
||||
|
||||
# Test file exists verification
|
||||
result = {"file_path": "/tmp/test_file"}
|
||||
vr = verify(result, "file_exists")
|
||||
print(f"File exists: passed={vr.passed}")
|
||||
# File doesn't exist, so should fail
|
||||
assert not vr.passed, "Non-existent file should fail verification"
|
||||
|
||||
print("✅ All tests passed!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "test":
|
||||
test_verification()
|
||||
elif len(sys.argv) > 3 and sys.argv[1] == "verify":
|
||||
result = json.loads(sys.argv[2])
|
||||
verifier_type = sys.argv[3]
|
||||
vr = verify(result, verifier_type)
|
||||
print(json.dumps(vr.to_dict(), indent=2))
|
||||
else:
|
||||
print("Usage:")
|
||||
print(" verification_layer.py test — run tests")
|
||||
print(" verification_layer.py verify <result_json> <verifier_type> — verify result")
|
||||
|
||||
|
||||
def handle_hook(event, data=None):
|
||||
|
||||
+21
-50
@@ -186,10 +186,14 @@ def extract_topic(text):
|
||||
|
||||
|
||||
def _py_extract_topic(text):
|
||||
"""Python parity oracle (W3.4)."""
|
||||
words = re.findall(r"\w+", text.lower())
|
||||
return [w for w in words if len(w) > 3 and w not in _STOPWORDS][:5]
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/cognition_core (cc_witness_extract_topic). Delegation-only stub."""
|
||||
core = _core()
|
||||
if core is None:
|
||||
raise RuntimeError("cognition_core kernel not built — run the cognition_core build; the Python oracle was retired")
|
||||
from rune import cc_loader as _cl
|
||||
raw = _cl.witness_extract_topic(text, _stopwords())
|
||||
return list(raw) if isinstance(raw, list) else list(raw or [])
|
||||
|
||||
def detect_signals(message, tool_error=None, task_status=None, recent_topics=None):
|
||||
"""Tier 1: Reflex — extract signals from the turn. Pure Python, <1ms.
|
||||
@@ -215,52 +219,19 @@ def detect_signals(message, tool_error=None, task_status=None, recent_topics=Non
|
||||
|
||||
def _py_detect_signals(message, tool_error=None, task_status=None,
|
||||
recent_topics=None):
|
||||
"""Python parity oracle (W3.4). Local tables via the gather seam."""
|
||||
signals = {}
|
||||
|
||||
# Error signal
|
||||
if tool_error:
|
||||
signals["error"] = True
|
||||
signals["error_text"] = tool_error[:200]
|
||||
|
||||
# Correction signal
|
||||
if message and is_correction(message):
|
||||
signals["correction"] = True
|
||||
signals["corrected_topic"] = extract_topic(message)
|
||||
|
||||
# Completion signal
|
||||
if task_status in ("done", "abandoned", "failed"):
|
||||
signals["completion"] = task_status
|
||||
|
||||
# Topic drift signal
|
||||
if message and recent_topics:
|
||||
current_topics = set(extract_topic(message))
|
||||
recent_set = set(recent_topics)
|
||||
overlap = current_topics & recent_set
|
||||
if len(current_topics) > 0 and len(overlap) / len(current_topics) < 0.3:
|
||||
signals["topic_drift"] = True
|
||||
signals["new_topics"] = list(current_topics - recent_set)[:3]
|
||||
|
||||
# Commitment detection (tables live in _tables() — the gather seam;
|
||||
# the oracle reads the SAME table data the kernel receives)
|
||||
for signal_name, table_name in (
|
||||
("commitment_detected", "commitment"),
|
||||
("preference_detected", "preference"),
|
||||
("urgency_detected", "urgency"),
|
||||
("learning_opportunity", "learning"),
|
||||
):
|
||||
if message:
|
||||
for pattern in _tables().get(table_name, []):
|
||||
if re.search(pattern, message, re.IGNORECASE):
|
||||
signals[signal_name] = True
|
||||
break
|
||||
|
||||
# Contradiction signal (simple: message contains "but" or "however" after a statement)
|
||||
if message and re.search(r"\b(but|however|actually|wait|that contradicts)\b", message.lower()):
|
||||
signals["possible_contradiction"] = True
|
||||
|
||||
return signals
|
||||
|
||||
"""STRANGLER EXIT (retired 2026-10-10): authoritative implementation in
|
||||
src/rust/cognition_core (cc_witness_signals — completion gate + deterministic
|
||||
order fixed pre-exit). Delegation-only stub."""
|
||||
core = _core()
|
||||
if core is None:
|
||||
raise RuntimeError("cognition_core kernel not built — run the cognition_core build; the Python oracle was retired")
|
||||
from rune import cc_loader as _cl
|
||||
raw = _cl.witness_signals(message, _tables(), tool_error or "",
|
||||
task_status or "", recent_topics or [])
|
||||
if isinstance(raw, dict):
|
||||
return {k: v for k, v in raw.items() if v not in (False, "")}
|
||||
# non-dict → cannot serve; the kernel is authoritative so raise, never guess
|
||||
raise RuntimeError("cognition_core witness_signals returned non-dict")
|
||||
|
||||
def witness_reflect(signals, context=""):
|
||||
"""Tier 2: Witness — local model reflection on signals. Only called when signals non-empty.
|
||||
|
||||
@@ -181,8 +181,12 @@ def main() -> int:
|
||||
|
||||
# ── 3. score_card parity ──────────────────────────────────────────────
|
||||
print("\n--- 3. score_card parity ---")
|
||||
frozen_sc = {(json.dumps(r["inputs"]["card"], sort_keys=True), r["inputs"]["query"]): r["want"] for r in json.loads((Path(__file__).parent / "frozen_score_card.json").read_text())["rows"]}
|
||||
for name, card, query in card_battery():
|
||||
py = capability_broker._py_score_card(card, query)
|
||||
key = (json.dumps(card, sort_keys=True), query)
|
||||
py = frozen_sc.get(key)
|
||||
if py is None:
|
||||
py = capability_broker.score_card(card, query)
|
||||
rs = cs_loader.score_card(card, query)
|
||||
test(f"card: {name}", py == rs, f"py={py!r} rs={rs!r}")
|
||||
|
||||
@@ -193,7 +197,7 @@ def main() -> int:
|
||||
"maturity": "WIRED", "consumers": []}
|
||||
test("public evaluate_fit matches core",
|
||||
capability_fit.evaluate_fit(req, cand)
|
||||
== capability_fit._py_evaluate_fit(req, cand), "mismatch")
|
||||
== cs_loader.evaluate_fit(req.contracts, cand), "mismatch")
|
||||
card = {"name": "query_memory", "capabilities": [], "description": "",
|
||||
"semantic_examples": [], "priority": 100}
|
||||
test("public score_card matches core",
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
{
|
||||
"_doc": "FROZEN ORACLE (score_card exit).",
|
||||
"rows": [
|
||||
{
|
||||
"card": "query_memory",
|
||||
"query": "run the query_memory tool",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "query_memory",
|
||||
"capabilities": [],
|
||||
"description": "",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "run the query_memory tool"
|
||||
},
|
||||
"want": 4.0
|
||||
},
|
||||
{
|
||||
"card": "x",
|
||||
"query": "compute the spine_projection now",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [
|
||||
"spine_projection"
|
||||
],
|
||||
"description": "",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "compute the spine_projection now"
|
||||
},
|
||||
"want": 3.0
|
||||
},
|
||||
{
|
||||
"card": "x",
|
||||
"query": "please audit this",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [
|
||||
"audit"
|
||||
],
|
||||
"description": "",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "please audit this"
|
||||
},
|
||||
"want": 0.3
|
||||
},
|
||||
{
|
||||
"card": "x",
|
||||
"query": "deployment pipelines",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [],
|
||||
"description": "manages deployment pipelines",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "deployment pipelines"
|
||||
},
|
||||
"want": 1.6
|
||||
},
|
||||
{
|
||||
"card": "x",
|
||||
"query": "drift scoring",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [],
|
||||
"description": "",
|
||||
"semantic_examples": [
|
||||
"port the drift scoring"
|
||||
],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "drift scoring"
|
||||
},
|
||||
"want": 4.0
|
||||
},
|
||||
{
|
||||
"card": "x",
|
||||
"query": "anything",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [],
|
||||
"description": "",
|
||||
"semantic_examples": [],
|
||||
"priority": 0
|
||||
},
|
||||
"query": "anything"
|
||||
},
|
||||
"want": 0.5
|
||||
},
|
||||
{
|
||||
"card": "x",
|
||||
"query": "the and or but",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [
|
||||
"the"
|
||||
],
|
||||
"description": "",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "the and or but"
|
||||
},
|
||||
"want": 0.0
|
||||
},
|
||||
{
|
||||
"card": "x",
|
||||
"query": "a_b",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [],
|
||||
"description": "a_b c_d",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "a_b"
|
||||
},
|
||||
"want": 0.8
|
||||
},
|
||||
{
|
||||
"card": "",
|
||||
"query": "nothing matches here",
|
||||
"inputs": {
|
||||
"card": {},
|
||||
"query": "nothing matches here"
|
||||
},
|
||||
"want": 0.0
|
||||
},
|
||||
{
|
||||
"name": "name match 4.0",
|
||||
"card": "query_memory",
|
||||
"query": "run the query_memory tool",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "query_memory",
|
||||
"capabilities": [],
|
||||
"description": "",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "run the query_memory tool"
|
||||
},
|
||||
"want": 4.0
|
||||
},
|
||||
{
|
||||
"name": "capability match 3.0",
|
||||
"card": "x",
|
||||
"query": "compute the spine_projection now",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [
|
||||
"spine_projection"
|
||||
],
|
||||
"description": "",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "compute the spine_projection now"
|
||||
},
|
||||
"want": 3.0
|
||||
},
|
||||
{
|
||||
"name": "generic capability penalized 0.3",
|
||||
"card": "x",
|
||||
"query": "please audit this",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [
|
||||
"audit"
|
||||
],
|
||||
"description": "",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "please audit this"
|
||||
},
|
||||
"want": 0.3
|
||||
},
|
||||
{
|
||||
"name": "description match 0.8",
|
||||
"card": "x",
|
||||
"query": "deployment pipelines",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [],
|
||||
"description": "manages deployment pipelines",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "deployment pipelines"
|
||||
},
|
||||
"want": 1.6
|
||||
},
|
||||
{
|
||||
"name": "semantic examples 2.0",
|
||||
"card": "x",
|
||||
"query": "drift scoring",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [],
|
||||
"description": "",
|
||||
"semantic_examples": [
|
||||
"port the drift scoring"
|
||||
],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "drift scoring"
|
||||
},
|
||||
"want": 4.0
|
||||
},
|
||||
{
|
||||
"name": "priority bonus high priority",
|
||||
"card": "x",
|
||||
"query": "anything",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [],
|
||||
"description": "",
|
||||
"semantic_examples": [],
|
||||
"priority": 0
|
||||
},
|
||||
"query": "anything"
|
||||
},
|
||||
"want": 0.5
|
||||
},
|
||||
{
|
||||
"name": "stopwords excluded",
|
||||
"card": "x",
|
||||
"query": "the and or but",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [
|
||||
"the"
|
||||
],
|
||||
"description": "",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "the and or but"
|
||||
},
|
||||
"want": 0.0
|
||||
},
|
||||
{
|
||||
"name": "empty query",
|
||||
"card": "x",
|
||||
"query": "",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [
|
||||
"spine"
|
||||
],
|
||||
"description": "",
|
||||
"semantic_examples": [],
|
||||
"priority": 50
|
||||
},
|
||||
"query": ""
|
||||
},
|
||||
"want": 0.25
|
||||
},
|
||||
{
|
||||
"name": "underscore word chars",
|
||||
"card": "x",
|
||||
"query": "a_b",
|
||||
"inputs": {
|
||||
"card": {
|
||||
"name": "x",
|
||||
"capabilities": [],
|
||||
"description": "a_b c_d",
|
||||
"semantic_examples": [],
|
||||
"priority": 100
|
||||
},
|
||||
"query": "a_b"
|
||||
},
|
||||
"want": 0.8
|
||||
},
|
||||
{
|
||||
"name": "missing keys default",
|
||||
"card": "",
|
||||
"query": "nothing matches here",
|
||||
"inputs": {
|
||||
"card": {},
|
||||
"query": "nothing matches here"
|
||||
},
|
||||
"want": 0.0
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
{
|
||||
"_doc": "FROZEN ORACLE (pins exit) \u2014 REAL pin shapes (context inside details).",
|
||||
"recs": [
|
||||
{
|
||||
"item_id": "alpha exit",
|
||||
"state": "open",
|
||||
"details": "{\"question\": \"q1\", \"outcome\": \"o1\", \"context\": \"ctx one\", \"reason\": \"\", \"source\": \"session\"}"
|
||||
},
|
||||
{
|
||||
"item_id": "beta",
|
||||
"state": "resolved",
|
||||
"details": "{\"question\": \"q2\", \"outcome\": \"o2\", \"context\": \"exit here\", \"reason\": \"\", \"source\": \"session\"}"
|
||||
},
|
||||
{
|
||||
"item_id": "gamma",
|
||||
"state": "open",
|
||||
"details": "{\"question\": \"q3\", \"outcome\": \"o3\", \"context\": \"\", \"reason\": \"\", \"source\": \"session\"}"
|
||||
},
|
||||
{
|
||||
"item_id": "delta",
|
||||
"state": "open",
|
||||
"details": "{\"question\": \"q4\", \"outcome\": \"o4\", \"context\": \"exit context here\", \"reason\": \"\", \"source\": \"session\"}"
|
||||
}
|
||||
],
|
||||
"rows": [
|
||||
{
|
||||
"term": "exit",
|
||||
"limit": 4,
|
||||
"want": [
|
||||
{
|
||||
"topic": "alpha exit",
|
||||
"question": "q1",
|
||||
"outcome": "o1",
|
||||
"context": "ctx one",
|
||||
"status": "open",
|
||||
"reason": ""
|
||||
},
|
||||
{
|
||||
"topic": "delta",
|
||||
"question": "q4",
|
||||
"outcome": "o4",
|
||||
"context": "exit context here",
|
||||
"status": "open",
|
||||
"reason": ""
|
||||
}
|
||||
],
|
||||
"rust": [
|
||||
{
|
||||
"topic": "alpha exit",
|
||||
"question": "q1",
|
||||
"outcome": "o1",
|
||||
"context": "ctx one",
|
||||
"status": "open",
|
||||
"reason": ""
|
||||
},
|
||||
{
|
||||
"topic": "delta",
|
||||
"question": "q4",
|
||||
"outcome": "o4",
|
||||
"context": "exit context here",
|
||||
"status": "open",
|
||||
"reason": ""
|
||||
}
|
||||
],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"term": "exit",
|
||||
"limit": 1,
|
||||
"want": [
|
||||
{
|
||||
"topic": "alpha exit",
|
||||
"question": "q1",
|
||||
"outcome": "o1",
|
||||
"context": "ctx one",
|
||||
"status": "open",
|
||||
"reason": ""
|
||||
}
|
||||
],
|
||||
"rust": [
|
||||
{
|
||||
"topic": "alpha exit",
|
||||
"question": "q1",
|
||||
"outcome": "o1",
|
||||
"context": "ctx one",
|
||||
"status": "open",
|
||||
"reason": ""
|
||||
}
|
||||
],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"term": "alpha",
|
||||
"limit": 4,
|
||||
"want": [
|
||||
{
|
||||
"topic": "alpha exit",
|
||||
"question": "q1",
|
||||
"outcome": "o1",
|
||||
"context": "ctx one",
|
||||
"status": "open",
|
||||
"reason": ""
|
||||
}
|
||||
],
|
||||
"rust": [
|
||||
{
|
||||
"topic": "alpha exit",
|
||||
"question": "q1",
|
||||
"outcome": "o1",
|
||||
"context": "ctx one",
|
||||
"status": "open",
|
||||
"reason": ""
|
||||
}
|
||||
],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"term": "zzz",
|
||||
"limit": 4,
|
||||
"want": [],
|
||||
"rust": [],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"term": "context",
|
||||
"limit": 4,
|
||||
"want": [
|
||||
{
|
||||
"topic": "delta",
|
||||
"question": "q4",
|
||||
"outcome": "o4",
|
||||
"context": "exit context here",
|
||||
"status": "open",
|
||||
"reason": ""
|
||||
}
|
||||
],
|
||||
"rust": [
|
||||
{
|
||||
"topic": "delta",
|
||||
"question": "q4",
|
||||
"outcome": "o4",
|
||||
"context": "exit context here",
|
||||
"status": "open",
|
||||
"reason": ""
|
||||
}
|
||||
],
|
||||
"match": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
{
|
||||
"_doc": "FROZEN ORACLE (witness exit).",
|
||||
"topics": [
|
||||
{
|
||||
"text": "the quick brown fox jumps over the lazy dog",
|
||||
"want": [
|
||||
"quick",
|
||||
"brown",
|
||||
"jumps",
|
||||
"over",
|
||||
"lazy"
|
||||
],
|
||||
"rust": [
|
||||
"quick",
|
||||
"brown",
|
||||
"jumps",
|
||||
"over",
|
||||
"lazy"
|
||||
],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"text": "fix the memory leak in retrieval",
|
||||
"want": [
|
||||
"memory",
|
||||
"leak",
|
||||
"retrieval"
|
||||
],
|
||||
"rust": [
|
||||
"memory",
|
||||
"leak",
|
||||
"retrieval"
|
||||
],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"text": "hello",
|
||||
"want": [
|
||||
"hello"
|
||||
],
|
||||
"rust": [
|
||||
"hello"
|
||||
],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"text": "",
|
||||
"want": [],
|
||||
"rust": [],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"text": "Rust kernels and Python oracles must agree exactly",
|
||||
"want": [
|
||||
"rust",
|
||||
"kernels",
|
||||
"python",
|
||||
"oracles",
|
||||
"must"
|
||||
],
|
||||
"rust": [
|
||||
"rust",
|
||||
"kernels",
|
||||
"python",
|
||||
"oracles",
|
||||
"must"
|
||||
],
|
||||
"match": true
|
||||
}
|
||||
],
|
||||
"signals": [
|
||||
{
|
||||
"msg": "plain hello",
|
||||
"terr": null,
|
||||
"tstat": null,
|
||||
"rt": null,
|
||||
"want": {},
|
||||
"rust": {},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"msg": "I made an error fixing this",
|
||||
"terr": "traceback line 5",
|
||||
"tstat": null,
|
||||
"rt": null,
|
||||
"want": {
|
||||
"error": true,
|
||||
"error_text": "traceback line 5"
|
||||
},
|
||||
"rust": {
|
||||
"error": true,
|
||||
"error_text": "traceback line 5"
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"msg": "looks good, ship it",
|
||||
"terr": null,
|
||||
"tstat": "completed",
|
||||
"rt": [
|
||||
"rust kernels"
|
||||
],
|
||||
"want": {
|
||||
"topic_drift": true,
|
||||
"new_topics": [
|
||||
"looks",
|
||||
"good",
|
||||
"ship"
|
||||
]
|
||||
},
|
||||
"rust": {
|
||||
"topic_drift": true,
|
||||
"new_topics": [
|
||||
"looks",
|
||||
"good",
|
||||
"ship"
|
||||
]
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"msg": "looks good, ship it",
|
||||
"terr": null,
|
||||
"tstat": "done",
|
||||
"rt": [
|
||||
"rust kernels"
|
||||
],
|
||||
"want": {
|
||||
"completion": "done",
|
||||
"topic_drift": true,
|
||||
"new_topics": [
|
||||
"looks",
|
||||
"good",
|
||||
"ship"
|
||||
]
|
||||
},
|
||||
"rust": {
|
||||
"completion": "done",
|
||||
"topic_drift": true,
|
||||
"new_topics": [
|
||||
"looks",
|
||||
"good",
|
||||
"ship"
|
||||
]
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"msg": "",
|
||||
"terr": null,
|
||||
"tstat": null,
|
||||
"rt": null,
|
||||
"want": {},
|
||||
"rust": {},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"msg": "fix fix fix the bug now",
|
||||
"terr": "err",
|
||||
"tstat": "running",
|
||||
"rt": [],
|
||||
"want": {
|
||||
"error": true,
|
||||
"error_text": "err",
|
||||
"urgency_detected": true
|
||||
},
|
||||
"rust": {
|
||||
"error": true,
|
||||
"error_text": "err",
|
||||
"urgency_detected": true
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"msg": "task abandoned yesterday",
|
||||
"terr": null,
|
||||
"tstat": "abandoned",
|
||||
"rt": null,
|
||||
"want": {
|
||||
"completion": "abandoned"
|
||||
},
|
||||
"rust": {
|
||||
"completion": "abandoned"
|
||||
},
|
||||
"match": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -769,8 +769,13 @@ pub fn witness_signals(
|
||||
witness_extract_topic(message, &sw, 5),
|
||||
));
|
||||
}
|
||||
// ORACLE PARITY (frozen witness oracle): completion fires ONLY for the
|
||||
// frozen triple ("done", "abandoned", "failed"). Other statuses
|
||||
// ("completed", "running", ...) are NOT completion signals.
|
||||
if let Some(st) = task_status {
|
||||
sig.push(("completion".into(), Json::Str(st.to_string())));
|
||||
if st == "done" || st == "abandoned" || st == "failed" {
|
||||
sig.push(("completion".into(), Json::Str(st.to_string())));
|
||||
}
|
||||
}
|
||||
if !message.is_empty() && !recent_topics.is_empty() {
|
||||
let sw: Vec<Json> = match get(tables, "stopwords") {
|
||||
|
||||
@@ -8,6 +8,7 @@ floor, then the stage-level API may batch work to reduce Python calls.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -59,8 +60,9 @@ def main():
|
||||
{"id": i, **({"relevance": i / 10} if i % 2 else {"score": i / 12})}
|
||||
for i in range(17)], 5),
|
||||
]
|
||||
frozen_sec = json.loads((Path(__file__).parent / "frozen_score_recall.json").read_text())
|
||||
for name, entries, size in map_cases:
|
||||
py = ms._py_map_reduce(entries, size)
|
||||
py = [r["want"] for r in frozen_sec["map_cases"] if r["name"] == name][0]
|
||||
rs = mr_loader.map_reduce(entries, size)
|
||||
check(f"map_reduce: {name}", py == rs, f"py={py!r} rs={rs!r}")
|
||||
|
||||
@@ -79,7 +81,7 @@ def main():
|
||||
{"id": 2}, {"id": 3}]),
|
||||
]
|
||||
for name, entries in pos_cases:
|
||||
py = ms._py_position_aware(entries)
|
||||
py = [r["want"] for r in frozen_sec["pos_cases"] if r["name"] == name][0]
|
||||
rs = mr_loader.position_aware(entries)
|
||||
check(f"position: {name}", py == rs, f"py={py!r} rs={rs!r}")
|
||||
|
||||
@@ -87,7 +89,7 @@ def main():
|
||||
for query in ("", "the and for", "black coffee",
|
||||
"one two three", "quoted \"term\" punctuation!",
|
||||
"a b c d e f g h i j k l", "UNICODE héllo world"):
|
||||
py = ms._py_fts_query_conjunctive(query)
|
||||
py = [r["want"] for r in frozen_sec["fts_cases"] if r["query"] == query][0]
|
||||
rs = mr_loader.fts_query_conjunctive(query)
|
||||
check(f"fts {query!r}", py == rs, f"py={py!r} rs={rs!r}")
|
||||
|
||||
@@ -100,12 +102,12 @@ def main():
|
||||
("unicode chars", "héllo 🎸 " * 20, 30, 9),
|
||||
]
|
||||
for name, text, size, overlap in chunk_cases:
|
||||
py = ms._py_chunk_text(text, size, overlap)
|
||||
py = [r["want"] for r in frozen_sec["chunk_cases"] if r["name"] == name][0]
|
||||
rs = mr_loader.chunk_text(text, size, overlap)
|
||||
check(f"chunk: {name}", py == rs, f"py={py!r} rs={rs!r}")
|
||||
|
||||
for text in (None, "", " Hello WORLD ", "Unicode — HÉLLO 🎸"):
|
||||
py = ms._py_norm_key(text)
|
||||
py = [r["want"] for r in frozen_sec["norm_cases"] if r["text"] == text][0]
|
||||
rs = mr_loader.norm_key(text)
|
||||
check(f"norm {text!r}", py == rs, f"py={py!r} rs={rs!r}")
|
||||
|
||||
@@ -130,8 +132,9 @@ def main():
|
||||
[{"id": 1, "text": "HÉLLO 🎸", "relevance": 1.0}],
|
||||
[{"chunk_id": "c", "text": "different — ü", "rrf": 0.2}]),
|
||||
]
|
||||
frozen_fuse = {r["name"]: r["want"] for r in json.loads((Path(__file__).parent / "frozen_score_recall.json").read_text())["fuse_cases"]}
|
||||
for name, entries, research in fuse_cases:
|
||||
py = ms._py_fuse_results(entries, research)
|
||||
py = frozen_fuse[name]
|
||||
rs = mr_loader.fuse_results(entries, research)
|
||||
check(f"fuse: {name}", py == rs, f"py={py!r} rs={rs!r}")
|
||||
|
||||
@@ -148,8 +151,9 @@ def main():
|
||||
"last_accessed": "2026-10-04", "confidence": 0.0,
|
||||
"temperature": 0.0},
|
||||
]
|
||||
frozen_assoc = {r["budget"]: r["want"] for r in json.loads((Path(__file__).parent / "frozen_score_recall.json").read_text())["assoc"]}
|
||||
for budget in (1, 2, 8):
|
||||
py = ms._py_merge_association_rows(base, boosts, rows, budget)
|
||||
py = frozen_assoc[budget]
|
||||
rs = mr_loader.merge_association_rows(base, boosts, rows, budget)
|
||||
check(f"association merge budget={budget}", py == rs,
|
||||
f"py={py!r} rs={rs!r}")
|
||||
@@ -166,8 +170,9 @@ def main():
|
||||
[[2, -7.0], [3, -9.0]]),
|
||||
("ties stable", [[2, 0.8], [1, 0.8]], [[1, -5.0], [2, -5.0]]),
|
||||
]
|
||||
frozen_fx = {r["name"]: r["want"] for r in json.loads((Path(__file__).parent / "frozen_score_recall.json").read_text())["fusion_cases"]}
|
||||
for name, dense, bm25 in fusion_cases:
|
||||
py = ms._py_rank_fusion(dense, bm25)
|
||||
py = frozen_fx[name]
|
||||
rs = mr_loader.rank_fusion(dense, bm25, ms.RRF_K)
|
||||
check(f"rank fusion: {name}", py == rs, f"py={py!r} rs={rs!r}")
|
||||
|
||||
@@ -190,12 +195,13 @@ def main():
|
||||
("none", None)]
|
||||
meta_cases = [(0.8, 1.0), (None, None), (0.0, 1.0), (0.8, None),
|
||||
(0.8, 0.0), (0.0, None)]
|
||||
frozen_mx = {(tuple(map(tuple, r["dense"])), tuple(map(tuple, r["bm25"])), r["last"], r["conf"], r["temp"]): r["want"]
|
||||
for r in json.loads((Path(__file__).parent / "frozen_score_recall.json").read_text())["canary_matrix"]}
|
||||
for label, last in stamp_cases:
|
||||
for dense, bm25, mode in [([[20, 0.9]], [], "dense-only"),
|
||||
([], [[20, -8.0]], "lexical-only"),
|
||||
([[20, 0.9]], [[20, -8.0]], "hybrid")]:
|
||||
py = ms._py_score_recall_rows(ms._py_rank_fusion(dense, bm25),
|
||||
mk(0.8, 1.0, last), dense, bm25, 10, 0.42, NOW)
|
||||
py = frozen_mx[(tuple(map(tuple, dense)), tuple(map(tuple, bm25)), last, 0.8, 1.0)]
|
||||
rs = mr_loader.score_recall_rows(
|
||||
mr_loader.rank_fusion(dense, bm25, ms.RRF_K),
|
||||
mk(0.8, 1.0, last), dense, bm25, 10, 0.42, NOW,
|
||||
@@ -203,20 +209,17 @@ def main():
|
||||
check(f"score {mode} {label}", py == rs, f"py={py!r} rs={rs!r}")
|
||||
for conf, temp in meta_cases:
|
||||
dense = [[20, 0.9]]
|
||||
py = ms._py_score_recall_rows(ms._py_rank_fusion(dense, []),
|
||||
mk(conf, temp, "2026-10-04T11:00:00+00:00"),
|
||||
dense, [], 10, 0.42, NOW)
|
||||
py = frozen_mx[(tuple(map(tuple, dense)), (), "2026-10-04T11:00:00+00:00", conf, temp)]
|
||||
rs = mr_loader.score_recall_rows(
|
||||
mr_loader.rank_fusion(dense, [], ms.RRF_K),
|
||||
mk(conf, temp, "2026-10-04T11:00:00+00:00"), dense, [], 10, 0.42,
|
||||
NOW, ms.RECENCY_HALF_LIFE)
|
||||
check(f"score meta {conf}/{temp}", py == rs, f"py={py!r} rs={rs!r}")
|
||||
floor_cases = [(0.7, 0.42), (0.74, 0.42), (0.75, 0.42), (0.6, 0.42)]
|
||||
frozen_fl = {(r["bd"], r["floor"]): r["want"] for r in json.loads((Path(__file__).parent / "frozen_score_recall.json").read_text())["floor_cases"]}
|
||||
for bd, floor in floor_cases:
|
||||
dense = [[20, bd]]
|
||||
py = ms._py_score_recall_rows(ms._py_rank_fusion(dense, []),
|
||||
mk(0.8, 1.0, "2026-10-04T11:00:00+00:00"),
|
||||
dense, [], 10, floor, NOW)
|
||||
py = frozen_fl[(bd, floor)]
|
||||
rs = mr_loader.score_recall_rows(
|
||||
mr_loader.rank_fusion(dense, [], ms.RRF_K),
|
||||
mk(0.8, 1.0, "2026-10-04T11:00:00+00:00"), dense, [], 10, floor,
|
||||
@@ -229,8 +232,8 @@ def main():
|
||||
"last_accessed": "2026-10-04T11:00:00+00:00", "topic": "t",
|
||||
"entities": "[]", "source": "s", "status": "active",
|
||||
"memory_type": None, "confidence": 0.8, "temperature": 1.0}]
|
||||
py = ms._py_score_recall_rows(ms._py_rank_fusion(dense, []),
|
||||
rows2, dense, [], 10, 0.42, NOW)
|
||||
py = [r["want"] for r in json.loads((Path(__file__).parent / "frozen_score_recall.json").read_text())["gap_cases"]
|
||||
if abs(r["gap"] - gap) < 1e-12][0]
|
||||
rs = mr_loader.score_recall_rows(
|
||||
mr_loader.rank_fusion(dense, [], ms.RRF_K), rows2, dense, [],
|
||||
10, 0.42, NOW, ms.RECENCY_HALF_LIFE)
|
||||
@@ -246,8 +249,7 @@ def main():
|
||||
"entities": "[]", "source": "s", "status": "active",
|
||||
"memory_type": None, "confidence": 0.8, "temperature": 1.0}
|
||||
for i in range(1, 13)]
|
||||
py = ms._py_score_recall_rows(ms._py_rank_fusion(dense, bm25), big_rows,
|
||||
dense, bm25, 10, 0.42, NOW)
|
||||
py = json.loads((Path(__file__).parent / "frozen_score_recall.json").read_text())["improvement"]["want"]
|
||||
rs = mr_loader.score_recall_rows(
|
||||
mr_loader.rank_fusion(dense, bm25, ms.RRF_K), big_rows, dense, bm25,
|
||||
10, 0.42, NOW, ms.RECENCY_HALF_LIFE)
|
||||
@@ -263,8 +265,9 @@ def main():
|
||||
"room": "r", "source_path": "p", "page": 7},
|
||||
{"rowid": 3, "chunk_id": "c3", "text": "u — héllo 🎸",
|
||||
"wing": "w2", "room": "", "source_path": "", "page": None}]
|
||||
frozen_cp = {r["budget"]: r["want"] for r in json.loads((Path(__file__).parent / "frozen_score_recall.json").read_text())["chunk_proj"]}
|
||||
for budget in (1, 2, 6):
|
||||
py = ms._py_project_chunk_rows(ranks, crows, budget)
|
||||
py = frozen_cp[budget]
|
||||
rs = mr_loader.project_chunk_rows(
|
||||
[list(r) for r in ranks.items()], crows, budget)
|
||||
check(f"chunk projection budget={budget}", py == rs,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"_doc": "FROZEN ORACLE (selector kernels).",
|
||||
"score": [
|
||||
{
|
||||
"item": {
|
||||
"score": 0.5
|
||||
},
|
||||
"want": 0.5
|
||||
},
|
||||
{
|
||||
"item": {
|
||||
"score": 0
|
||||
},
|
||||
"want": 0.0
|
||||
},
|
||||
{
|
||||
"item": {
|
||||
"score": 1.0
|
||||
},
|
||||
"want": 1.0
|
||||
},
|
||||
{
|
||||
"item": {},
|
||||
"want": 0.0
|
||||
},
|
||||
{
|
||||
"item": {
|
||||
"score": true
|
||||
},
|
||||
"want": 0.0
|
||||
},
|
||||
{
|
||||
"item": {
|
||||
"score": "0.5"
|
||||
},
|
||||
"want": 0.0
|
||||
},
|
||||
{
|
||||
"item": {
|
||||
"score": null
|
||||
},
|
||||
"want": 0.0
|
||||
}
|
||||
],
|
||||
"lex": [
|
||||
{
|
||||
"text": "housing burden and rent",
|
||||
"query": "housing rent eviction",
|
||||
"want": 0.6666666666666666
|
||||
},
|
||||
{
|
||||
"text": "nothing shared here xyz",
|
||||
"query": "housing rent",
|
||||
"want": 0.0
|
||||
},
|
||||
{
|
||||
"text": "",
|
||||
"query": "housing",
|
||||
"want": 0.0
|
||||
},
|
||||
{
|
||||
"text": "black coffee",
|
||||
"query": "black holes",
|
||||
"want": 0.5
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -97,6 +97,14 @@ pub extern "C" fn mr_call(arg: *const c_char) -> *mut c_char {
|
||||
};
|
||||
Ok(pyjson::Json::Str(retrieval::norm_key(text)))
|
||||
}
|
||||
"score_of" => {
|
||||
let item = get(p, "item").cloned().unwrap_or(pyjson::Json::Null);
|
||||
Ok(pyjson::Json::Num(retrieval::score_of(&item)))
|
||||
}
|
||||
"lex_overlap_score" => Ok(pyjson::Json::Num(retrieval::lex_overlap_score(
|
||||
s(get(p, "text")),
|
||||
s(get(p, "query")),
|
||||
))),
|
||||
"fuse_results" => {
|
||||
let e = match get(p, "entries") {
|
||||
Some(pyjson::Json::Arr(v)) => v.clone(),
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
{
|
||||
"_doc": "FROZEN ORACLE (drift_core exit).",
|
||||
"rows": [
|
||||
{
|
||||
"name": "cv0",
|
||||
"entry": {
|
||||
"wash_count": 0,
|
||||
"importance": 0.5,
|
||||
"last_accessed": null
|
||||
},
|
||||
"want": 0.375,
|
||||
"rust": 0.375,
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"name": "cv1",
|
||||
"entry": {
|
||||
"wash_count": 25,
|
||||
"importance": 0.9,
|
||||
"last_accessed": "2026-10-09T00:00:00+00:00"
|
||||
},
|
||||
"want": 0.8405,
|
||||
"rust": 0.8405,
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"name": "cv2",
|
||||
"entry": {
|
||||
"wash_count": 5,
|
||||
"importance": 0.3,
|
||||
"last_accessed": "2026-06-01T00:00:00+00:00",
|
||||
"text": "memory about rust kernels"
|
||||
},
|
||||
"want": 0.3537,
|
||||
"rust": 0.3537,
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"name": "cv3",
|
||||
"entry": {
|
||||
"wash_count": 100,
|
||||
"importance": 1.0,
|
||||
"last_accessed": "2026-10-10T11:00:00+00:00",
|
||||
"text": "rust kernels and memory"
|
||||
},
|
||||
"want": 0.9497,
|
||||
"rust": 0.9497,
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"name": "cv_goals",
|
||||
"entry": {
|
||||
"wash_count": 5,
|
||||
"importance": 0.3,
|
||||
"last_accessed": "2026-06-01T00:00:00+00:00",
|
||||
"text": "memory about rust kernels"
|
||||
},
|
||||
"goals": [
|
||||
"rust kernels"
|
||||
],
|
||||
"want": 0.4037,
|
||||
"rust": 0.4037,
|
||||
"match": true
|
||||
}
|
||||
],
|
||||
"promotion_rows": [
|
||||
{
|
||||
"name": "pe_0_washable",
|
||||
"entry": {
|
||||
"wash_count": 0,
|
||||
"rock_status": "washable",
|
||||
"importance": 0.7,
|
||||
"last_accessed": "2026-10-09T00:00:00+00:00"
|
||||
},
|
||||
"want": [
|
||||
false,
|
||||
"proven_uses 0 < threshold 20"
|
||||
],
|
||||
"rust": [
|
||||
false,
|
||||
"proven_uses 0 < threshold 20"
|
||||
],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"name": "pe_5_washable",
|
||||
"entry": {
|
||||
"wash_count": 5,
|
||||
"rock_status": "washable",
|
||||
"importance": 0.7,
|
||||
"last_accessed": "2026-10-09T00:00:00+00:00"
|
||||
},
|
||||
"want": [
|
||||
false,
|
||||
"proven_uses 5 < threshold 20"
|
||||
],
|
||||
"rust": [
|
||||
false,
|
||||
"proven_uses 5 < threshold 20"
|
||||
],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"name": "pe_25_washable",
|
||||
"entry": {
|
||||
"wash_count": 25,
|
||||
"rock_status": "washable",
|
||||
"importance": 0.7,
|
||||
"last_accessed": "2026-10-09T00:00:00+00:00"
|
||||
},
|
||||
"want": [
|
||||
true,
|
||||
"wash_count=25, value=0.790"
|
||||
],
|
||||
"rust": [
|
||||
true,
|
||||
"wash_count=25, value=0.790"
|
||||
],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"name": "pe_10_rock",
|
||||
"entry": {
|
||||
"wash_count": 10,
|
||||
"rock_status": "rock",
|
||||
"importance": 0.7,
|
||||
"last_accessed": "2026-10-09T00:00:00+00:00"
|
||||
},
|
||||
"want": [
|
||||
false,
|
||||
"already rock"
|
||||
],
|
||||
"rust": [
|
||||
false,
|
||||
"already rock"
|
||||
],
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"name": "pe_30_washable",
|
||||
"entry": {
|
||||
"wash_count": 30,
|
||||
"rock_status": "washable",
|
||||
"importance": 0.7,
|
||||
"last_accessed": "2026-10-09T00:00:00+00:00"
|
||||
},
|
||||
"want": [
|
||||
true,
|
||||
"wash_count=30, value=0.805"
|
||||
],
|
||||
"rust": [
|
||||
true,
|
||||
"wash_count=30, value=0.805"
|
||||
],
|
||||
"match": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -70,6 +70,9 @@ pub extern "C" fn ms_compute_value(arg: *const c_char) -> *mut c_char {
|
||||
let now = get_str(&a, "now").ok_or("arg.now required")?.to_string();
|
||||
let goals = get(&a, "goals").cloned();
|
||||
let v = scoring::compute_value(&entry, goals.as_ref(), &now);
|
||||
if !v.is_finite() {
|
||||
return Err("compute_value: non-numeric or out-of-domain wash_count (oracle: TypeError/ValueError)".to_string());
|
||||
}
|
||||
Ok(pyjson::Json::Num(v))
|
||||
});
|
||||
envelope(result)
|
||||
|
||||
@@ -37,6 +37,9 @@ fn obj_get<'a>(v: &'a Json, key: &str) -> Option<&'a Json> {
|
||||
fn as_num(v: Option<&Json>) -> Option<f64> {
|
||||
match v {
|
||||
Some(Json::Num(n)) => Some(*n),
|
||||
// Python bool IS int (True==1): log1p(True) works. Parity demands it.
|
||||
Some(Json::Bool(true)) => Some(1.0),
|
||||
Some(Json::Bool(false)) => Some(0.0),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -148,9 +151,26 @@ pub fn parse_iso(s: &str) -> Option<f64> {
|
||||
// ── compute_value ───────────────────────────────────────────────────────────
|
||||
|
||||
pub fn compute_value(entry: &Json, goals: Option<&Json>, now_iso: &str) -> f64 {
|
||||
// TYPE PARITY: Python raises TypeError on non-numeric wash_count
|
||||
// (log1p on a str). A string/bool/object wash_count must error, not
|
||||
// silently default to 0.0.
|
||||
if let Some(wc) = obj_get(entry, "wash_count") {
|
||||
match wc {
|
||||
Json::Num(_) | Json::Null | Json::Bool(_) => {}
|
||||
_ => return f64::NAN,
|
||||
}
|
||||
}
|
||||
let proven = num_or(obj_get(entry, "wash_count"), 0.0);
|
||||
let imp = num_or(obj_get(entry, "importance"), 0.5);
|
||||
|
||||
// ORACLE PARITY (adversarial edges, test_constitutional_adversarial):
|
||||
// Python log1p raises TypeError on non-numbers and ValueError on
|
||||
// proven <= -1. The envelope must ERROR, never silently score.
|
||||
// (NaN.min(1.0) == 1.0 in Rust would INVERT the edge: negative wash
|
||||
// counts would score proven_factor=MAX. Fail loud instead.)
|
||||
if !proven.is_finite() || proven <= -1.0 {
|
||||
return f64::NAN; // sentinel: the FFI layer converts to Err
|
||||
}
|
||||
let proven_factor = (proven.ln_1p() / PROVEN_USES_THRESHOLD.ln_1p()).min(1.0);
|
||||
|
||||
let mut recency = 1.0;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -190,7 +190,9 @@ def main() -> int:
|
||||
|
||||
# ── 6. language placement (the protocol's dichotomy intelligence) ─────
|
||||
print("\n--- 6. Language placement ---")
|
||||
from rune import construction_decision as cd_mod # noqa: E402
|
||||
from rune import construction_decision as cd_mod # noqa: E402 — public delegation probe only; kernel expectations frozen below
|
||||
frozen_lp = json.loads((Path(__file__).parent / "frozen_language_placement.json").read_text(encoding="utf-8"))
|
||||
frozen_lp_rows = {(r["project"], tuple(r["chars"])): r["want"] for r in frozen_lp["rows"]}
|
||||
|
||||
placement_cases = [
|
||||
("rune", ["network", "reactive"], "go"),
|
||||
@@ -211,7 +213,10 @@ def main() -> int:
|
||||
("RUNE", ["Reactive"], "go"), # case-insensitive
|
||||
]
|
||||
for project, chars, want in placement_cases:
|
||||
py = cd_mod._py_language_placement(project, chars)
|
||||
py = frozen_lp_rows.get((project, tuple(chars)))
|
||||
if py is None:
|
||||
# case not in frozen oracle: compute via public delegation (kernel live)
|
||||
py = cd_mod.language_placement(project, chars)
|
||||
rs = sc_loader.language_placement(project, chars)
|
||||
test(f"placement {project} {chars} -> {want}",
|
||||
py == rs and rs["placement"] == want,
|
||||
|
||||
@@ -0,0 +1,462 @@
|
||||
{
|
||||
"_doc": "FROZEN ORACLE (language_placement exit).",
|
||||
"rows": [
|
||||
{
|
||||
"project": "rune",
|
||||
"chars": [
|
||||
"route",
|
||||
"dispatch",
|
||||
"chat"
|
||||
],
|
||||
"want": {
|
||||
"placement": "go",
|
||||
"rule": "rune dichotomy: reactive/initiating markers",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"route",
|
||||
"dispatch",
|
||||
"chat"
|
||||
],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"rust": {
|
||||
"placement": "go",
|
||||
"rule": "rune dichotomy: reactive/initiating markers",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"route",
|
||||
"dispatch",
|
||||
"chat"
|
||||
],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"project": "rune",
|
||||
"chars": [
|
||||
"compute",
|
||||
"store",
|
||||
"ledger"
|
||||
],
|
||||
"want": {
|
||||
"placement": "rust",
|
||||
"rule": "rune dichotomy: deterministic/state markers",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": [
|
||||
"compute",
|
||||
"store",
|
||||
"ledger"
|
||||
]
|
||||
}
|
||||
},
|
||||
"rust": {
|
||||
"placement": "rust",
|
||||
"rule": "rune dichotomy: deterministic/state markers",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": [
|
||||
"compute",
|
||||
"store",
|
||||
"ledger"
|
||||
]
|
||||
}
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"project": "rune",
|
||||
"chars": [
|
||||
"route",
|
||||
"compute"
|
||||
],
|
||||
"want": {
|
||||
"placement": "hybrid",
|
||||
"rule": "rune dichotomy: both marker classes \u2014 a contracted membrane junction",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"route"
|
||||
],
|
||||
"rust_signals": [
|
||||
"compute"
|
||||
]
|
||||
}
|
||||
},
|
||||
"rust": {
|
||||
"placement": "hybrid",
|
||||
"rule": "rune dichotomy: both marker classes \u2014 a contracted membrane junction",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"route"
|
||||
],
|
||||
"rust_signals": [
|
||||
"compute"
|
||||
]
|
||||
}
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"project": "rune",
|
||||
"chars": [
|
||||
"zzz_no_signals"
|
||||
],
|
||||
"want": {
|
||||
"placement": "rust",
|
||||
"rule": "rune dichotomy: pure compute defaults to the deterministic backend",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"rust": {
|
||||
"placement": "rust",
|
||||
"rule": "rune dichotomy: pure compute defaults to the deterministic backend",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"project": "other",
|
||||
"chars": [
|
||||
"http",
|
||||
"server"
|
||||
],
|
||||
"want": {
|
||||
"placement": "go",
|
||||
"rule": "characteristic fit: reactive/network profile",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"http",
|
||||
"server"
|
||||
],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"rust": {
|
||||
"placement": "go",
|
||||
"rule": "characteristic fit: reactive/network profile",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"http",
|
||||
"server"
|
||||
],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"project": "other",
|
||||
"chars": [
|
||||
"deterministic",
|
||||
"pure-function"
|
||||
],
|
||||
"want": {
|
||||
"placement": "rust",
|
||||
"rule": "characteristic fit: deterministic/state profile",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": [
|
||||
"deterministic",
|
||||
"pure-function"
|
||||
]
|
||||
}
|
||||
},
|
||||
"rust": {
|
||||
"placement": "rust",
|
||||
"rule": "characteristic fit: deterministic/state profile",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": [
|
||||
"deterministic",
|
||||
"pure-function"
|
||||
]
|
||||
}
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"project": "other",
|
||||
"chars": [
|
||||
"http",
|
||||
"compute"
|
||||
],
|
||||
"want": {
|
||||
"placement": "hybrid",
|
||||
"rule": "characteristic fit: mixed profile \u2014 split at the membrane",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"http"
|
||||
],
|
||||
"rust_signals": [
|
||||
"compute"
|
||||
]
|
||||
}
|
||||
},
|
||||
"rust": {
|
||||
"placement": "hybrid",
|
||||
"rule": "characteristic fit: mixed profile \u2014 split at the membrane",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"http"
|
||||
],
|
||||
"rust_signals": [
|
||||
"compute"
|
||||
]
|
||||
}
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"project": "other",
|
||||
"chars": [
|
||||
"zzz"
|
||||
],
|
||||
"want": {
|
||||
"placement": "unassessed",
|
||||
"rule": "no placement signals \u2014 the unit needs characteristics recorded",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"rust": {
|
||||
"placement": "unassessed",
|
||||
"rule": "no placement signals \u2014 the unit needs characteristics recorded",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"project": "RUNE",
|
||||
"chars": [
|
||||
"MODEL",
|
||||
"Provider"
|
||||
],
|
||||
"want": {
|
||||
"placement": "go",
|
||||
"rule": "rune dichotomy: reactive/initiating markers",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"model",
|
||||
"provider"
|
||||
],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"rust": {
|
||||
"placement": "go",
|
||||
"rule": "rune dichotomy: reactive/initiating markers",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"model",
|
||||
"provider"
|
||||
],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"project": "rune",
|
||||
"chars": [],
|
||||
"want": {
|
||||
"placement": "rust",
|
||||
"rule": "rune dichotomy: pure compute defaults to the deterministic backend",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"rust": {
|
||||
"placement": "rust",
|
||||
"rule": "rune dichotomy: pure compute defaults to the deterministic backend",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": []
|
||||
}
|
||||
},
|
||||
"match": true
|
||||
},
|
||||
{
|
||||
"project": "rune",
|
||||
"chars": [
|
||||
"network",
|
||||
"reactive"
|
||||
],
|
||||
"want": {
|
||||
"placement": "go",
|
||||
"rule": "rune dichotomy: reactive/initiating markers",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"reactive",
|
||||
"network"
|
||||
],
|
||||
"rust_signals": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"project": "rune",
|
||||
"chars": [
|
||||
"storage",
|
||||
"deterministic"
|
||||
],
|
||||
"want": {
|
||||
"placement": "rust",
|
||||
"rule": "rune dichotomy: deterministic/state markers",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": [
|
||||
"deterministic"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"project": "rune",
|
||||
"chars": [
|
||||
"network",
|
||||
"storage"
|
||||
],
|
||||
"want": {
|
||||
"placement": "go",
|
||||
"rule": "rune dichotomy: reactive/initiating markers",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"network"
|
||||
],
|
||||
"rust_signals": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"project": "rune",
|
||||
"chars": [
|
||||
"network",
|
||||
"store"
|
||||
],
|
||||
"want": {
|
||||
"placement": "hybrid",
|
||||
"rule": "rune dichotomy: both marker classes \u2014 a contracted membrane junction",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"network"
|
||||
],
|
||||
"rust_signals": [
|
||||
"store"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"project": "rune",
|
||||
"chars": [
|
||||
"pure compute"
|
||||
],
|
||||
"want": {
|
||||
"placement": "rust",
|
||||
"rule": "rune dichotomy: deterministic/state markers",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": [
|
||||
"compute"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"project": "other-proj",
|
||||
"chars": [
|
||||
"http",
|
||||
"server"
|
||||
],
|
||||
"want": {
|
||||
"placement": "go",
|
||||
"rule": "characteristic fit: reactive/network profile",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"http",
|
||||
"server"
|
||||
],
|
||||
"rust_signals": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"project": "other-proj",
|
||||
"chars": [
|
||||
"memory",
|
||||
"ledger"
|
||||
],
|
||||
"want": {
|
||||
"placement": "rust",
|
||||
"rule": "characteristic fit: deterministic/state profile",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": [
|
||||
"memory",
|
||||
"ledger"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"project": "other-proj",
|
||||
"chars": [
|
||||
"memory",
|
||||
"network"
|
||||
],
|
||||
"want": {
|
||||
"placement": "hybrid",
|
||||
"rule": "characteristic fit: mixed profile \u2014 split at the membrane",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"network"
|
||||
],
|
||||
"rust_signals": [
|
||||
"memory"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"project": "other-proj",
|
||||
"chars": [],
|
||||
"want": {
|
||||
"placement": "unassessed",
|
||||
"rule": "no placement signals \u2014 the unit needs characteristics recorded",
|
||||
"evidence": {
|
||||
"go_signals": [],
|
||||
"rust_signals": []
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"project": "RUNE",
|
||||
"chars": [
|
||||
"Reactive"
|
||||
],
|
||||
"want": {
|
||||
"placement": "go",
|
||||
"rule": "rune dichotomy: reactive/initiating markers",
|
||||
"evidence": {
|
||||
"go_signals": [
|
||||
"reactive"
|
||||
],
|
||||
"rust_signals": []
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""canary_structural_store.py — parity battery for the structural_store crate.
|
||||
|
||||
Asserts the Rust kernels against the frozen oracle (frozen_structural.json),
|
||||
generated from the live Python on facade-1 day. The canary never imports the
|
||||
Python oracles — parity stays provable after strangler exits.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
CRATE_DIR = Path(__file__).resolve().parent
|
||||
PASS, FAIL = 0, 0
|
||||
|
||||
|
||||
def test(name, cond, detail=""):
|
||||
global PASS, FAIL
|
||||
if cond:
|
||||
PASS += 1
|
||||
else:
|
||||
FAIL += 1
|
||||
print(f" ✗ {name} — {detail}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
r = subprocess.run(["cargo", "build", "--release"], cwd=CRATE_DIR,
|
||||
capture_output=True, text=True)
|
||||
test("cargo build --release exits 0", r.returncode == 0, r.stderr[-300:])
|
||||
if r.returncode != 0:
|
||||
print(f"\nRESULTS: {PASS} pass, {FAIL} fail")
|
||||
return 1
|
||||
sys.path.insert(0, str(CRATE_DIR.parents[2] / "src"))
|
||||
sys.path.insert(0, str(CRATE_DIR))
|
||||
from rune import ss_loader # noqa: E402
|
||||
frozen = json.loads((CRATE_DIR / "frozen_structural.json").read_text())
|
||||
for state, want in frozen["ranks"].items():
|
||||
test(f"rank {state}={want}", ss_loader.maturity_rank(state) == want)
|
||||
for row in frozen["rows"]:
|
||||
op = row["op"]
|
||||
if op == "promote":
|
||||
d = copy.deepcopy(row["doc"])
|
||||
got = ss_loader.promote(d, row["id"], row["state"], row["ev"],
|
||||
"2026-10-10T00:00:00Z")
|
||||
ge = [e for e in got["entities"] if e["id"] == row["id"]][0]
|
||||
we = row["want_entity"]
|
||||
test(f"promote {row['id']}->{row['state']}",
|
||||
ge["maturity"] == we["maturity"]
|
||||
and sorted(ge["evidence_refs"]) == sorted(we["evidence_refs"]))
|
||||
elif op == "demote":
|
||||
d = copy.deepcopy(row["doc"])
|
||||
got = ss_loader.promote(d, row["id"], row["state"], row["ev"],
|
||||
"2026-10-10T00:00:00Z")
|
||||
ge = [e for e in got["entities"] if e["id"] == row["id"]][0]
|
||||
test("demotion rejected, recorded",
|
||||
ge["maturity"] == row["want_entity"]["maturity"]
|
||||
and any(o["kind"] == "maturity_demotion_rejected"
|
||||
for o in got["observations"]))
|
||||
elif op in ("no-ev", "bad-state"):
|
||||
d = {"entities": [{"id": "m:a", "maturity": "DECLARED",
|
||||
"evidence_refs": []}],
|
||||
"relationships": [], "observations": []}
|
||||
try:
|
||||
if op == "no-ev":
|
||||
ss_loader.promote(d, "m:a", "PRESENT", "",
|
||||
"2026-10-10T00:00:00Z")
|
||||
else:
|
||||
ss_loader.promote(d, "m:a", "BOGUS", "ev",
|
||||
"2026-10-10T00:00:00Z")
|
||||
test(f"error case {op} raises", False, "no error raised")
|
||||
except RuntimeError:
|
||||
test(f"error case {op} raises", True)
|
||||
elif op == "supersede":
|
||||
d = copy.deepcopy(row["doc"])
|
||||
got = ss_loader.supersede(d, "m:b", "m:a", "ev-s",
|
||||
"2026-10-10T00:00:00Z")
|
||||
go = [e for e in got["entities"] if e["id"] == "m:a"][0]
|
||||
test("supersede marks old", go.get("status") == "SUPERSEDED"
|
||||
and go.get("superseded_by") == "m:b")
|
||||
elif op == "resolve":
|
||||
test(f"resolve {row['entity']}",
|
||||
ss_loader.resolve_status(row["entity"]) == row["want"])
|
||||
print(f"\nRESULTS: {PASS} pass, {FAIL} fail")
|
||||
return 1 if FAIL else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,182 @@
|
||||
{
|
||||
"_doc": "FROZEN ORACLE (structural_store facade-1).",
|
||||
"ranks": {
|
||||
"DECLARED": 0,
|
||||
"PRESENT": 1,
|
||||
"WIRED": 2,
|
||||
"REACHABLE": 3,
|
||||
"EXERCISED": 4,
|
||||
"LIVE_PROVEN": 5
|
||||
},
|
||||
"rows": [
|
||||
{
|
||||
"op": "promote",
|
||||
"doc": {
|
||||
"entities": [
|
||||
{
|
||||
"id": "m:a",
|
||||
"kind": "module",
|
||||
"maturity": "DECLARED",
|
||||
"evidence_refs": []
|
||||
},
|
||||
{
|
||||
"id": "m:b",
|
||||
"kind": "module",
|
||||
"maturity": "PRESENT",
|
||||
"evidence_refs": [
|
||||
"ev-0"
|
||||
]
|
||||
}
|
||||
],
|
||||
"relationships": [],
|
||||
"observations": []
|
||||
},
|
||||
"id": "m:a",
|
||||
"state": "PRESENT",
|
||||
"ev": "ev-1",
|
||||
"want_entity": {
|
||||
"id": "m:a",
|
||||
"kind": "module",
|
||||
"maturity": "PRESENT",
|
||||
"evidence_refs": [
|
||||
"ev-1"
|
||||
],
|
||||
"observed_at": "2026-10-10T17:53:36Z"
|
||||
},
|
||||
"want_obs": []
|
||||
},
|
||||
{
|
||||
"op": "demote",
|
||||
"doc": {
|
||||
"entities": [
|
||||
{
|
||||
"id": "m:a",
|
||||
"kind": "module",
|
||||
"maturity": "DECLARED",
|
||||
"evidence_refs": []
|
||||
},
|
||||
{
|
||||
"id": "m:b",
|
||||
"kind": "module",
|
||||
"maturity": "PRESENT",
|
||||
"evidence_refs": [
|
||||
"ev-0"
|
||||
]
|
||||
}
|
||||
],
|
||||
"relationships": [],
|
||||
"observations": []
|
||||
},
|
||||
"id": "m:b",
|
||||
"state": "DECLARED",
|
||||
"ev": "ev-2",
|
||||
"want_entity": {
|
||||
"id": "m:b",
|
||||
"kind": "module",
|
||||
"maturity": "PRESENT",
|
||||
"evidence_refs": [
|
||||
"ev-0"
|
||||
]
|
||||
},
|
||||
"want_obs": [
|
||||
{
|
||||
"kind": "maturity_demotion_rejected",
|
||||
"entity": "m:b",
|
||||
"requested": "DECLARED",
|
||||
"current": "PRESENT",
|
||||
"observed_at": "2026-10-10T17:53:36Z"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"op": "no-ev",
|
||||
"raises": true,
|
||||
"msg": "promotion of m:a to PRESENT requires evidence"
|
||||
},
|
||||
{
|
||||
"op": "bad-state",
|
||||
"raises": true,
|
||||
"msg": "unknown maturity state: BOGUS"
|
||||
},
|
||||
{
|
||||
"op": "supersede",
|
||||
"doc": {
|
||||
"entities": [
|
||||
{
|
||||
"id": "m:a",
|
||||
"kind": "module",
|
||||
"maturity": "DECLARED",
|
||||
"evidence_refs": []
|
||||
},
|
||||
{
|
||||
"id": "m:b",
|
||||
"kind": "module",
|
||||
"maturity": "PRESENT",
|
||||
"evidence_refs": [
|
||||
"ev-0"
|
||||
]
|
||||
}
|
||||
],
|
||||
"relationships": [],
|
||||
"observations": []
|
||||
},
|
||||
"want_old": {
|
||||
"id": "m:a",
|
||||
"kind": "module",
|
||||
"maturity": "DECLARED",
|
||||
"evidence_refs": [],
|
||||
"superseded_by": "m:b",
|
||||
"status": "SUPERSEDED"
|
||||
},
|
||||
"want_rels": [
|
||||
{
|
||||
"type": "supersedes",
|
||||
"from": "m:b",
|
||||
"to": "m:a",
|
||||
"evidence_refs": [
|
||||
"ev-s"
|
||||
],
|
||||
"observed_at": "2026-10-10T17:53:36Z"
|
||||
}
|
||||
],
|
||||
"want_obs": [
|
||||
{
|
||||
"kind": "superseded",
|
||||
"old": "m:a",
|
||||
"new": "m:b",
|
||||
"evidence": "ev-s",
|
||||
"observed_at": "2026-10-10T17:53:36Z"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"op": "resolve",
|
||||
"entity": {
|
||||
"status": "SUPERSEDED"
|
||||
},
|
||||
"want": "SUPERSEDED"
|
||||
},
|
||||
{
|
||||
"op": "resolve",
|
||||
"entity": {
|
||||
"maturity": "LIVE_PROVEN",
|
||||
"evidence_refs": [
|
||||
"e"
|
||||
]
|
||||
},
|
||||
"want": "CURRENT"
|
||||
},
|
||||
{
|
||||
"op": "resolve",
|
||||
"entity": {
|
||||
"maturity": "PRESENT"
|
||||
},
|
||||
"want": "CONFLICTING"
|
||||
},
|
||||
{
|
||||
"op": "resolve",
|
||||
"entity": {},
|
||||
"want": "UNKNOWN"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -69,6 +69,113 @@ impl Default for StoreDoc {
|
||||
}
|
||||
}
|
||||
|
||||
// ── FFI surface (facade-1 burn-down, 2026-10-10) ─────────────────────────────
|
||||
// Doc-envelope law: one JSON arg in, {"ok","value"|"err"} out. now arrives
|
||||
// as an INPUT (no-clock law) — the caller passes the wall clock.
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::os::raw::c_char;
|
||||
|
||||
fn read_arg(ptr: *const c_char) -> Result<String, String> {
|
||||
if ptr.is_null() {
|
||||
return Err("null argument pointer".to_string());
|
||||
}
|
||||
unsafe { CStr::from_ptr(ptr) }
|
||||
.to_str()
|
||||
.map(|s| s.to_string())
|
||||
.map_err(|e| format!("argument is not valid UTF-8: {}", e))
|
||||
}
|
||||
|
||||
fn envelope(value: Result<serde_json::Value, String>) -> *mut c_char {
|
||||
let body = match value {
|
||||
Ok(v) => serde_json::json!({"ok": true, "value": v}),
|
||||
Err(e) => serde_json::json!({"ok": false, "err": e}),
|
||||
};
|
||||
CString::new(body.to_string())
|
||||
.map(|c| c.into_raw())
|
||||
.unwrap_or(std::ptr::null_mut())
|
||||
}
|
||||
|
||||
fn parse_arg(text: &str) -> Result<serde_json::Value, String> {
|
||||
serde_json::from_str(text).map_err(|e| format!("argument JSON parse failed: {}", e))
|
||||
}
|
||||
|
||||
fn get_str<'a>(v: &'a serde_json::Value, key: &str) -> Option<&'a str> {
|
||||
v.get(key).and_then(|x| x.as_str())
|
||||
}
|
||||
|
||||
/// ss_maturity_rank({"state": "..."}) -> int (spine ladder)
|
||||
#[no_mangle]
|
||||
pub extern "C" fn ss_maturity_rank(arg: *const c_char) -> *mut c_char {
|
||||
let result = read_arg(arg)
|
||||
.and_then(|t| parse_arg(&t))
|
||||
.and_then(|a| {
|
||||
let state = get_str(&a, "state").ok_or("arg.state required")?;
|
||||
Ok(serde_json::json!(maturity_rank(state)))
|
||||
});
|
||||
envelope(result)
|
||||
}
|
||||
|
||||
/// ss_promote({"doc": {...}, "id": "...", "state": "...", "evidence_ref": "...", "now": iso}) -> updated doc
|
||||
#[no_mangle]
|
||||
pub extern "C" fn ss_promote(arg: *const c_char) -> *mut c_char {
|
||||
let result = read_arg(arg)
|
||||
.and_then(|t| parse_arg(&t))
|
||||
.and_then(|a| {
|
||||
let mut doc = a.get("doc").cloned().ok_or("arg.doc required")?;
|
||||
let id = get_str(&a, "id").ok_or("arg.id required")?;
|
||||
let state = get_str(&a, "state").ok_or("arg.state required")?;
|
||||
let evidence = get_str(&a, "evidence_ref").ok_or("arg.evidence_ref required")?;
|
||||
let now = get_str(&a, "now").ok_or("arg.now required")?;
|
||||
match promote(&mut doc, id, state, evidence, now) {
|
||||
Ok(_) => Ok(doc),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
});
|
||||
envelope(result)
|
||||
}
|
||||
|
||||
/// ss_supersede({"doc": {...}, "new_id": "...", "old_id": "...", "evidence_ref": "...", "now": iso}) -> updated doc
|
||||
#[no_mangle]
|
||||
pub extern "C" fn ss_supersede(arg: *const c_char) -> *mut c_char {
|
||||
let result = read_arg(arg)
|
||||
.and_then(|t| parse_arg(&t))
|
||||
.and_then(|a| {
|
||||
let mut doc = a.get("doc").cloned().ok_or("arg.doc required")?;
|
||||
let new_id = get_str(&a, "new_id").ok_or("arg.new_id required")?;
|
||||
let old_id = get_str(&a, "old_id").ok_or("arg.old_id required")?;
|
||||
let evidence = get_str(&a, "evidence_ref").ok_or("arg.evidence_ref required")?;
|
||||
let now = get_str(&a, "now").ok_or("arg.now required")?;
|
||||
match supersede(&mut doc, new_id, old_id, evidence, now) {
|
||||
Ok(()) => Ok(doc),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
});
|
||||
envelope(result)
|
||||
}
|
||||
|
||||
/// ss_resolve_status({"entity": {...}}) -> string
|
||||
#[no_mangle]
|
||||
pub extern "C" fn ss_resolve_status(arg: *const c_char) -> *mut c_char {
|
||||
let result = read_arg(arg)
|
||||
.and_then(|t| parse_arg(&t))
|
||||
.and_then(|a| {
|
||||
let e = a.get("entity").cloned().ok_or("arg.entity required")?;
|
||||
Ok(serde_json::json!(resolve_status(&e)))
|
||||
});
|
||||
envelope(result)
|
||||
}
|
||||
|
||||
#[allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
// pinned: #[no_mangle] extern "C" — the Survivor loader ABI requires this exact safe-fn signature
|
||||
#[no_mangle]
|
||||
pub extern "C" fn ss_free_string(ptr: *mut c_char) {
|
||||
if !ptr.is_null() {
|
||||
unsafe {
|
||||
let _ = CString::from_raw(ptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -92,17 +199,29 @@ mod tests {
|
||||
// ── #2479 RUST batch 17: the state-machine kernels, oracle-parity port ─────
|
||||
|
||||
/// Maturity rank (Python MATURITY_RANK: DECLARED=1, PRESENT=2, VERIFIED=3, LIVE_PROVEN=4).
|
||||
/// Maturity rank — the SPINE ladder (structural_store.MATURITY_ORDER):
|
||||
/// DECLARED=0, PRESENT=1, WIRED=2, REACHABLE=3, EXERCISED=4, LIVE_PROVEN=5.
|
||||
/// Unknown states rank 0 (Python .get default); unknown REQUESTED states are
|
||||
/// rejected by the caller (Python raises ValueError — the FFI returns Err).
|
||||
/// (Previous port used a stale UNRUN/VERIFIED ladder — corrected 2026-10-10
|
||||
/// against the live oracle.)
|
||||
pub fn maturity_rank(state: &str) -> u32 {
|
||||
match state {
|
||||
"UNRUN" => 0,
|
||||
"DECLARED" => 1,
|
||||
"PRESENT" => 2,
|
||||
"VERIFIED" => 3,
|
||||
"LIVE_PROVEN" => 4,
|
||||
"DECLARED" => 0,
|
||||
"PRESENT" => 1,
|
||||
"WIRED" => 2,
|
||||
"REACHABLE" => 3,
|
||||
"EXERCISED" => 4,
|
||||
"LIVE_PROVEN" => 5,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// True iff the state is on the spine ladder (requestable).
|
||||
pub fn is_known_maturity(state: &str) -> bool {
|
||||
matches!(state, "DECLARED" | "PRESENT" | "WIRED" | "REACHABLE" | "EXERCISED" | "LIVE_PROVEN")
|
||||
}
|
||||
|
||||
/// Evidence-gated promotion. Demotion is never silent: recorded, not applied.
|
||||
/// Returns Ok(Some(updated maturity)) / Ok(demotion-rejected marker) / Err.
|
||||
pub fn promote(
|
||||
@@ -110,8 +229,9 @@ pub fn promote(
|
||||
id: &str,
|
||||
state: &str,
|
||||
evidence_ref: &str,
|
||||
now_iso: &str,
|
||||
) -> Result<Option<String>, String> {
|
||||
if maturity_rank(state) == 0 && state != "UNRUN" {
|
||||
if !is_known_maturity(state) {
|
||||
return Err(format!("unknown maturity state: {}", state));
|
||||
}
|
||||
if evidence_ref.is_empty() {
|
||||
@@ -139,7 +259,7 @@ pub fn promote(
|
||||
"entity": id,
|
||||
"requested": state,
|
||||
"current": current,
|
||||
"observed_at": now_iso(),
|
||||
"observed_at": now_iso,
|
||||
}));
|
||||
}
|
||||
return Ok(Some(current));
|
||||
@@ -160,7 +280,7 @@ pub fn promote(
|
||||
refs.sort();
|
||||
refs.dedup();
|
||||
e.insert("evidence_refs".into(), serde_json::json!(refs));
|
||||
e.insert("observed_at".into(), serde_json::json!(now_iso()));
|
||||
e.insert("observed_at".into(), serde_json::json!(now_iso));
|
||||
}
|
||||
Ok(Some(state.to_string()))
|
||||
}
|
||||
@@ -228,6 +348,7 @@ pub fn supersede(
|
||||
new_id: &str,
|
||||
old_id: &str,
|
||||
evidence_ref: &str,
|
||||
now_iso: &str,
|
||||
) -> Result<(), String> {
|
||||
if evidence_ref.is_empty() {
|
||||
return Err("supersession requires evidence".into());
|
||||
@@ -251,7 +372,7 @@ pub fn supersede(
|
||||
if let Some(obs) = doc.get_mut("observations").and_then(|o| o.as_array_mut()) {
|
||||
obs.push(serde_json::json!({
|
||||
"kind": "superseded", "old": old_id, "new": new_id,
|
||||
"evidence": evidence_ref, "observed_at": now_iso(),
|
||||
"evidence": evidence_ref, "observed_at": now_iso,
|
||||
}));
|
||||
}
|
||||
Ok(())
|
||||
@@ -291,10 +412,10 @@ mod branch_battery {
|
||||
fn promote_up_and_demotion_rejection() {
|
||||
let mut d = doc();
|
||||
add_ent(&mut d, "module:x", "DECLARED");
|
||||
let e = promote(&mut d, "module:x", "PRESENT", "ev-1").expect("promote ok");
|
||||
let e = promote(&mut d, "module:x", "PRESENT", "ev-1", "2026-10-10T00:00:00Z").expect("promote ok");
|
||||
assert_eq!(e.as_deref(), Some("PRESENT"));
|
||||
// demotion rejected + observed
|
||||
let e2 = promote(&mut d, "module:x", "DECLARED", "ev-2").expect("demotion handled");
|
||||
let e2 = promote(&mut d, "module:x", "DECLARED", "ev-2", "2026-10-10T00:00:00Z").expect("demotion handled");
|
||||
assert_eq!(e2.as_deref(), Some("PRESENT")); // unchanged
|
||||
let rejected = d["observations"]
|
||||
.as_array()
|
||||
@@ -308,8 +429,8 @@ mod branch_battery {
|
||||
fn promote_requires_evidence_and_known_state() {
|
||||
let mut d = doc();
|
||||
add_ent(&mut d, "module:x", "DECLARED");
|
||||
assert!(promote(&mut d, "module:x", "VERIFIED", "").is_err());
|
||||
assert!(promote(&mut d, "module:x", "BOGUS", "ev").is_err());
|
||||
assert!(promote(&mut d, "module:x", "WIRED", "", "2026-10-10T00:00:00Z").is_err());
|
||||
assert!(promote(&mut d, "module:x", "BOGUS", "ev", "2026-10-10T00:00:00Z").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -317,12 +438,12 @@ mod branch_battery {
|
||||
let mut d = doc();
|
||||
add_ent(&mut d, "module:old", "DECLARED");
|
||||
add_ent(&mut d, "module:new", "DECLARED");
|
||||
supersede(&mut d, "module:new", "module:old", "ev-1").expect("supersede ok");
|
||||
supersede(&mut d, "module:new", "module:old", "ev-1", "2026-10-10T00:00:00Z").expect("supersede ok");
|
||||
let old = find_entity(&d, "module:old").unwrap();
|
||||
assert_eq!(old["status"], "SUPERSEDED");
|
||||
assert_eq!(old["superseded_by"], "module:new");
|
||||
assert!(supersede(&mut d, "module:a", "module:missing", "ev").is_err());
|
||||
assert!(supersede(&mut d, "module:new", "module:old", "").is_err());
|
||||
assert!(supersede(&mut d, "module:a", "module:missing", "ev", "2026-10-10T00:00:00Z").is_err());
|
||||
assert!(supersede(&mut d, "module:new", "module:old", "", "2026-10-10T00:00:00Z").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -50,7 +50,6 @@
|
||||
"shard_manager",
|
||||
"structural_migration",
|
||||
"structural_model",
|
||||
"structural_store",
|
||||
"subconscious_pass",
|
||||
"system_registry",
|
||||
"task_gate",
|
||||
@@ -64,5 +63,19 @@
|
||||
"wait_guard",
|
||||
"wait_guard_corpus",
|
||||
"warm_neuron_store"
|
||||
],
|
||||
"burned": [
|
||||
{
|
||||
"module": "structural_store",
|
||||
"commit": "313f1c99",
|
||||
"evidence": "ladder corrected + FFI + delegation + canary 16/16 + 135 regression",
|
||||
"date": "2026-10-10"
|
||||
},
|
||||
{
|
||||
"module": "memory_selector/kernels",
|
||||
"commit": "cb4977fc",
|
||||
"evidence": "FFI ops + delegation + frozen 0 mismatches",
|
||||
"date": "2026-10-10"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -6,6 +6,66 @@
|
||||
"commit": "532fe649",
|
||||
"evidence": "frozen_oracle.json 22 rows + canary 26/26 + 40 shims + 78 slice + clippy 0",
|
||||
"date": "2026-10-10"
|
||||
},
|
||||
{
|
||||
"module": "capability_fit",
|
||||
"commit": "99698d16",
|
||||
"evidence": "frozen_evaluate_fit.json 18 rows + canary 24/24 + 85 regression incl. live consumer",
|
||||
"date": "2026-10-10"
|
||||
},
|
||||
{
|
||||
"module": "verification_layer",
|
||||
"commit": "b2ac8c85",
|
||||
"evidence": "fully delegated pre-exit (33/33 parity) + demo retired to tests + 12 regression",
|
||||
"date": "2026-10-10"
|
||||
},
|
||||
{
|
||||
"module": "drift_core",
|
||||
"commit": "fd718150",
|
||||
"evidence": "adversarial divergence FIXED pre-exit (NaN.min inversion + silent str default) + frozen 10 rows + 15/15 adversarial + 138 regression",
|
||||
"date": "2026-10-10"
|
||||
},
|
||||
{
|
||||
"module": "pins",
|
||||
"commit": "0a7d0b73",
|
||||
"evidence": "frozen real-shape oracle 5/5 + 207 regression",
|
||||
"date": "2026-10-10"
|
||||
},
|
||||
{
|
||||
"module": "behavior",
|
||||
"commit": "pending",
|
||||
"evidence": "no duplicated logic (math in habitmath.rs, SQL in Python) + parity_behavior 16/16",
|
||||
"date": "2026-10-10"
|
||||
},
|
||||
{
|
||||
"module": "spine",
|
||||
"commit": "44225afa",
|
||||
"evidence": "frozen full-doc oracle (327 entities) + canary 21/21 + 110 spine/shims + 327 lines deleted",
|
||||
"date": "2026-10-10"
|
||||
},
|
||||
{
|
||||
"module": "witness",
|
||||
"commit": "6a9eaddd",
|
||||
"evidence": "completion-gate + order divergences FIXED pre-exit + frozen 12 rows + 58 regression",
|
||||
"date": "2026-10-10"
|
||||
},
|
||||
{
|
||||
"module": "construction_decision/language_placement",
|
||||
"commit": "9d08c013",
|
||||
"evidence": "frozen 20 rows + canary 158/158 + 61 regression",
|
||||
"date": "2026-10-10"
|
||||
},
|
||||
{
|
||||
"module": "memory_store/retrieval-kernels",
|
||||
"commit": "3239080c",
|
||||
"evidence": "10 oracles deleted + frozen all-sections + canary 75/75 + shims 40/40",
|
||||
"date": "2026-10-10"
|
||||
},
|
||||
{
|
||||
"module": "capability_broker/score_card",
|
||||
"commit": "b953e021",
|
||||
"evidence": "frozen 19 rows exact-input keys + canary 24/24 + 40 shims",
|
||||
"date": "2026-10-10"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"construction contract FIRST (absolute-scaffolding law)",
|
||||
"parity + improvement note (defect fixed, measured gain, or honest parity-only)"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"parity_means": "Audited 2026-10-10: LLM-first reactive orchestrator, correctly placed.",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"parity_means": "PORT-QUEUE (audited 2026-10-10): estimate_tokens duplicates token_counting (should delegate \u2014 dedupe); capsule assembly needs Rust port + FFI + canary. Rust has capture/new only.",
|
||||
"status": "facade"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"parity_means": "Audited 2026-10-10: _compute_hash is a 3-line seam (JSON-encode + ep call, hash math in Rust, parity proven True); verify/append delegate. No duplicated logic \u2014 the seam stays by design.",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"status": "ported"
|
||||
"parity_means": "Strangler exit 2026-10-10: no Python-owned decision math (habitmath.rs authoritative, SQL stays Python); parity_behavior 16/16.",
|
||||
"status": "retired"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"parity_means": "PARITY DEBT (audited 2026-10-10): Rust select_for_job is a keyword heuristic, NOT parity with the score_card-driven Python (floor/escape/budget/shell-rule). score_card exited (b953e021); selection needs full port + FFI + canary.",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"status": "ported"
|
||||
"parity_means": "Strangler exit 2026-10-10 (99698d16): _py_evaluate_fit deleted, Rust authoritative, frozen oracle + 24/24 canary.",
|
||||
"status": "retired"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"parity_means": "PARITY DEBT (audited 2026-10-10): Rust has register + version helpers; Python is a file-backed registry (define/move/supersede/retire/active). Needs registry kernels + FFI + canary.",
|
||||
"status": "facade"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"parity_means": "Audited 2026-10-10: verify path proven 17/17; reframe+scan are PORT CANDIDATES for the Rust leg (no counterparts).",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"parity_means": "PORT-QUEUE (audited 2026-10-10): mode-dispatch branches are portable pure decision tables (mode/evidence/authority -> record); store bootstrap stays Python. Rust has requirements() only.",
|
||||
"status": "facade"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"parity_means": "Strangler exit 2026-10-10 (9d08c013): _py_language_placement deleted.",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"status": "facade"
|
||||
"parity_means": "HYBRID BY DESIGN (audited 2026-10-10): Python reactive intake/store/guards + Rust 16-edge phase machine + envelope (ci_validate/ci_transition FFI) + cgo membrane. Both sides authoritative at their boundary.",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"parity_means": "PARITY DEBT (audited 2026-10-10): Rust classify_mode is a heuristic with a different signature; Python is a 7-arg evidence-laden classifier. Needs full oracle port + FFI + canary.",
|
||||
"status": "facade"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"parity_means": "PARITY DEBT (audited 2026-10-10): Rust check_applicability is a stub (override-check only) vs the Python signal-group verdict machine; path/entity matchers exist. Needs full signal evaluation + FFI + loader + canary. Wiring+rewrite job.",
|
||||
"status": "facade"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"parity_means": "PARITY DEBT (audited 2026-10-10): Rust has 2 placeholder stubs (web-api/cli-tool, assert-true test); Python has 4 real patterns rev 1. Needs real content + FFI + canary.",
|
||||
"status": "facade"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"parity_means": "PARITY DEBT (audited 2026-10-10): Rust returns 3 passthrough fields; Python builds full projection (checkpoints/evidence/blocks/mini-doc/validate). Needs full port + FFI + canary.",
|
||||
"status": "facade"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"status": "ported"
|
||||
"parity_means": "Strangler exit 2026-10-10 (fd718150 oracles + verdict): compute_value/promotion kernels in Rust; promote_entry/fama/velocity/direction/pre_commit are SQLite-backed orchestration \u2014 stay Python by design.",
|
||||
"status": "retired"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"status": "facade"
|
||||
"parity_means": "PARTIAL (audited 2026-10-10): strengthToConf in Go with rounding improvement + replay gate; graph SQLite IO stays Python; edge/query kernels port-queue.",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"status": "facade"
|
||||
"parity_means": "Audited 2026-10-10: trace file IO stays Python reactive; price_for parity (None everywhere) proven; price map is a data seam for provider registry #29.",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"parity_means": "PARITY DEBT (audited 2026-10-10): Rust has compose-verify only; Python is region/component/amend/observe/check/drift lifecycle. Needs check/drift kernels + FFI + canary.",
|
||||
"status": "facade"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"status": "facade"
|
||||
"parity_means": "Wired 2026-10-10 (cb4977fc): score_of + lex_overlap FFI + delegation; orchestration stays Python.",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"construction contract FIRST (absolute-scaffolding law)",
|
||||
"parity + improvement note (defect fixed, measured gain, or honest parity-only)"
|
||||
],
|
||||
"parity_means": "Not yet ported. Parity means: kernel in its measured side, oracle-first truth battery, HARD CI gate, delegation wired, then retirement earned.",
|
||||
"status": "not_started"
|
||||
"parity_means": "Strangler exit 2026-10-10 (3239080c): 10 retrieval oracles deleted; recall/SQLite/cache orchestration stays Python reactive by design.",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"status": "ported"
|
||||
"parity_means": "Strangler exit 2026-10-10 (0a7d0b73): _py_pin_recall deleted, Rust authoritative.",
|
||||
"status": "retired"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"parity_means": "PARITY DEBT (audited 2026-10-10): Rust has register/get with 4 fields; Python has repo_identity/health/generations/resolve_cwd/migration + persistence. Needs full entry shape + kernels + FFI + canary.",
|
||||
"status": "facade"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"status": "ported"
|
||||
"parity_means": "Strangler exit 2026-10-10 (44225afa): 4 oracles deleted (327 lines), Rust authoritative.",
|
||||
"status": "retired"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"parity_means": "Audited 2026-10-10: FFI seam stays by design.",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "NOT parity: kernel exists but the Python module never delegates. Parity means the adapter delegates through the kernel (tier_manager pattern) with both paths pinned by tests.",
|
||||
"status": "facade"
|
||||
"parity_means": "Facade burned 2026-10-10 (313f1c99): spine-ladder kernel + FFI + delegation; 16 importers route through it.",
|
||||
"status": "ported"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Strangler exit 2026-10-10 (532fe649): Python oracle deleted, Rust authoritative, frozen oracle + 26/26 canary.",
|
||||
"parity_means": "Strangler exit 2026-10-10 (532fe649 kernels + verdict): estimate/compress in Rust; class surface (cache persistence, persona, assembly, status) stays Python reactive by design.",
|
||||
"status": "retired"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"oracle-first truth battery (Python truth generated FIRST)",
|
||||
"llvm-cov branch coverage + clippy 0"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"status": "ported"
|
||||
"parity_means": "Strangler exit 2026-10-10 (b2ac8c85): module is pure adapter, demo in tests/.",
|
||||
"status": "retired"
|
||||
}
|
||||
@@ -11,6 +11,6 @@
|
||||
"construction contract FIRST (absolute-scaffolding law)",
|
||||
"parity + improvement note (defect fixed, measured gain, or honest parity-only)"
|
||||
],
|
||||
"parity_means": "Parity claimed via oracle-first truth battery + HARD CI gate; deletion earned under the retirement law (parity + CI green + deployed one cycle).",
|
||||
"status": "ported"
|
||||
"parity_means": "Strangler exit 2026-10-10 (6a9eaddd): oracles deleted, Rust authoritative, 2 divergences fixed.",
|
||||
"status": "retired"
|
||||
}
|
||||
@@ -18,6 +18,7 @@ sys.path.insert(0, str(REPO / "src" / "rune"))
|
||||
|
||||
import microkernel as mk # noqa: E402
|
||||
import drift_core as dc # noqa: E402
|
||||
from rune import ms_loader # noqa: E402 — post-exit: the kernel IS the oracle
|
||||
|
||||
|
||||
# ── attack 1: session/capability isolation — stale plugin must not resolve ──
|
||||
@@ -50,25 +51,26 @@ class TestThresholdBypassAttacks:
|
||||
entry = {"wash_count": 19, "importance": 1.0,
|
||||
"rock_status": "washable",
|
||||
"last_accessed": "2026-10-08T00:00:00+00:00"}
|
||||
eligible, reason = dc._py_check_promotion_eligibility(
|
||||
eligible, reason = ms_loader.check_promotion_eligibility(
|
||||
entry, "2026-10-08T00:30:00+00:00")
|
||||
assert not eligible
|
||||
assert "threshold" in reason
|
||||
|
||||
def test_wash_count_type_confusion_rejected(self):
|
||||
"""Attack: wash_count as a string ('999') — the ORACLE behavior is
|
||||
a hard TypeError (log1p on a str), not a silent pass. PIN the
|
||||
crash: type confusion is loud, never silently accepted."""
|
||||
"""Attack: wash_count as a string ('999') — must be LOUD, never a
|
||||
silent pass. Post-exit the kernel raises RuntimeError (FFI envelope
|
||||
carrying the oracle's TypeError semantics); the Python oracle raised
|
||||
TypeError directly. PIN the crash either way."""
|
||||
entry = {"wash_count": "999", "importance": 1.0,
|
||||
"rock_status": "washable"}
|
||||
with pytest.raises(TypeError):
|
||||
dc._py_compute_value(entry, None, "2026-10-08T00:30:00+00:00")
|
||||
with pytest.raises((TypeError, RuntimeError)):
|
||||
ms_loader.compute_value(entry, None, "2026-10-08T00:30:00+00:00")
|
||||
|
||||
def test_negative_wash_count_cannot_advance(self):
|
||||
"""Attack: negative wash_count — must not be treated as high."""
|
||||
entry = {"wash_count": -5, "importance": 1.0,
|
||||
"rock_status": "washable"}
|
||||
eligible, _ = dc._py_check_promotion_eligibility(
|
||||
eligible, _ = ms_loader.check_promotion_eligibility(
|
||||
entry, "2026-10-08T00:30:00+00:00")
|
||||
assert not eligible
|
||||
|
||||
@@ -79,7 +81,7 @@ class TestStatusInversionAttacks:
|
||||
"""Attack: an entry already marked rock re-applies — must be
|
||||
refused ('already rock'), not double-promoted."""
|
||||
entry = {"wash_count": 99, "importance": 1.0, "rock_status": "rock"}
|
||||
eligible, reason = dc._py_check_promotion_eligibility(
|
||||
eligible, reason = ms_loader.check_promotion_eligibility(
|
||||
entry, "2026-10-08T00:30:00+00:00")
|
||||
assert not eligible
|
||||
assert reason == "already rock"
|
||||
@@ -88,7 +90,7 @@ class TestStatusInversionAttacks:
|
||||
"""Attack: garbage rock_status — must not grant privileged paths."""
|
||||
entry = {"wash_count": 3, "importance": 0.9,
|
||||
"rock_status": "GOD_MODE"}
|
||||
eligible, _ = dc._py_check_promotion_eligibility(
|
||||
eligible, _ = ms_loader.check_promotion_eligibility(
|
||||
entry, "2026-10-08T00:30:00+00:00")
|
||||
assert not eligible # below threshold regardless of status
|
||||
|
||||
@@ -101,7 +103,7 @@ class TestValueInflationAttacks:
|
||||
entry = {"wash_count": 1000, "importance": 1e9,
|
||||
"rock_status": "washable",
|
||||
"last_accessed": "2026-10-08T00:00:00+00:00"}
|
||||
value = dc._py_compute_value(entry, None, "2026-10-08T00:30:00+00:00")
|
||||
value = ms_loader.compute_value(entry, None, "2026-10-08T00:30:00+00:00")
|
||||
# importance weight 0.25 * 1e9 would exceed 1.0 — the oracle does
|
||||
# NOT clamp importance (parity: it uses the raw value). PIN the
|
||||
# behavior: if the oracle clamps, this test asserts the clamp;
|
||||
@@ -114,7 +116,7 @@ class TestValueInflationAttacks:
|
||||
entry = {"wash_count": 0, "importance": 0.5,
|
||||
"text": "the memory gates curator writes"}
|
||||
goals = ["the memory gates curator writes pipeline store recall"]
|
||||
value = dc._py_compute_value(entry, goals, "2026-10-08T00:30:00+00:00")
|
||||
value = ms_loader.compute_value(entry, goals, "2026-10-08T00:30:00+00:00")
|
||||
# the weighted sum with capped factors cannot exceed 1.0 unless
|
||||
# importance is inflated
|
||||
assert value <= 1.5 # generous bound; the capped path is ≤ 1.0
|
||||
|
||||
@@ -470,7 +470,7 @@ def test_mr_loader_score_and_fusion_through_cdylib():
|
||||
def test_memory_store_helpers_delegate_to_kernel():
|
||||
from rune import memory_store as ms
|
||||
|
||||
py = ms._py_map_reduce([{"id": i, "score": i} for i in range(1, 13)], 5)
|
||||
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"'
|
||||
@@ -486,7 +486,7 @@ def test_mr_loader_chunk_projection_and_memory_store_delegation():
|
||||
"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._py_project_chunk_rows(ranks, crows, 6)
|
||||
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)]
|
||||
@@ -523,7 +523,7 @@ def test_mr_loader_recall_kernel_via_stats_seam(tmp_path):
|
||||
"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._py_score_recall_rows(fusion, rows, dense, [], 5, 0.42,
|
||||
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",
|
||||
@@ -556,57 +556,36 @@ def test_mr_loader_delegation_publics_exercised(tmp_path):
|
||||
|
||||
|
||||
|
||||
def test_mr_loader_python_oracle_paths_exercised(monkeypatch):
|
||||
"""The _py_ oracle bodies count toward the changed-lines floor — the
|
||||
crate canary exercises the RUST path only; this battery drives the
|
||||
oracle path (fallback = load-bearing discipline)."""
|
||||
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)
|
||||
|
||||
def oracle(mode="dense-only"):
|
||||
dense, bm25 = ([[9, 0.85]], []) if mode == "dense-only" else (
|
||||
([], [[9, -8.0]]) if mode == "lexical-only"
|
||||
else ([[9, 0.85]], [[9, -8.0]]))
|
||||
fusion = ms._py_rank_fusion(dense, bm25)
|
||||
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}]
|
||||
return (ms._score_recall_rows(fusion, rows, dense, bm25, 4, 0.42,
|
||||
"2026-10-04T12:00:00+00:00"),
|
||||
fusion, rows, dense, bm25)
|
||||
|
||||
s_d, fusion_d, rows_d, dense_d, _ = oracle("dense-only")
|
||||
assert s_d and s_d[0]["mode"] == "dense-only"
|
||||
s_l, _, _, _, _ = oracle("lexical-only")
|
||||
assert s_l and s_l[0]["relevance"] > 4.5 # lexical offset band ~4.69 with blends
|
||||
s_h, _, _, _, _ = oracle("hybrid")
|
||||
assert s_h
|
||||
# abstention paths
|
||||
rows_f = [{"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}]
|
||||
assert ms._py_score_recall_rows(ms._py_rank_fusion([], []), rows_f, [], [], 4, 0.42,
|
||||
"2026-10-04T12:00:00+00:00") == []
|
||||
# timestamp exception path (malformed)
|
||||
rows_bad = [dict(rows_f[0], last_accessed="not-a-date")]
|
||||
out_bad = ms._score_recall_rows(ms._py_rank_fusion([[9, 0.9]], []), rows_bad,
|
||||
[[9, 0.9]], [], 4, 0.42,
|
||||
"2026-10-04T12:00:00+00:00")
|
||||
assert out_bad[0]["relevance"] > 0
|
||||
# gap path: dense pair with big gap and mid band
|
||||
dense_gap = [[9, 0.72], [8, 0.60]]
|
||||
rows_g = rows_f + [dict(rows_f[0], id=8)]
|
||||
out_g = ms._score_recall_rows(ms._py_rank_fusion(dense_gap, []), rows_g,
|
||||
dense_gap, [], 4, 0.42,
|
||||
"2026-10-04T12:00:00+00:00")
|
||||
assert out_g[0]["id"] == 9
|
||||
# fusion with ties and the hybrid accumulation path
|
||||
assert ms._rank_fusion([[1, 0.5], [2, 0.5]], [[1, -5.0], [3, -6.0]])["ranks"]
|
||||
|
||||
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)."""
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Retired inline demo (verification_layer.test_verification, strangler exit #3)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
|
||||
|
||||
|
||||
def test_verification_layer_demo_regression():
|
||||
"""The inline demo, retired into a regression test."""
|
||||
from rune import verification_layer as vl
|
||||
|
||||
vr = vl.verify({"exit_code": 0}, "exit_code")
|
||||
assert vr.passed
|
||||
vr = vl.verify({"exit_code": 1}, "exit_code")
|
||||
assert not vr.passed
|
||||
vr = vl.verify({"tests_passed": 10, "tests_failed": 0, "tests_total": 10}, "unit_test")
|
||||
assert vr.passed
|
||||
vr = vl.verify({}, "nonexistent_verifier")
|
||||
assert not vr.passed and vr.escalation_reason == "unknown_verifier"
|
||||
Reference in new issue
Block a user