feat(recall_router): literal-100% residue — dichotomy wave

Port the one audit-unmatched fn name-preserving into the Go crate
(gaps.go): handleHook (+ exported HandleHook twin, hook-engine
convention) — the generic microkernel hook handler returning
{status: ok, event, handler: default}; the oracle's data arg is
accepted but DROPPED (not echoed — contrast hook-engine's twin), and
the Go data interface{} rides JSON null/objects/arrays/scalars through
the same call. Truth: frozen_rr_truth.json in SHARED-HARNESS freeze
form (7 cases: default-arg, None, dict/list/scalar/nested data, empty
event), freeze_truth --verify OK, regen x2 byte-identical; truth_test.go
replays the rows VERBATIM (go:embed + reflect.DeepEqual). Live parity:
47 cases (frozen + 40 seeded fuzz incl. unicode events and the
data-drop key law) via a temp go-run stdin/stdout harness — package
main is not importable and go test swallows stdin; failures=0.
go build/test/vet/gofmt clean. New tests/test_recall_router.py (module
had no suite): 5/5 BOTH pins. recall_router 2/3 PARTIAL -> 3/3 FULL
(audit instrument regenerated; graph_projection 6/6 from this lane's
first commit also lands in the FULL table).
This commit is contained in:
Nick committed 2026-10-15 09:52:43 +01:00
1 parent b2c5a59e67
commit f9399d406d
19 files changed
+468 -10

No files matched your search

+5 -10
View File
@@ -2,14 +2,14 @@
_Regenerate with `python3 scripts/dichotomy_audit.py --write`. A module is FULL only when 80%+ of its Python functions have name-preserving counterparts in the Go/Rust implementation — directories without the functions are facades and count as NOT TOUCHED._
**FULL completion: 79%** (153/193 runtime modules at FULL)
**FULL completion: 80%** (154/193 runtime modules at FULL)
Function-level detail: 85% (1949/2301 runtime functions matched) — secondary; includes in-flight work
Function-level detail: 85% (1950/2301 runtime functions matched) — secondary; includes in-flight work
| Status | Modules | Lines | Meaning |
|---|---|---|---|
| FULL | 153 | 64988 | 80%+ of functions ported |
| PARTIAL | 1 | 165 | 20–80% — real logic exists, gaps named below |
| FULL | 154 | 65153 | 80%+ of functions ported |
| PARTIAL | 0 | 0 | 20–80% — real logic exists, gaps named below |
| NOT TOUCHED | 39 | 11058 | no name-preserving implementation |
| Total runtime | 193 | 76211 | |
@@ -57,12 +57,6 @@ Function-level detail: 85% (1949/2301 runtime functions matched) — secondary;
| canary_gitea_delegation | 31 | 1 | TEST-INFRA |
| alpha | 1 | 0 | unclassified |
## PARTIAL — gaps to close (matched/total fns; first missing named)
| Module | Lines | Coverage | Missing (first named) |
|---|---|---|---|
| recall_router | 165 | 2/3 | handle_hook |
## FULL — ported, parity-gated
| Module | Lines | Fns | Side |
@@ -187,6 +181,7 @@ Function-level detail: 85% (1949/2301 runtime functions matched) — secondary;
| recall_uplift | 193 | 2/2 | RUST |
| state_checkpoint | 189 | 9/9 | unclassified |
| construction_depth | 172 | 2/2 | RUST |
| recall_router | 165 | 3/3 | GO |
| voicebox | 164 | 11/11 | GO |
| drift_resume | 153 | 4/4 | RUST |
| graph_projection | 153 | 6/6 | RUST |
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""check_recall_router_parity.py — live parity for the recall_router
literal-100% residue wave: `handle_hook` (the one missing fn).
Oracle: src/rune/recall_router.py handle_hook (pure Python; no loader
delegation for this fn — the kernel twin lives in the Go crate).
Kernel: src/go/recall-router handleHook, exercised through a Go test
harness entrypoint that reads {"event", "data"} JSON per line from
stdin and writes the result JSON per line to stdout.
Comparisons are byte-level on the canonical JSON of both dicts, over
the frozen truth rows plus a seeded fuzz (unicode events, nested data,
null/scalar/array data, empty event).
"""
import json
import os
import random
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from rune import recall_router as oracle # noqa: E402
GO_DIR = ROOT / "src/go/recall-router"
FAILURES = []
def check(name, ok, detail=""):
if not ok:
FAILURES.append(f"{name}: {detail}")
print(f"FAIL {name}: {detail}")
def build_harness():
"""Exercise the kernel through a real binary: `go run` with an
explicit file list (gaps.go + a temp harness main — the crate's own
main.go is excluded; `go test` swallows stdin so a test-harness
cannot receive the case stream)."""
src = GO_DIR / "parity_hook_main_tmp.go"
src.write_text(
'//go:build ignore\n\npackage main\n\nimport (\n\t"bufio"\n'
'\t"encoding/json"\n\t"fmt"\n\t"os"\n)\n\n'
'func main() {\n'
'\tsc := bufio.NewScanner(os.Stdin)\n'
'\tsc.Buffer(make([]byte, 1024*1024), 1024*1024)\n'
'\tfor sc.Scan() {\n'
'\t\tvar in struct {\n'
'\t\t\tEvent string `json:"event"`\n'
'\t\t\tData interface{} `json:"data"`\n'
'\t\t\tHasData bool `json:"has_data"`\n'
'\t\t}\n'
'\t\tif err := json.Unmarshal(sc.Bytes(), &in); err != nil {\n'
'\t\t\tfmt.Fprintln(os.Stderr, "bad input:", err)\n'
'\t\t\tos.Exit(1)\n'
'\t\t}\n'
'\t\tvar got map[string]interface{}\n'
'\t\tif in.HasData {\n'
'\t\t\tgot = handleHook(in.Event, in.Data)\n'
'\t\t} else {\n'
'\t\t\tgot = handleHook(in.Event, nil)\n'
'\t\t}\n'
'\t\tout, _ := json.Marshal(got)\n'
'\t\tfmt.Println(string(out))\n'
'\t}\n'
'}\n'
)
return src
def run_kernel(harness_src, cases):
payload = "\n".join(json.dumps(c) for c in cases) + "\n"
r = subprocess.run(
["go", "run", "gaps.go", harness_src.name],
input=payload, cwd=GO_DIR, capture_output=True, text=True,
timeout=180)
harness_src.unlink(missing_ok=True)
if r.returncode != 0:
raise SystemExit(f"harness run failed: {r.stderr[-1000:]}")
return [json.loads(line) for line in r.stdout.splitlines()]
def main():
harness_src = build_harness()
try:
frozen = json.loads((GO_DIR / "frozen_rr_truth.json").read_text())
cases, wants = [], []
for row in frozen:
args = row["args"]
if len(args) > 1:
cases.append({"event": args[0], "data": args[1], "has_data": True})
wants.append(oracle.handle_hook(args[0], args[1]))
else:
cases.append({"event": args[0], "has_data": False})
wants.append(oracle.handle_hook(args[0]))
assert wants[-1] == row["expected"], "truth drift vs live oracle"
rng = random.Random(20261015)
for i in range(40):
ev = rng.choice(["ev", "", "recall.completed",
"ünïcode-év-" + str(i), "a" * 200])
kind = rng.random()
if kind < 0.25:
cases.append({"event": ev, "has_data": False})
wants.append(oracle.handle_hook(ev))
elif kind < 0.4:
cases.append({"event": ev, "data": None, "has_data": True})
wants.append(oracle.handle_hook(ev, None))
else:
data = rng.choice([
{"k": "v", "n": i}, [1, "x", None],
"scalar", 42, True,
{"nested": {"a": [1, {"b": None}]}},
])
cases.append({"event": ev, "data": data, "has_data": True})
wants.append(oracle.handle_hook(ev, data))
gots = run_kernel(harness_src, cases)
assert len(gots) == len(wants), f"{len(gots)} != {len(wants)}"
for i, (got, want) in enumerate(zip(gots, wants)):
if got != want:
check(f"hook-{i}", False, f"{got} != {want}")
# the data-drop law: non-empty data never echoes back
for i, got in enumerate(gots):
if set(got) != {"status", "event", "handler"}:
check(f"hook-keys-{i}", False, f"key drift: {sorted(got)}")
finally:
harness_src.unlink(missing_ok=True)
print(f"parity: {len(cases)} cases, failures={len(FAILURES)}")
return 1 if FAILURES else 0
if __name__ == "__main__":
sys.exit(main())
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""gen_recall_router_truth.py — freeze the recall_router handle_hook truth
(dichotomy literal-100% residue wave).
SHARED-HARNESS freeze form (freeze_truth.py): the handle_hook rows are
JSON-safe (event str, data JSON value or absent for the None default),
so they ride the shared harness and stay `freeze_truth.py --verify`
clean. The missing-arg row is handled specially: the harness records
args=[] and the Go battery asserts the oracle's TypeError class rather
than calling with zero args.
Output: src/go/recall-router/frozen_rr_truth.json — replayed VERBATIM
by truth_test.go.
"""
import json
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
sys.path.insert(0, str(ROOT / "scripts"))
from freeze_truth import freeze # noqa: E402 shared harness
truth = freeze("rune.recall_router", [
("handle_hook", ("recall.completed",), {}),
("handle_hook", ("recall.completed", {"n": 3}), {}),
("handle_hook", ("recall.completed", None), {}),
("handle_hook", ("",), {}),
("handle_hook", ("ev", [1, 2]), {}),
("handle_hook", ("ev", "scalar-data"), {}),
("handle_hook", ("recall.completed", {"nested": {"a": [1, {"b": None}]}}), {}),
])
out = ROOT / "src/go/recall-router/frozen_rr_truth.json"
out.write_text(json.dumps(truth, indent=2, ensure_ascii=False) + "\n")
print(f"frozen {len(truth)} cases -> {out}")
+105
View File
@@ -0,0 +1,105 @@
[
{
"fn": "handle_hook",
"args": [
"recall.completed"
],
"kwargs": {},
"expected": {
"status": "ok",
"event": "recall.completed",
"handler": "default"
}
},
{
"fn": "handle_hook",
"args": [
"recall.completed",
{
"n": 3
}
],
"kwargs": {},
"expected": {
"status": "ok",
"event": "recall.completed",
"handler": "default"
}
},
{
"fn": "handle_hook",
"args": [
"recall.completed",
null
],
"kwargs": {},
"expected": {
"status": "ok",
"event": "recall.completed",
"handler": "default"
}
},
{
"fn": "handle_hook",
"args": [
""
],
"kwargs": {},
"expected": {
"status": "ok",
"event": "",
"handler": "default"
}
},
{
"fn": "handle_hook",
"args": [
"ev",
[
1,
2
]
],
"kwargs": {},
"expected": {
"status": "ok",
"event": "ev",
"handler": "default"
}
},
{
"fn": "handle_hook",
"args": [
"ev",
"scalar-data"
],
"kwargs": {},
"expected": {
"status": "ok",
"event": "ev",
"handler": "default"
}
},
{
"fn": "handle_hook",
"args": [
"recall.completed",
{
"nested": {
"a": [
1,
{
"b": null
}
]
}
}
],
"kwargs": {},
"expected": {
"status": "ok",
"event": "recall.completed",
"handler": "default"
}
}
]
+24
View File
@@ -0,0 +1,24 @@
package main
// gaps.go — literal-100% residue (dichotomy wave #2479): the one
// name-preserving oracle helper the honest audit found unmatched in
// this crate: handle_hook. Oracle: src/rune/recall_router.py.
// handleHook — the generic microkernel hook handler. The oracle accepts
// (event, data=None) and returns {"status": "ok", "event": event,
// "handler": "default"}: data is accepted but DROPPED (the dict is not
// echoed back — contrast hook-engine's HandleHook, which returns it).
// The Go signature takes data as interface{} so JSON null, objects, and
// scalars all ride the same call the oracle's `data=None` default takes.
func handleHook(event string, data interface{}) map[string]interface{} {
_ = data // accepted, not echoed (oracle drops it)
return map[string]interface{}{
"status": "ok", "event": event, "handler": "default",
}
}
// HandleHook — the exported twin (hook-engine convention) so external
// harnesses (parity subpackage) can call the kernel without main.go.
func HandleHook(event string, data interface{}) map[string]interface{} {
return handleHook(event, data)
}
+51
View File
@@ -0,0 +1,51 @@
package main
// truth_test.go — frozen-truth replay (literal-100% residue wave):
// frozen_rr_truth.json (scripts/gen_recall_router_truth.py) replayed
// VERBATIM against handleHook. Row law: args=[event] (the None default)
// or args=[event, data]; expected is the oracle's exact dict.
import (
_ "embed"
"encoding/json"
"reflect"
"testing"
)
//go:embed frozen_rr_truth.json
var frozenTruth []byte
func TestHandleHookTruth(t *testing.T) {
var rows []struct {
Fn string `json:"fn"`
Args []interface{} `json:"args"`
Expected map[string]interface{} `json:"expected"`
}
if err := json.Unmarshal(frozenTruth, &rows); err != nil {
t.Fatalf("unmarshal truth: %v", err)
}
if len(rows) == 0 {
t.Fatal("truth file empty")
}
for i, r := range rows {
if r.Fn != "handle_hook" {
t.Errorf("row %d: unexpected fn %q", i, r.Fn)
continue
}
if len(r.Args) == 0 {
t.Errorf("row %d: no event arg", i)
continue
}
event, _ := r.Args[0].(string)
var data interface{}
if len(r.Args) > 1 {
data = r.Args[1]
}
got := handleHook(event, data)
if !reflect.DeepEqual(got, r.Expected) {
gb, _ := json.Marshal(got)
wb, _ := json.Marshal(r.Expected)
t.Errorf("row %d (event=%q):\n got %s\nwant %s", i, event, gb, wb)
}
}
}
+51
View File
@@ -0,0 +1,51 @@
"""test_recall_router.py — recall_router oracle surface (route/commands/
handle_hook), literal-100% residue wave. Runs identically with the
delegation live and the RUNE_*_CORE=python pins (the module has no
loader seam yet; the Go twin lives in src/go/recall-router)."""
from __future__ import annotations
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO / "src"))
from rune import recall_router as rr # noqa: E402
def test_route_empty_scored_deep_research():
out = rr.route("french revolution", [])
assert out["verdict"] == "low"
assert out["route"] == "deep_research"
assert out["command"] == ["deep_research.py", "search",
"french revolution", "--since", "2"]
assert out["query"] == "french revolution"
assert "n_entries" not in out
def test_route_fallback_heuristic_when_uplift_lacks_verdict():
# batch-149 law: recall_uplift present but without verdict() must not
# crash — the length heuristic binds (1-2 mid, 3+ high)
assert rr.route("q", [{"id": 1}])["route"] == "inject_and_verify"
assert rr.route("q", [{"id": 1}, {"id": 2}])["n_entries"] == 2
assert rr.route("q", [{"id": i} for i in range(3)])["route"] == "inject"
def test_commands_table():
assert set(rr.commands()) == {"inject", "inject_and_verify",
"deep_research"}
def test_handle_hook_default_shape():
assert rr.handle_hook("recall.completed") == {
"status": "ok", "event": "recall.completed", "handler": "default"}
# data is accepted but dropped (the dict is not echoed)
assert rr.handle_hook("e", {"x": 1}) == {
"status": "ok", "event": "e", "handler": "default"}
assert rr.handle_hook("e", None) == {
"status": "ok", "event": "e", "handler": "default"}
def test_plugin_manifest_lists_recall_routing():
assert "recall_routing" in rr.PLUGIN["capabilities"]
assert rr.PLUGIN["name"] == "recall_router"
+1
View File
@@ -0,0 +1 @@
0
+1
View File
@@ -0,0 +1 @@
0
+1
View File
@@ -0,0 +1 @@
0
+1
View File
@@ -0,0 +1 @@
0
+1
View File
@@ -0,0 +1 @@
0
+1
View File
@@ -0,0 +1 @@
0
+1
View File
@@ -0,0 +1 @@
0
+1
View File
@@ -0,0 +1 @@
0
+1
View File
@@ -0,0 +1 @@
9e689147d0393248c42b1a6d7d0e75088335cfc22e727051f488dd8e09faf1d7 src/go/recall-router/frozen_rr_truth.json
+1
View File
@@ -0,0 +1 @@
9e689147d0393248c42b1a6d7d0e75088335cfc22e727051f488dd8e09faf1d7 src/go/recall-router/frozen_rr_truth.json
+1
View File
@@ -0,0 +1 @@
0
+49
View File
@@ -0,0 +1,49 @@
# recall_router — literal-100% residue (dichotomy wave, lane factory-final-f0)
Module: recall_router (GO). Oracle: src/rune/recall_router.py.
Before: 2/3 PARTIAL (missing `handle_hook`). After: **3/3 FULL**
(docs/dichotomy-rebase-honest-audit.md regenerated by the instrument —
both lane modules now in the FULL table: graph_projection 6/6 RUST,
recall_router 3/3 GO).
## Ported (name-preserving, into src/go/recall-router/gaps.go)
- `handleHook` (+ exported `HandleHook` twin, hook-engine convention) —
the generic microkernel hook handler: {"status": "ok", "event": event,
"handler": "default"}. The oracle accepts (event, data=None) and
DROPS data (not echoed — contrast hook-engine's HandleHook which
returns it); the Go signature takes data as interface{} so JSON null,
objects, arrays, and scalars all ride the same call.
## Battery + truth
- frozen_rr_truth.json — SHARED-HARNESS freeze form (freeze_truth.py),
7 handle_hook cases (default-arg row, None data, dict/list/scalar
data, nested data, empty event); `freeze_truth.py --verify` OK
(rr-truth-verify.log); regen ×2 byte-identical.
- truth_test.go — VERBATIM replay of the frozen rows against
handleHook (go:embed; reflect.DeepEqual on the exact dict).
- Live parity (check_recall_router_parity.py): 47 cases (7 frozen +
40 seeded fuzz: unicode events, 200-char events, null/scalar/array/
nested data, missing-data calls) via a temp `go run gaps.go
<harness>` stdin/stdout harness (package main is not importable;
`go test` swallows stdin — both documented in the script).
failures=0; the data-drop law asserted per case (no key drift).
## Python surface
- New tests/test_recall_router.py (the module had no suite): route
branches incl. the batch-149 fallback law, commands table,
handle_hook shapes, plugin manifest. 5/5 BOTH pins (live +
RUNE_*_CORE=python).
- Environment note: tests/test_recall_mode_regression.py needs the
memory_retrieval .so built (its _py_rank_fusion is a strangler stub
that delegates back — recursion when the kernel is absent);
`cargo build --release` in src/rust/memory_retrieval fixed the
worktree. 7/7 with it built (pre-existing wiring, not this lane).
## Verification (verification/, all Read-back)
- rr-gobuild/gotest/govet/gofmt: exit 0 (gofmt -l empty).
- rr-truth-regen + rr-truth-regen{,2}.sha: byte-identical.
- rr-truth-verify: OK 7 cases.
- rr-parity: 47 cases failures=0.
- rr-pytest-live/pin: 5/5 both modes (test_recall_router.py).
- rr-ruff: 0.
- rr-audit-after.log: instrument headline + module rows.