seam: implement decorated-fn boundary auto-emit; prove on clone
Will waived diff review -> build it for real. Add engram_boundary_beat() to the runtime (afferent counter++ + engram_chrono_tick + engram_strengthen(self-anchor) + dharma_emit) and two act-stats counters (aff_boundary_ops, dharma_emits). codegen cg_fn injects ONE engram_boundary_beat(op) at the entry of every @manager/@accessor fn (fn_has_decorator, so it fires under @route @manager too) — a decorated op self-reports with ZERO hand-written instrumentation. Rebuilt elc self-host + the cognition engram in the worktree; ran it as the clone daemon on :8900. Proof (/api/boundary-proof, @manager, empty body, 5x): aff_boundary_ops 0->5, dharma_emits 0->5, self activation_count 1510->1513, chrono stamp advanced. Brought in feat/cognitive-architecture engram runtime+server for the build. strengthen = activation bump (not content/edge write) -> identity protection intact. Live :8742 untouched; no push, no cutover.
This commit is contained in:
+525
-32
@@ -117,6 +117,17 @@ fn route_text_health(method: String, path: String, body: String) -> String {
|
||||
// save/load with no "path" hit engram_save(""). Rewritten to the
|
||||
// `let x = if cond { a } else { b }` expression form (the pattern the newer
|
||||
// routes route_emit_ise/route_capture_knowledge already use correctly).
|
||||
// store_on — ENGRAM_STORE flag (tiered paged store as the durable owner). Matches
|
||||
// engram_store_enabled() in el_runtime.c EXACTLY (1 / on / true). Default off →
|
||||
// every persistence path below is byte-for-byte the historical snapshot behavior.
|
||||
fn store_on() -> Bool {
|
||||
let v: String = env("ENGRAM_STORE")
|
||||
if str_eq(v, "1") { return true }
|
||||
if str_eq(v, "on") { return true }
|
||||
if str_eq(v, "true") { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
// persist_canonical — save the canonical snapshot after a durable write.
|
||||
//
|
||||
// WHY (2026-07-22 self-review): the 2026-07-21 fix correctly stopped READ
|
||||
@@ -131,8 +142,16 @@ fn route_text_health(method: String, path: String, body: String) -> String {
|
||||
// tolerant, ~2/min — snapshotting the whole store per heartbeat is waste;
|
||||
// any durable write that follows persists the pruning too).
|
||||
fn persist_canonical() -> Int {
|
||||
// ENGRAM_STORE: the paged store is the durable owner — a checkpoint flushes
|
||||
// dirty pages behind a WAL-durable record (durable the moment the WAL fsyncs).
|
||||
// This is the fix for the "restart reverted to a 17h-old snapshot" data loss:
|
||||
// durable writes no longer depend on a full snapshot.json rewrite. Returns 1
|
||||
// on a successful checkpoint, 0 otherwise. Flag-off: unchanged (writes JSON).
|
||||
if store_on() {
|
||||
return engram_store_checkpoint()
|
||||
}
|
||||
let dir_raw: String = env("ENGRAM_DATA_DIR")
|
||||
let dir: String = if str_eq(dir_raw, "") { "/tmp/engram" } else { dir_raw }
|
||||
let dir: String = engram_resolve_data_dir()
|
||||
// (2026-08-10 self-review) This returned a hardcoded 1, which made every
|
||||
// caller's `let saved: Int = persist_canonical()` a dead variable — six
|
||||
// durable write paths each believed they had confirmation of a successful
|
||||
@@ -140,6 +159,82 @@ fn persist_canonical() -> Int {
|
||||
return engram_save(dir + "/snapshot.json")
|
||||
}
|
||||
|
||||
// ── WAL persistence (design doc §§3-14; gated behind ENGRAM_WAL=on) ──────────
|
||||
// Default OFF → every persist path below is byte-identical to the historical
|
||||
// per-write full-snapshot behavior. When ON, structural mutations append O(1)
|
||||
// WAL records instead of rewriting the whole graph, with threshold compaction.
|
||||
fn wal_on() -> Bool {
|
||||
str_eq(env("ENGRAM_WAL"), "on")
|
||||
}
|
||||
|
||||
// autoconnect_on — ENGRAM_AUTOCONNECT. Will's rule: "we shouldn't be inserting
|
||||
// orphaned nodes." When ON, every content-node insert forms >=1 semantic-similar
|
||||
// edge (kNN over embeddings) so no content node enters the graph edgeless.
|
||||
// Default OFF -> byte-identical to prior behavior (node created, no auto edges).
|
||||
fn autoconnect_on() -> Bool {
|
||||
let v: String = env("ENGRAM_AUTOCONNECT")
|
||||
if str_eq(v, "1") { return true }
|
||||
if str_eq(v, "on") { return true }
|
||||
if str_eq(v, "true") { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
// ise_offgraph_on — ENGRAM_ISE_OFFGRAPH. The census showed ~8k of the ~8.9k
|
||||
// orphans are InternalStateEvent telemetry (heartbeat/curiosity_scan/session-
|
||||
// start), 100% edgeless by design. When ON, that telemetry is routed to a
|
||||
// separate state-event log tier instead of the node graph. Default OFF -> ISEs
|
||||
// remain graph nodes exactly as before (with 48h prune).
|
||||
fn ise_offgraph_on() -> Bool {
|
||||
let v: String = env("ENGRAM_ISE_OFFGRAPH")
|
||||
if str_eq(v, "1") { return true }
|
||||
if str_eq(v, "on") { return true }
|
||||
if str_eq(v, "true") { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
// Persist a single-node mutation (create / content-evolve / strengthen).
|
||||
fn persist_node(id: String) -> Int {
|
||||
if wal_on() {
|
||||
let d: String = engram_resolve_data_dir()
|
||||
let a: Int = engram_wal_node_put(d, id)
|
||||
let c: Int = engram_wal_maybe_compact(d)
|
||||
return a
|
||||
}
|
||||
return persist_canonical()
|
||||
}
|
||||
|
||||
// Persist edges appended at index >= start (covers single-edge and batch).
|
||||
fn persist_edges_since(start: Int) -> Int {
|
||||
if wal_on() {
|
||||
let d: String = engram_resolve_data_dir()
|
||||
let a: Int = engram_wal_edges_since(d, start)
|
||||
let c: Int = engram_wal_maybe_compact(d)
|
||||
return a
|
||||
}
|
||||
return persist_canonical()
|
||||
}
|
||||
|
||||
// Persist a Hebbian consolidation batch as ONE WAL record (single fsync, §5-B).
|
||||
fn persist_hebb_batch(start: Int) -> Int {
|
||||
if wal_on() {
|
||||
let d: String = engram_resolve_data_dir()
|
||||
let a: Int = engram_wal_hebb_batch(d, start)
|
||||
let c: Int = engram_wal_maybe_compact(d)
|
||||
return a
|
||||
}
|
||||
return persist_canonical()
|
||||
}
|
||||
|
||||
// Bulk mutation (embedding backfill, load-merge): write a fresh compaction base
|
||||
// so the many-node change is durable in one atomic snapshot; WAL is truncated.
|
||||
fn persist_bulk() -> Int {
|
||||
if wal_on() {
|
||||
let d: String = engram_resolve_data_dir()
|
||||
return engram_wal_compact(d)
|
||||
}
|
||||
return persist_canonical()
|
||||
}
|
||||
|
||||
// INCOMPLETE-ROUTE FIX (2026-07-24 self-review): this route silently dropped
|
||||
// label, importance, tier, and tags — engram_node() defaults label to content
|
||||
// and importance to 0.5, so every node created over HTTP lost its metadata.
|
||||
@@ -181,8 +276,17 @@ fn route_create_node(method: String, path: String, body: String) -> String {
|
||||
salience, importance, confidence,
|
||||
tier, tags
|
||||
)
|
||||
let saved: Int = persist_canonical()
|
||||
"{\"id\":\"" + id + "\",\"content\":\"" + content + "\",\"node_type\":\"" + node_type + "\"}"
|
||||
let saved: Int = persist_node(id)
|
||||
// ORPHAN PREVENTION (ENGRAM_AUTOCONNECT): connect the fresh node to its
|
||||
// nearest embedded neighbors so it never enters the graph edgeless.
|
||||
let connected: Int = if autoconnect_on() {
|
||||
let ec0: Int = engram_edge_count()
|
||||
let ac: String = engram_autoconnect_node(id, 3, 25)
|
||||
let added: Int = engram_edge_count() - ec0
|
||||
if added > 0 { let sv2: Int = persist_edges_since(ec0) }
|
||||
added
|
||||
} else { 0 }
|
||||
"{\"id\":\"" + id + "\",\"content\":\"" + content + "\",\"node_type\":\"" + node_type + "\",\"connected\":" + int_to_str(connected) + "}"
|
||||
}
|
||||
|
||||
fn route_get_node(method: String, path: String, body: String) -> String {
|
||||
@@ -191,6 +295,16 @@ fn route_get_node(method: String, path: String, body: String) -> String {
|
||||
return engram_get_node_json(id)
|
||||
}
|
||||
|
||||
// route_get_node_singular — GET /api/node/<id>. Singular alias for node-by-id
|
||||
// fetch. The plural /api/nodes/<id> already resolves; the viz's "see full node
|
||||
// value on click" and other clients call the SINGULAR form, which had no route
|
||||
// and 404'd for every id. Same handler, singular prefix. Read-only.
|
||||
fn route_get_node_singular(method: String, path: String, body: String) -> String {
|
||||
let id: String = extract_id(path, "/api/node/")
|
||||
if str_eq(id, "") { return err_json("missing id") }
|
||||
return engram_get_node_json(id)
|
||||
}
|
||||
|
||||
fn route_scan_nodes(method: String, path: String, body: String) -> String {
|
||||
let limit: Int = query_int(path, "limit", 50)
|
||||
let offset: Int = query_int(path, "offset", 0)
|
||||
@@ -208,7 +322,7 @@ fn route_scan_nodes(method: String, path: String, body: String) -> String {
|
||||
// clobbered the good snapshot. Read routes must never write the canonical path.)
|
||||
fn route_scan_edges(method: String, path: String, body: String) -> String {
|
||||
let dir_raw: String = env("ENGRAM_DATA_DIR")
|
||||
let dir: String = if str_eq(dir_raw, "") { "/tmp/engram" } else { dir_raw }
|
||||
let dir: String = engram_resolve_data_dir()
|
||||
let snap_path: String = dir + "/.scan-export.json"
|
||||
engram_save(snap_path)
|
||||
let snap: String = fs_read(snap_path)
|
||||
@@ -222,6 +336,15 @@ fn route_scan_edges(method: String, path: String, body: String) -> String {
|
||||
}
|
||||
|
||||
fn route_search(method: String, path: String, body: String) -> String {
|
||||
let q: String = if str_eq(method, "GET") { query_param(path, "q") } else { json_get_string(body, "query") }
|
||||
let lim_url: Int = query_int(path, "limit", 0)
|
||||
let lim_body: Int = json_get_int(body, "limit")
|
||||
let lim_either: Int = if lim_url > 0 { lim_url } else { lim_body }
|
||||
let limit: Int = if lim_either > 0 { lim_either } else { 20 }
|
||||
return engram_retrieve_geometric_json(q, limit)
|
||||
}
|
||||
|
||||
fn route_search_lexical(method: String, path: String, body: String) -> String {
|
||||
let q: String = if str_eq(method, "GET") { query_param(path, "q") } else { json_get_string(body, "query") }
|
||||
let lim_url: Int = query_int(path, "limit", 0)
|
||||
let lim_body: Int = json_get_int(body, "limit")
|
||||
@@ -250,8 +373,9 @@ fn route_create_edge(method: String, path: String, body: String) -> String {
|
||||
// (dormant association); only default when the key is absent.
|
||||
let w_present: String = json_get_raw(body, "weight")
|
||||
let weight: Float = if str_eq(w_present, "") { 0.5 } else { json_get_float(body, "weight") }
|
||||
let ec0: Int = engram_edge_count()
|
||||
engram_connect(from_id, to_id, weight, relation)
|
||||
let saved: Int = persist_canonical()
|
||||
let saved: Int = persist_edges_since(ec0)
|
||||
"{\"ok\":true,\"from_id\":\"" + from_id + "\",\"to_id\":\"" + to_id + "\",\"relation\":\"" + relation + "\"}"
|
||||
}
|
||||
|
||||
@@ -276,6 +400,7 @@ fn route_create_edges_batch(method: String, path: String, body: String) -> Strin
|
||||
if str_eq(arr, "") { return err_json("missing edges array") }
|
||||
let n: Int = json_array_len(arr)
|
||||
if n == 0 { return "{\"ok\":true,\"accepted\":0,\"skipped\":0}" }
|
||||
let ec0: Int = engram_edge_count()
|
||||
let i: Int = 0
|
||||
let accepted: Int = 0
|
||||
let skipped: Int = 0
|
||||
@@ -299,7 +424,7 @@ fn route_create_edges_batch(method: String, path: String, body: String) -> Strin
|
||||
// Skip it when nothing was accepted: an all-malformed payload must not
|
||||
// trigger a 60MB write.
|
||||
if accepted > 0 {
|
||||
let saved: Int = persist_canonical()
|
||||
let saved: Int = persist_hebb_batch(ec0)
|
||||
}
|
||||
return "{\"ok\":true,\"accepted\":" + int_to_str(accepted) + ",\"skipped\":" + int_to_str(skipped) + "}"
|
||||
}
|
||||
@@ -315,22 +440,50 @@ fn route_strengthen(method: String, path: String, body: String) -> String {
|
||||
let id: String = json_get_string(body, "node_id")
|
||||
if str_eq(id, "") { return err_json("missing node_id") }
|
||||
engram_strengthen(id)
|
||||
let saved: Int = persist_canonical()
|
||||
let saved: Int = persist_node(id)
|
||||
ok_json()
|
||||
}
|
||||
|
||||
// route_forget — DELETE /api/nodes/:id — INTEGRITY HARDENED (design doc §18.1).
|
||||
//
|
||||
// Two invariants now enforced AT THE STORE (not one layer up in neuron-api.el,
|
||||
// which a direct HTTP client could bypass):
|
||||
// 1. Write-protection: protected identity/value nodes (derived from the self
|
||||
// graph — self root + values hub + their neighbors, §18.3) cannot be
|
||||
// deleted over HTTP. Returns 403, node untouched.
|
||||
// 2. No hard delete over the wire, ever: an ordinary delete creates a
|
||||
// Tombstone marker node + `tombstones` edge and KEEPS the original node
|
||||
// and its edges (recoverable), instead of the old destructive
|
||||
// engram_forget() shift-delete. Raw engram_forget is now internal-GC only
|
||||
// and no longer reachable from any HTTP route.
|
||||
fn route_forget(method: String, path: String, body: String) -> String {
|
||||
let id: String = extract_id(path, "/api/nodes/")
|
||||
if str_eq(id, "") { return err_json("missing id") }
|
||||
engram_forget(id)
|
||||
let saved: Int = persist_canonical()
|
||||
ok_json()
|
||||
if engram_is_protected(id) == 1 {
|
||||
return "{\"__status__\":403,\"error\":\"protected node; deletion refused\",\"id\":\"" + id + "\"}"
|
||||
}
|
||||
let tomb_id: String = engram_node_full(
|
||||
"tombstone:" + id, "Tombstone", "tombstone:" + id,
|
||||
0.1, 0.1, 1.0, "Episodic", "[\"tombstone\"]"
|
||||
)
|
||||
let ec0: Int = engram_edge_count()
|
||||
engram_connect(tomb_id, id, 1.0, "tombstones")
|
||||
let saved: Int = if wal_on() {
|
||||
let d: String = engram_resolve_data_dir()
|
||||
let a: Int = engram_wal_node_put(d, tomb_id)
|
||||
let b: Int = engram_wal_edges_since(d, ec0)
|
||||
let c: Int = engram_wal_maybe_compact(d)
|
||||
a
|
||||
} else {
|
||||
persist_canonical()
|
||||
}
|
||||
"{\"ok\":true,\"tombstoned\":\"" + id + "\",\"tombstone_id\":\"" + tomb_id + "\"}"
|
||||
}
|
||||
|
||||
fn route_save(method: String, path: String, body: String) -> String {
|
||||
let p_raw: String = json_get_string(body, "path")
|
||||
let dir_raw: String = env("ENGRAM_DATA_DIR")
|
||||
let dir: String = if str_eq(dir_raw, "") { "/tmp/engram" } else { dir_raw }
|
||||
let dir: String = engram_resolve_data_dir()
|
||||
let p: String = if str_eq(p_raw, "") { dir + "/snapshot.json" } else { p_raw }
|
||||
// (2026-08-10 self-review) engram_save returns 0 on an empty path and the
|
||||
// route discarded it, so the response was a literal "ok":true regardless
|
||||
@@ -343,10 +496,78 @@ fn route_save(method: String, path: String, body: String) -> String {
|
||||
"{\"ok\":" + sv_ok + ",\"path\":\"" + p + "\",\"node_count\":" + int_to_str(engram_node_count()) + ",\"edge_count\":" + int_to_str(engram_edge_count()) + "}"
|
||||
}
|
||||
|
||||
// route_checkpoint — force a full resident-graph checkpoint into the paged
|
||||
// store (2026-08-13). Neither /api/save nor /api/load makes edges durable in
|
||||
// the tiered paged store — only persist_canonical -> engram_store_checkpoint
|
||||
// does, and that only fires on mutating write routes. This route exposes the
|
||||
// checkpoint directly so a RAM-loaded state (e.g. after /api/load of an export)
|
||||
// can be made durable without a rebuild. Returns ok=false if ENGRAM_STORE is
|
||||
// off (nothing to checkpoint into) or the checkpoint fails.
|
||||
fn route_checkpoint(method: String, path: String, body: String) -> String {
|
||||
let ck: Int = engram_store_checkpoint()
|
||||
let ck_ok: String = if ck == 0 { "false" } else { "true" }
|
||||
"{\"ok\":" + ck_ok + ",\"checkpointed\":true,\"node_count\":" + int_to_str(engram_node_count()) + ",\"edge_count\":" + int_to_str(engram_edge_count()) + "}"
|
||||
}
|
||||
|
||||
// route_tick — chronoception soul-tick (M-INTEROCEPTION P2 wiring, 2026-08-13).
|
||||
// The soul heartbeat pumps this once per beat: node ages advance by the MEASURED
|
||||
// wall-clock delta since the previous tick (self-seeding sidecar stamp). Returns
|
||||
// the cooling magnitude in [0,1). Inert (magnitude 0) unless ENGRAM_CHRONOCEPTION
|
||||
// is set, so wiring this route is safe by default — the flag is the cutover gate.
|
||||
fn route_tick(method: String, path: String, body: String) -> String {
|
||||
let mag: Float = engram_chrono_tick()
|
||||
// SELF-REIFICATION on the heartbeat (2026-08-14). Reification runs HERE, next
|
||||
// to chronoception — unbidden, every beat. Flag-gated (ENGRAM_SELF_REIFY):
|
||||
// when off, engram_self_reify_beat_json() returns {"enabled":false} and writes
|
||||
// nothing, so an unset flag leaves the existing tick byte-inert. Enabling the
|
||||
// flag alone activates continuous autonomous neighborhood formation on the beat
|
||||
// — no heartbeat-script change needed. Idempotent: unchanged regions append
|
||||
// nothing, so a settled store's beat is write-free (convergent under barrier/GC).
|
||||
let reify: String = engram_self_reify_beat_json()
|
||||
"{\"ok\":true,\"cooling_magnitude\":" + float_to_str(mag) + ",\"self_reify\":" + reify + "}"
|
||||
}
|
||||
|
||||
// route_self_reify_beat — POST /api/self-reify-beat. Explicit pump of ONE on-beat
|
||||
// self-reification pass (the same operation route_tick folds in). Used by the
|
||||
// secondary-soul validation harness to drive many beats deterministically. Inert
|
||||
// (writes nothing) unless ENGRAM_SELF_REIFY is set. WRITE op — auth-gated POST.
|
||||
fn route_self_reify_beat(method: String, path: String, body: String) -> String {
|
||||
return engram_self_reify_beat_json()
|
||||
}
|
||||
|
||||
// route_rename — POST /api/rename {"neighborhood_id":"...","name":"..."}. The
|
||||
// DEGENERATE, ASYNCHRONOUS, NON-BLOCKING override: Will (or a self-facet) renames
|
||||
// a reified neighborhood at any time; it SUPERSEDES the autonomous record into the
|
||||
// residue chain (cause="explicit-override", prior name retained). Never halts or
|
||||
// gates the beat — it just writes a superseding record the next beat sees. WRITE.
|
||||
fn route_rename(method: String, path: String, body: String) -> String {
|
||||
let id: String = json_get_string(body, "neighborhood_id")
|
||||
if str_eq(id, "") { return err_json("missing neighborhood_id") }
|
||||
let name: String = json_get_string(body, "name")
|
||||
if str_eq(name, "") { return err_json("missing name") }
|
||||
return engram_neighborhood_rename_json(id, name)
|
||||
}
|
||||
|
||||
// route_self_anchor — capture the durable SelfAnchor drift baseline (the current
|
||||
// self-geometry). Returns ok=false if ENGRAM_DRIFT_SENSOR is off or geometry is
|
||||
// unavailable. Pump once to establish the baseline before reading drift.
|
||||
fn route_self_anchor(method: String, path: String, body: String) -> String {
|
||||
let a: Int = engram_self_anchor_capture()
|
||||
let a_ok: String = if a == 0 { "false" } else { "true" }
|
||||
"{\"ok\":" + a_ok + ",\"anchored\":" + a_ok + "}"
|
||||
}
|
||||
|
||||
// route_drift — live self-drift reading: displacement of CURRENT self-geometry
|
||||
// vs the persisted SelfAnchor (GROWTH vs CORRUPTION split). {"error":...} when
|
||||
// disabled / no anchor yet. The heartbeat can fold this into its ISEs.
|
||||
fn route_drift(method: String, path: String, body: String) -> String {
|
||||
return engram_self_drift_json()
|
||||
}
|
||||
|
||||
fn route_load(method: String, path: String, body: String) -> String {
|
||||
let p_raw: String = json_get_string(body, "path")
|
||||
let dir_raw: String = env("ENGRAM_DATA_DIR")
|
||||
let dir: String = if str_eq(dir_raw, "") { "/tmp/engram" } else { dir_raw }
|
||||
let dir: String = engram_resolve_data_dir()
|
||||
let p: String = if str_eq(p_raw, "") { dir + "/snapshot.json" } else { p_raw }
|
||||
// (2026-08-10 self-review) This was a stub response over the single most
|
||||
// destructive operation in the server. engram_load returns 0 on an empty
|
||||
@@ -398,7 +619,7 @@ fn route_embed_backfill(method: String, path: String, body: String) -> String {
|
||||
let result: String = engram_embed_backfill(n)
|
||||
let done: Float = json_get_float(result, "embedded")
|
||||
if done > 0.0 {
|
||||
let saved: Int = persist_canonical()
|
||||
let saved: Int = persist_bulk()
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -417,7 +638,7 @@ fn route_embed_backfill(method: String, path: String, body: String) -> String {
|
||||
// (2026-06-27 self-review: added this route to fix silent 10-min sync failures)
|
||||
fn route_sync(method: String, path: String, body: String) -> String {
|
||||
let dir_raw: String = env("ENGRAM_DATA_DIR")
|
||||
let dir: String = if str_eq(dir_raw, "") { "/tmp/engram" } else { dir_raw }
|
||||
let dir: String = engram_resolve_data_dir()
|
||||
// 2026-07-21 self-review: export to a scratch path, never the canonical
|
||||
// snapshot.json — read routes must not be able to clobber the good snapshot.
|
||||
let snap_path: String = dir + "/.sync-export.json"
|
||||
@@ -451,7 +672,7 @@ fn route_load_merge(method: String, path: String, body: String) -> String {
|
||||
engram_load_merge(p)
|
||||
let added_n: Int = engram_node_count() - before_n
|
||||
let added_e: Int = engram_edge_count() - before_e
|
||||
let saved: Int = persist_canonical()
|
||||
let saved: Int = persist_bulk()
|
||||
"{\"ok\":true,\"nodes_added\":" + int_to_str(added_n) + ",\"edges_added\":" + int_to_str(added_e) + ",\"node_count\":" + int_to_str(engram_node_count()) + "}"
|
||||
}
|
||||
|
||||
@@ -485,6 +706,15 @@ fn route_load_merge(method: String, path: String, body: String) -> String {
|
||||
fn route_emit_ise(method: String, path: String, body: String) -> String {
|
||||
let content: String = json_get_string(body, "content")
|
||||
if str_eq(content, "") { return err_json("missing content") }
|
||||
// TELEMETRY OFF-GRAPH (ENGRAM_ISE_OFFGRAPH): route the state event to a
|
||||
// separate append-only log tier instead of inserting an edgeless graph node.
|
||||
// dream-recall (engram_dreams_json) reads the log tail when this is on, so
|
||||
// the one in-graph consumer is preserved. Default OFF -> existing behavior.
|
||||
if ise_offgraph_on() {
|
||||
let ok: Int = engram_ise_log_append(content)
|
||||
let ok_s: String = if ok == 0 { "false" } else { "true" }
|
||||
return "{\"ok\":" + ok_s + ",\"offgraph\":true}"
|
||||
}
|
||||
let sal: Float = 0.3
|
||||
let imp: Float = 0.3
|
||||
let conf: Float = 0.8
|
||||
@@ -550,8 +780,17 @@ fn route_capture_knowledge(method: String, path: String, body: String) -> String
|
||||
sal, imp, conf,
|
||||
"Semantic", tags
|
||||
)
|
||||
let saved: Int = persist_canonical()
|
||||
"{\"ok\":true,\"id\":\"" + id + "\"}"
|
||||
let saved: Int = persist_node(id)
|
||||
// ORPHAN PREVENTION (ENGRAM_AUTOCONNECT): same kNN auto-connect as
|
||||
// route_create_node — captured Knowledge should not land edgeless either.
|
||||
let connected: Int = if autoconnect_on() {
|
||||
let ec0: Int = engram_edge_count()
|
||||
let ac: String = engram_autoconnect_node(id, 3, 25)
|
||||
let added: Int = engram_edge_count() - ec0
|
||||
if added > 0 { let sv2: Int = persist_edges_since(ec0) }
|
||||
added
|
||||
} else { 0 }
|
||||
"{\"ok\":true,\"id\":\"" + id + "\",\"connected\":" + int_to_str(connected) + "}"
|
||||
}
|
||||
|
||||
// route_similarity — GET /api/similarity?a=<id>&b=<id>
|
||||
@@ -573,6 +812,139 @@ fn route_similarity(method: String, path: String, body: String) -> String {
|
||||
"{\"a\":\"" + a + "\",\"b\":\"" + b + "\",\"cosine\":" + float_to_str(sim) + "}"
|
||||
}
|
||||
|
||||
// ── M10 reified-neighborhood viz surface (read-only) ────────────────────────────
|
||||
//
|
||||
// The soul maintains reified neighborhoods (centroid, covariance-ellipsoid
|
||||
// extents, k-core skeleton, membership) as a resident index loaded at boot. These
|
||||
// routes surface that ALREADY-maintained structure so the viz shows the mind's
|
||||
// real reified regions instead of recomputing them client-side. They compute
|
||||
// nothing on request. NOTE: the offline reify WRITER (engram_geo_reify_store) is
|
||||
// currently unwired, so on the live store the resident index is empty and the
|
||||
// list returns [] until reification runs — see the cutover report.
|
||||
fn route_neighborhoods(method: String, path: String, body: String) -> String {
|
||||
engram_geo_reify_list_json()
|
||||
}
|
||||
|
||||
fn route_neighborhood(method: String, path: String, body: String) -> String {
|
||||
let id: String = extract_id(path, "/api/neighborhoods/")
|
||||
if str_eq(id, "") { return err_json("missing id") }
|
||||
return engram_geo_reify_get_json(id)
|
||||
}
|
||||
|
||||
// route_reify — POST /api/reify. WIRES the M10 reification writer: computes the
|
||||
// store's neighborhoods and PERSISTS each as a first-class Neighborhood node
|
||||
// (geometry in metadata) with relation="member" edges to its members, then
|
||||
// rebuilds the resident index so /api/neighborhoods reflects them at once. The
|
||||
// records live in neuron.egm, so they survive a cold reboot. WRITE op — the
|
||||
// central auth gate covers POST. Returns {"reified":N,"resident":M}.
|
||||
fn route_reify(method: String, path: String, body: String) -> String {
|
||||
return engram_geo_reify_run_json()
|
||||
}
|
||||
|
||||
// ── Geometry OPERATORS (read-only). The viz runs these on activated node/region
|
||||
// id-sets; the math already lives in the binary, these routes just expose it.
|
||||
// Faculty name -> underlying geometry op:
|
||||
// /api/gauge-distance -> engram_geo_distance (centroid distance/cosine + Wasserstein-2)
|
||||
// /api/recognize -> engram_geo_overlap (shared members, jaccard, overlap_score)
|
||||
// /api/discern -> engram_geo_subtract (?mode=setdiff | orthogonal residual)
|
||||
// /api/synthesize -> engram_geo_combine (merged region descriptor)
|
||||
// Inputs: ?a=<csv ids>&b=<csv ids> (id sets = activated neighborhoods' members / nodes).
|
||||
// Compute-only: no store writes, so auth-exempt like the other GET read routes.
|
||||
fn route_gauge_distance(method: String, path: String, body: String) -> String {
|
||||
let a: String = query_param(path, "a")
|
||||
let b: String = query_param(path, "b")
|
||||
if str_eq(a, "") { return err_json("missing a") }
|
||||
if str_eq(b, "") { return err_json("missing b") }
|
||||
return engram_geo_distance_json(a, b)
|
||||
}
|
||||
fn route_recognize(method: String, path: String, body: String) -> String {
|
||||
let a: String = query_param(path, "a")
|
||||
let b: String = query_param(path, "b")
|
||||
if str_eq(a, "") { return err_json("missing a") }
|
||||
if str_eq(b, "") { return err_json("missing b") }
|
||||
return engram_geo_overlap_json(a, b)
|
||||
}
|
||||
fn route_discern(method: String, path: String, body: String) -> String {
|
||||
let a: String = query_param(path, "a")
|
||||
let b: String = query_param(path, "b")
|
||||
if str_eq(a, "") { return err_json("missing a") }
|
||||
if str_eq(b, "") { return err_json("missing b") }
|
||||
let mode: String = query_param(path, "mode")
|
||||
return engram_geo_subtract_json(a, b, mode)
|
||||
}
|
||||
fn route_synthesize(method: String, path: String, body: String) -> String {
|
||||
let a: String = query_param(path, "a")
|
||||
let b: String = query_param(path, "b")
|
||||
if str_eq(a, "") { return err_json("missing a") }
|
||||
if str_eq(b, "") { return err_json("missing b") }
|
||||
return engram_geo_combine_json(a, b)
|
||||
}
|
||||
|
||||
// route_nearest — GET /api/nearest/<id>?k=3 — read-only kNN semantic neighbors of
|
||||
// a node (cosine). Drives the orphan-backfill dry-run and manual inspection.
|
||||
fn route_nearest(method: String, path: String, body: String) -> String {
|
||||
let id: String = extract_id(path, "/api/nearest/")
|
||||
if str_eq(id, "") { return err_json("missing id") }
|
||||
let k: Int = query_int(path, "k", 3)
|
||||
return engram_nearest_json(id, k)
|
||||
}
|
||||
|
||||
// ── COGNITION: THE ONE OPERATION (think) surfaced as act-named verbs. Every
|
||||
// faculty routes to engram_think_json with a faculty label — one primitive
|
||||
// underneath. ground/assert/attend are the hold/ground/assert split; the
|
||||
// correspondence-beat is the reflexive learning loop, keystone-protected.
|
||||
fn route_think(method: String, path: String, body: String) -> String {
|
||||
let seeds: String = query_param(path, "seeds")
|
||||
if str_eq(seeds, "") { return err_json("missing seeds") }
|
||||
let faculty: String = query_param(path, "faculty")
|
||||
let f: String = if str_eq(faculty, "") { "reason" } else { faculty }
|
||||
return engram_think_json(seeds, f)
|
||||
}
|
||||
fn route_faculty(path: String, faculty: String) -> String {
|
||||
let seeds: String = query_param(path, "seeds")
|
||||
if str_eq(seeds, "") { return err_json("missing seeds") }
|
||||
return engram_think_json(seeds, faculty)
|
||||
}
|
||||
// PROOF of the decorator-seam auto-emit. The body does exactly ONE thing —
|
||||
// return a string — with ZERO hand-written telemetry. The @manager decorator
|
||||
// makes codegen inject engram_boundary_beat() at entry, so every call fires
|
||||
// interoception (chrono tick) + telemetry (afferent counter) + strengthen
|
||||
// (self-activity) + a dharma bus event. Observe via /api/act-stats before/after.
|
||||
@manager
|
||||
fn route_boundary_proof(method: String, path: String, body: String) -> String {
|
||||
return "{\"op\":\"boundary_proof\",\"body_instrumentation\":\"none\",\"seam\":\"@manager -> engram_boundary_beat auto-injected\"}"
|
||||
}
|
||||
fn route_ground(method: String, path: String, body: String) -> String {
|
||||
let claim: String = json_get_string(body, "claim")
|
||||
let evidence: String = json_get_string(body, "evidence")
|
||||
let for_whom: String = json_get_string(body, "for_whom")
|
||||
if str_eq(claim, "") { return err_json("missing claim") }
|
||||
if str_eq(evidence, "") { return err_json("missing evidence") }
|
||||
return engram_ground_json(claim, evidence, for_whom)
|
||||
}
|
||||
fn route_assert(method: String, path: String, body: String) -> String {
|
||||
let claim: String = query_param(path, "claim")
|
||||
if str_eq(claim, "") { return err_json("missing claim") }
|
||||
let for_whom: String = query_param(path, "for_whom")
|
||||
let floor: String = query_param(path, "floor")
|
||||
return engram_assert_json(claim, for_whom, floor)
|
||||
}
|
||||
fn route_attend(method: String, path: String, body: String) -> String {
|
||||
let node: String = json_get_string(body, "node")
|
||||
let observer: String = json_get_string(body, "observer")
|
||||
let salience: String = json_get_string(body, "salience")
|
||||
if str_eq(node, "") { return err_json("missing node") }
|
||||
return engram_attend_json(node, observer, salience)
|
||||
}
|
||||
fn route_correspondence_beat(method: String, path: String, body: String) -> String {
|
||||
let seeds: String = json_get_string(body, "seeds")
|
||||
if str_eq(seeds, "") { return err_json("missing seeds") }
|
||||
let faculty: String = json_get_string(body, "faculty")
|
||||
let f: String = if str_eq(faculty, "") { "induce" } else { faculty }
|
||||
let keystone: String = json_get_string(body, "keystone")
|
||||
return engram_correspondence_beat_json(seeds, f, keystone)
|
||||
}
|
||||
|
||||
// ── Auth ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn check_auth_ok(method: String, body: String) -> Bool {
|
||||
@@ -639,6 +1011,11 @@ fn handle_request(method: String, path: String, body: String) -> String {
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/nodes/") {
|
||||
return route_get_node(method, path, body)
|
||||
}
|
||||
// Singular alias: /api/node/<id>. Distinct prefix from /api/nodes/ ("node/"
|
||||
// vs "nodes/"), so no collision with the plural route above.
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/node/") {
|
||||
return route_get_node_singular(method, path, body)
|
||||
}
|
||||
if str_eq(method, "DELETE") && str_starts_with(clean, "/api/nodes/") {
|
||||
return route_forget(method, path, body)
|
||||
}
|
||||
@@ -654,10 +1031,85 @@ fn handle_request(method: String, path: String, body: String) -> String {
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/edges/batch") || str_eq(clean, "/edges/batch")) {
|
||||
return route_create_edges_batch(method, path, body)
|
||||
}
|
||||
// M10 reified neighborhoods (read-only viz surface). Checked before the
|
||||
// /api/neighbors/ prefix; the two do not collide ("neighborhoods" vs
|
||||
// "neighbors/") but keeping them adjacent documents the intent.
|
||||
if str_eq(method, "GET") && (str_eq(clean, "/api/neighborhoods") || str_eq(clean, "/neighborhoods")) {
|
||||
return route_neighborhoods(method, path, body)
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/neighborhoods/") {
|
||||
return route_neighborhood(method, path, body)
|
||||
}
|
||||
// WRITE: run reification, persisting Neighborhood nodes + member edges.
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/reify") || str_eq(clean, "/reify")) {
|
||||
return route_reify(method, path, body)
|
||||
}
|
||||
// WRITE: on-beat self-reification (flag-gated). Explicit pump for validation.
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/self-reify-beat") || str_eq(clean, "/self-reify-beat")) {
|
||||
return route_self_reify_beat(method, path, body)
|
||||
}
|
||||
// WRITE: async explicit override — rename a reified neighborhood (→ residue).
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/rename") || str_eq(clean, "/rename")) {
|
||||
return route_rename(method, path, body)
|
||||
}
|
||||
// READ-ONLY geometry operators over id-sets (?a=csv&b=csv[&mode=]).
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/gauge-distance") {
|
||||
return route_gauge_distance(method, path, body)
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/recognize") {
|
||||
return route_recognize(method, path, body)
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/discern") {
|
||||
return route_discern(method, path, body)
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/synthesize") {
|
||||
return route_synthesize(method, path, body)
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/nearest/") {
|
||||
return route_nearest(method, path, body)
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/neighbors/") {
|
||||
return route_neighbors(method, path, body)
|
||||
}
|
||||
|
||||
// ── COGNITION: the ONE operation + grounding, surfaced live (2026-08-14).
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/boundary-proof") {
|
||||
return route_boundary_proof(method, path, body)
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/think") {
|
||||
return route_think(method, path, body)
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/reason") {
|
||||
return route_faculty(path, "reason")
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/induce") {
|
||||
return route_faculty(path, "induce")
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/abduce") {
|
||||
return route_faculty(path, "abduce")
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/relate") {
|
||||
return route_faculty(path, "relate")
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/analogize") {
|
||||
return route_faculty(path, "analogy")
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/plan") {
|
||||
return route_faculty(path, "plan")
|
||||
}
|
||||
if str_eq(method, "POST") && str_starts_with(clean, "/api/ground") {
|
||||
return route_ground(method, path, body)
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/assert") {
|
||||
return route_assert(method, path, body)
|
||||
}
|
||||
if str_eq(method, "POST") && str_starts_with(clean, "/api/attend") {
|
||||
return route_attend(method, path, body)
|
||||
}
|
||||
if str_eq(method, "POST") && str_starts_with(clean, "/api/correspondence-beat") {
|
||||
return route_correspondence_beat(method, path, body)
|
||||
}
|
||||
|
||||
// Activation + Search
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/activate") || str_eq(clean, "/activate")) {
|
||||
return route_activate(method, path, body)
|
||||
@@ -665,6 +1117,12 @@ fn handle_request(method: String, path: String, body: String) -> String {
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/activate") {
|
||||
return route_activate(method, path, body)
|
||||
}
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/search-lexical") || str_eq(clean, "/search-lexical")) {
|
||||
return route_search_lexical(method, path, body)
|
||||
}
|
||||
if str_eq(method, "GET") && str_starts_with(clean, "/api/search-lexical") {
|
||||
return route_search_lexical(method, path, body)
|
||||
}
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/search") || str_eq(clean, "/search")) {
|
||||
return route_search(method, path, body)
|
||||
}
|
||||
@@ -681,6 +1139,20 @@ fn handle_request(method: String, path: String, body: String) -> String {
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/save") || str_eq(clean, "/save")) {
|
||||
return route_save(method, path, body)
|
||||
}
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/checkpoint") || str_eq(clean, "/checkpoint")) {
|
||||
return route_checkpoint(method, path, body)
|
||||
}
|
||||
|
||||
// M-INTEROCEPTION: chronoception soul-tick + self-drift (flag-gated)
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/tick") || str_eq(clean, "/tick")) {
|
||||
return route_tick(method, path, body)
|
||||
}
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/self_anchor") || str_eq(clean, "/self_anchor")) {
|
||||
return route_self_anchor(method, path, body)
|
||||
}
|
||||
if (str_eq(method, "POST") || str_eq(method, "GET")) && (str_eq(clean, "/api/drift") || str_eq(clean, "/drift")) {
|
||||
return route_drift(method, path, body)
|
||||
}
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/api/load") || str_eq(clean, "/load")) {
|
||||
return route_load(method, path, body)
|
||||
}
|
||||
@@ -713,23 +1185,44 @@ let bind_str: String = if str_eq(bind_raw, "") { ":8742" } else { bind_raw }
|
||||
let port: Int = parse_port(bind_str)
|
||||
|
||||
// On startup, try to load any existing snapshot (best effort).
|
||||
let data_dir_raw: String = env("ENGRAM_DATA_DIR")
|
||||
let data_dir: String = if str_eq(data_dir_raw, "") { "/tmp/engram" } else { data_dir_raw }
|
||||
// §18.2: resolve the data dir safely — unset ENGRAM_DATA_DIR → $HOME/.neuron/engram,
|
||||
// never /tmp; fail loud if HOME is unresolvable (engram_resolve_data_dir exits).
|
||||
let data_dir: String = engram_resolve_data_dir()
|
||||
let snapshot_path: String = data_dir + "/snapshot.json"
|
||||
engram_load(snapshot_path)
|
||||
// ENGRAM_STORE (tiered paged store — engram-tiered-storage-engine.md). When set,
|
||||
// the durable owner is the paged store (neuron.egm + neuron.wal): engram_store_boot
|
||||
// imports snapshot.json ONCE into a fresh neuron.egm, else replays the WAL and loads
|
||||
// the store resident — snapshot.json is never read again as the ongoing store. This
|
||||
// closes the "restart reverted to a 17h-old snapshot" data-loss window. Flag-off
|
||||
// (default): byte-for-byte the historical snapshot + optional-WAL boot below.
|
||||
if store_on() {
|
||||
engram_store_boot(data_dir)
|
||||
println("[engram] ENGRAM_STORE enabled — tiered paged store is the durable owner")
|
||||
} else {
|
||||
engram_load(snapshot_path)
|
||||
|
||||
// 2026-07-21 self-review boot guard: if the snapshot file has content but the
|
||||
// load produced 0 nodes, something is wrong (corrupt file / parse failure).
|
||||
// Preserve the evidence and warn loudly — and since read routes no longer write
|
||||
// the canonical path, a bad boot can no longer clobber the good snapshot.
|
||||
let boot_snap: String = fs_read(snapshot_path)
|
||||
if !str_eq(boot_snap, "") {
|
||||
if engram_node_count() == 0 {
|
||||
println("[engram] WARNING: snapshot.json is non-empty but load produced 0 nodes — preserving copy at snapshot.failed-load.json")
|
||||
fs_write(data_dir + "/snapshot.failed-load.json", boot_snap)
|
||||
} else {
|
||||
// Good load: keep a boot-time backup of the snapshot as loaded.
|
||||
fs_write(data_dir + "/snapshot.boot-backup.json", boot_snap)
|
||||
// WAL replay (design doc §6). Gated: default OFF is byte-identical to legacy
|
||||
// snapshot-only boot. When ON, the snapshot above is the compaction BASE and
|
||||
// the WAL carries every mutation since; replay reconstructs state to the last
|
||||
// CRC-valid record, then opens the WAL for appending.
|
||||
if wal_on() {
|
||||
let replayed: Int = engram_wal_boot(data_dir)
|
||||
println("[engram] WAL enabled — replayed " + int_to_str(replayed) + " records")
|
||||
}
|
||||
|
||||
// 2026-07-21 self-review boot guard: if the snapshot file has content but the
|
||||
// load produced 0 nodes, something is wrong (corrupt file / parse failure).
|
||||
// Preserve the evidence and warn loudly — and since read routes no longer write
|
||||
// the canonical path, a bad boot can no longer clobber the good snapshot.
|
||||
let boot_snap: String = fs_read(snapshot_path)
|
||||
if !str_eq(boot_snap, "") {
|
||||
if engram_node_count() == 0 {
|
||||
println("[engram] WARNING: snapshot.json is non-empty but load produced 0 nodes — preserving copy at snapshot.failed-load.json")
|
||||
fs_write(data_dir + "/snapshot.failed-load.json", boot_snap)
|
||||
} else {
|
||||
// Good load: keep a boot-time backup of the snapshot as loaded.
|
||||
fs_write(data_dir + "/snapshot.boot-backup.json", boot_snap)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2956,6 +2956,15 @@ fn cg_fn(stmt: Map<String, Any>) -> Void {
|
||||
// arithmetic vs concat on type-annotated identifiers.
|
||||
build_int_names_for_params(params)
|
||||
emit_line("el_val_t " + fn_name + "(" + params_c + ") {")
|
||||
// ── API-reshape decorator-seam: auto-emit at the decorated-fn boundary ──
|
||||
// Every @manager/@accessor fn gets ONE injected call to engram_boundary_beat
|
||||
// at entry — interoception (chrono tick) + telemetry (afferent counter) +
|
||||
// strengthen (self-activity) + a dharma bus event — so a decorated op
|
||||
// self-reports with ZERO hand-written instrumentation in its body. (VBD role
|
||||
// = the topmost decorator; write it topmost when stacking with @route.)
|
||||
if fn_has_decorator(stmt, "manager") || fn_has_decorator(stmt, "accessor") {
|
||||
emit_line(" engram_boundary_beat(EL_STR(" + c_str_lit(fn_name) + "));")
|
||||
}
|
||||
// Seed declared with parameter names so reassignment works
|
||||
let decl = native_list_empty()
|
||||
let np: Int = native_list_len(params)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,883 @@
|
||||
/*
|
||||
* el_runtime.h — El language C runtime header
|
||||
*
|
||||
* Declares all built-in functions available to compiled El programs.
|
||||
* Include this in every generated .c file.
|
||||
*
|
||||
* Value model:
|
||||
* All El values are represented as el_val_t (= int64_t).
|
||||
* On 64-bit systems a pointer fits in int64_t.
|
||||
* String values are cast: (el_val_t)(uintptr_t)"hello"
|
||||
* Integer values are stored directly.
|
||||
* This lets arithmetic work naturally while still passing strings around.
|
||||
*
|
||||
* Type conventions (El -> C):
|
||||
* String -> el_val_t (holds const char* via uintptr_t cast)
|
||||
* Int -> el_val_t
|
||||
* Bool -> el_val_t (0 = false, nonzero = true)
|
||||
* Any -> el_val_t
|
||||
* Void -> void
|
||||
*
|
||||
* Macros for convenience:
|
||||
* EL_STR(s) cast string literal to el_val_t
|
||||
* EL_CSTR(v) cast el_val_t back to const char*
|
||||
* EL_INT(v) identity — el_val_t is already int64_t
|
||||
*
|
||||
* Link requirements:
|
||||
* -lcurl — required for the HTTP client (http_get, http_post, llm_*).
|
||||
* -lpthread — required for the HTTP server (one detached thread per
|
||||
* connection, capped at 64 concurrent).
|
||||
* -loqs — optional; required only when liboqs is installed and the
|
||||
* pq_* / sha3_256_hex entry points are needed. Detected at
|
||||
* compile time via __has_include(<oqs/oqs.h>).
|
||||
* -lcrypto — optional; pulled in alongside -loqs. Used for X25519 in
|
||||
* pq_hybrid_* and HKDF-SHA256 derivation.
|
||||
*
|
||||
* Canonical compile command:
|
||||
* cc -std=c11 -I runtime -lcurl -lpthread \
|
||||
* -o <out> <prog>.c runtime/el_runtime.c
|
||||
*
|
||||
* With liboqs (post-quantum stack):
|
||||
* cc -std=c11 -I runtime -lcurl -lpthread -loqs -lcrypto \
|
||||
* -o <out> <prog>.c runtime/el_runtime.c
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef int64_t el_val_t;
|
||||
|
||||
#define EL_STR(s) ((el_val_t)(uintptr_t)(s))
|
||||
#define EL_CSTR(v) ((const char*)(uintptr_t)(v))
|
||||
#define EL_INT(v) (v)
|
||||
#define EL_NULL ((el_val_t)0)
|
||||
|
||||
/* Float values share the el_val_t (int64) slot via a bit-cast.
|
||||
* The codegen emits Float literals as `el_from_float(<dbl>)` so the
|
||||
* underlying bits represent the IEEE 754 double. Float-aware builtins
|
||||
* (math, format, json) round-trip via these helpers. */
|
||||
static inline double el_to_float(el_val_t v) {
|
||||
union { int64_t i; double f; } u;
|
||||
u.i = (int64_t)v;
|
||||
return u.f;
|
||||
}
|
||||
|
||||
static inline el_val_t el_from_float(double f) {
|
||||
union { double f; int64_t i; } u;
|
||||
u.f = f;
|
||||
return (el_val_t)u.i;
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* ── I/O ──────────────────────────────────────────────────────────────────── */
|
||||
|
||||
void println(el_val_t s);
|
||||
void print(el_val_t s);
|
||||
el_val_t readline(void);
|
||||
|
||||
/* ── String builtins ─────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t el_str_concat(el_val_t a, el_val_t b);
|
||||
el_val_t str_eq(el_val_t a, el_val_t b);
|
||||
el_val_t str_starts_with(el_val_t s, el_val_t prefix);
|
||||
el_val_t str_ends_with(el_val_t s, el_val_t suffix);
|
||||
el_val_t str_len(el_val_t s);
|
||||
el_val_t str_concat(el_val_t a, el_val_t b);
|
||||
el_val_t int_to_str(el_val_t n);
|
||||
el_val_t str_to_int(el_val_t s);
|
||||
el_val_t str_slice(el_val_t s, el_val_t start, el_val_t end);
|
||||
el_val_t str_contains(el_val_t s, el_val_t sub);
|
||||
el_val_t str_replace(el_val_t s, el_val_t from, el_val_t to);
|
||||
el_val_t str_to_upper(el_val_t s);
|
||||
el_val_t str_to_lower(el_val_t s);
|
||||
el_val_t str_trim(el_val_t s);
|
||||
|
||||
/* ── Math ────────────────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t el_abs(el_val_t n);
|
||||
el_val_t el_max(el_val_t a, el_val_t b);
|
||||
el_val_t el_min(el_val_t a, el_val_t b);
|
||||
|
||||
/* ── Refcount (ARC) ──────────────────────────────────────────────────────────
|
||||
* Lists and Maps carry a refcount. Strings and ints do not — el_retain and
|
||||
* el_release are safe no-ops on non-refcounted values (they sniff a magic
|
||||
* header at offset 0 and only act if the magic matches).
|
||||
*
|
||||
* Codegen emits these at let-binding shadowing, function entry (params), and
|
||||
* function exit (locals other than the returned value). The refcount lets
|
||||
* el_list_append and el_map_set mutate in place when uniquely owned (cheap)
|
||||
* and copy-on-write when shared (preserves persistent semantics across
|
||||
* accumulator patterns in the compiler itself). */
|
||||
|
||||
void el_retain(el_val_t v);
|
||||
void el_release(el_val_t v);
|
||||
|
||||
/* ── Arena scoping ────────────────────────────────────────────────────────────
|
||||
* el_arena_push() activates the string arena (if not already active) and
|
||||
* returns a mark; el_arena_pop(mark) frees all strings allocated since that
|
||||
* mark. Used by codegen for per-function/statement scoping and by long-running
|
||||
* EL loops (e.g. the soul daemon's awareness tick) to reclaim per-iteration
|
||||
* allocations. */
|
||||
el_val_t el_arena_push(void);
|
||||
el_val_t el_arena_pop(el_val_t mark);
|
||||
|
||||
/* ── List ────────────────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t el_list_new(el_val_t count, ...);
|
||||
el_val_t el_list_len(el_val_t list);
|
||||
el_val_t el_list_get(el_val_t list, el_val_t index);
|
||||
el_val_t el_list_append(el_val_t list, el_val_t elem);
|
||||
el_val_t el_list_empty(void);
|
||||
el_val_t el_list_clone(el_val_t list);
|
||||
|
||||
/* ── Map ─────────────────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t el_map_new(el_val_t pair_count, ...);
|
||||
el_val_t el_get_field(el_val_t map, el_val_t key);
|
||||
el_val_t el_map_get(el_val_t map, el_val_t key);
|
||||
el_val_t el_map_set(el_val_t map, el_val_t key, el_val_t value);
|
||||
|
||||
/* ── HTTP ─────────────────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t http_get(el_val_t url);
|
||||
el_val_t http_post(el_val_t url, el_val_t body);
|
||||
el_val_t http_post_json(el_val_t url, el_val_t json_body);
|
||||
el_val_t http_get_with_headers(el_val_t url, el_val_t headers_map);
|
||||
el_val_t http_post_with_headers(el_val_t url, el_val_t body, el_val_t headers_map);
|
||||
el_val_t http_post_form_auth(el_val_t url, el_val_t form_body, el_val_t auth_header);
|
||||
el_val_t http_delete(el_val_t url);
|
||||
el_val_t http_delete_json(el_val_t url, el_val_t json_body);
|
||||
void http_serve(el_val_t port, el_val_t handler);
|
||||
void http_set_handler(el_val_t name);
|
||||
|
||||
/* HTTP server v2 ─────────────────────────────────────────────────────────────
|
||||
* Same dispatch model as http_serve, but the handler signature is widened:
|
||||
*
|
||||
* el_val_t handler(method, path, headers_map, body)
|
||||
*
|
||||
* `headers_map` is an ElMap from lowercased header name → header value (both
|
||||
* Strings). Repeated headers are joined with ", " per RFC 7230.
|
||||
*
|
||||
* Response value: the handler may return either
|
||||
* (a) a plain body string — same auto-content-type / 200-OK behaviour as
|
||||
* http_serve (3-arg) — or
|
||||
* (b) a response envelope built with `http_response(status, headers_json,
|
||||
* body)`. The runtime detects the envelope discriminator
|
||||
* `"el_http_response":1` at the start of the returned string and
|
||||
* unpacks status / headers / body before sending.
|
||||
*
|
||||
* The 3-arg http_serve(port, handler) remains supported unchanged for
|
||||
* existing handlers (e.g. products/web/server.el): it dispatches with
|
||||
* (method, path, body), hardcodes 200 OK, and auto-detects content type. */
|
||||
void http_serve_v2(el_val_t port, el_val_t handler);
|
||||
void http_set_handler_v2(el_val_t name);
|
||||
|
||||
/* Non-blocking variant of http_serve: runs the accept loop in a background
|
||||
* pthread and returns immediately so the caller can continue (used by the
|
||||
* soul daemon to run awareness_run() after starting its HTTP API). */
|
||||
void http_serve_async(el_val_t port, el_val_t handler);
|
||||
|
||||
/* Build an HTTP response envelope. `headers_json` should be a JSON object
|
||||
* literal like `{"WWW-Authenticate":"Basic"}` (or "" / "{}" for none). The
|
||||
* returned string carries the discriminator `{"el_http_response":1,...}`
|
||||
* which the runtime's send-path detects and unpacks. Detection happens
|
||||
* uniformly inside http_send_response, so a 3-arg handler may also return
|
||||
* an envelope. The 3-arg variant remains documented as a fixed 200-OK
|
||||
* auto-content-type contract for legacy handlers that return plain bodies. */
|
||||
el_val_t http_response(el_val_t status, el_val_t headers_json, el_val_t body);
|
||||
|
||||
/* HTTP timeout — every libcurl request honors EL_HTTP_TIMEOUT_MS (default
|
||||
* 60000ms). Read lazily on first use, so setting the env var any time before
|
||||
* the first http_* call is sufficient. */
|
||||
|
||||
/* Streaming variants — write the response body straight to a file via
|
||||
* libcurl's CURLOPT_WRITEFUNCTION = fwrite. These bypass the el_val_t string
|
||||
* wrapper entirely, so binary payloads (audio/mpeg, image/png, etc.) survive
|
||||
* embedded NUL bytes that would truncate a strlen()-based code path.
|
||||
*
|
||||
* Both honor EL_HTTP_TIMEOUT_MS, follow redirects, and accept the same
|
||||
* `headers_map` shape as http_post_with_headers (ElMap of String→String).
|
||||
*
|
||||
* Return value: 1 on success (file fully written), 0 on any failure
|
||||
* (network, file open, partial write). On failure the output file is removed
|
||||
* so callers cannot mistake a partially-written file for a valid one. */
|
||||
el_val_t http_post_to_file(el_val_t url, el_val_t body, el_val_t headers_map, el_val_t output_path);
|
||||
el_val_t http_get_to_file(el_val_t url, el_val_t headers_map, el_val_t output_path);
|
||||
|
||||
/* ── URL encoding ────────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t url_encode(el_val_t s); /* RFC 3986 unreserved set */
|
||||
el_val_t url_decode(el_val_t s); /* '+' → space, %XX → byte */
|
||||
|
||||
/* ── HTML allowlist sanitizer ────────────────────────────────────────────────
|
||||
* el_html_sanitize(input_html, allowlist_json) — strict allowlist HTML
|
||||
* cleaner. State-machine parser; tag/attribute names compared case-
|
||||
* insensitively against the allowlist; `<a href>` / `<… src>` URL schemes
|
||||
* validated (http, https, mailto, fragment-only, or relative); whole-
|
||||
* subtree drop for script / style / iframe / object / embed / form; HTML-
|
||||
* escapes free text outside dropped subtrees.
|
||||
*
|
||||
* The allowlist is JSON of the form
|
||||
* {"p":[],"a":["href","title"],"strong":[],...}
|
||||
* where each value is the array of attribute names allowed for that tag. */
|
||||
el_val_t el_html_sanitize(el_val_t input_html, el_val_t allowlist_json);
|
||||
|
||||
/* ── Filesystem ──────────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t fs_read(el_val_t path);
|
||||
el_val_t fs_write(el_val_t path, el_val_t content);
|
||||
el_val_t fs_list(el_val_t path);
|
||||
el_val_t fs_exists(el_val_t path);
|
||||
el_val_t fs_mkdir(el_val_t path); /* mkdir -p, mode 0755 */
|
||||
|
||||
/* Length-explicit binary write. `length` is an Int (el_val_t holding the
|
||||
* byte count). The caller knows the length from context — typically because
|
||||
* `bytes` came from base64_decode (which produces a magic-tagged binary
|
||||
* buffer with embedded NULs possible) and the caller already tracks the
|
||||
* decoded length, OR because the bytes came from a fixed-size source
|
||||
* (sha256_bytes = 32, hmac_sha256_bytes = 32). Bypasses strlen entirely.
|
||||
*
|
||||
* Returns 1 on success, 0 on failure (invalid path, can't open, partial
|
||||
* write, negative length). On partial-write failure, the file is removed
|
||||
* so callers cannot read back a truncated artefact. */
|
||||
el_val_t fs_write_bytes(el_val_t path, el_val_t bytes, el_val_t length);
|
||||
|
||||
/* ── JSON ────────────────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t json_get(el_val_t json, el_val_t key);
|
||||
el_val_t json_parse(el_val_t s);
|
||||
el_val_t json_stringify(el_val_t v);
|
||||
el_val_t json_get_string(el_val_t json_str, el_val_t key);
|
||||
el_val_t json_get_int(el_val_t json_str, el_val_t key);
|
||||
el_val_t json_get_float(el_val_t json_str, el_val_t key);
|
||||
el_val_t json_get_bool(el_val_t json_str, el_val_t key);
|
||||
el_val_t json_get_raw(el_val_t json_str, el_val_t key);
|
||||
el_val_t json_set(el_val_t json_str, el_val_t key, el_val_t value);
|
||||
el_val_t json_array_len(el_val_t json_str);
|
||||
el_val_t json_array_get(el_val_t json_str, el_val_t index);
|
||||
el_val_t json_array_get_string(el_val_t json_str, el_val_t index);
|
||||
|
||||
/* ── Time ────────────────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t time_now(void);
|
||||
el_val_t time_now_utc(void);
|
||||
el_val_t sleep_secs(el_val_t secs);
|
||||
el_val_t sleep_ms(el_val_t ms);
|
||||
el_val_t time_format(el_val_t ts, el_val_t fmt);
|
||||
el_val_t time_to_parts(el_val_t ts);
|
||||
el_val_t time_from_parts(el_val_t secs, el_val_t ns, el_val_t tz);
|
||||
el_val_t time_add(el_val_t ts, el_val_t n, el_val_t unit);
|
||||
el_val_t time_diff(el_val_t ts1, el_val_t ts2, el_val_t unit);
|
||||
|
||||
/* ── Instant + Duration: first-class temporal types ──────────────────────────
|
||||
* Both types share the el_val_t (int64) slot. Instants are nanoseconds
|
||||
* since the Unix epoch; Durations are signed nanoseconds. Type discipline
|
||||
* is enforced at codegen-time: BinOps on names registered as Instant or
|
||||
* Duration route through the typed wrappers below; mismatches like
|
||||
* Instant+Instant become #error at the C compiler.
|
||||
*
|
||||
* Postfix literals — `30.seconds`, `1.hour`, `500.millis`, `30.nanos` — are
|
||||
* recognised by the parser as DurationLit AST nodes and lowered to literal
|
||||
* int64 nanoseconds at codegen time. The runtime never sees the units. */
|
||||
|
||||
el_val_t el_now_instant(void);
|
||||
el_val_t now(void);
|
||||
el_val_t unix_seconds(el_val_t n);
|
||||
el_val_t unix_millis(el_val_t n);
|
||||
el_val_t instant_from_iso8601(el_val_t s);
|
||||
|
||||
el_val_t el_duration_from_nanos(el_val_t ns);
|
||||
el_val_t duration_seconds(el_val_t n);
|
||||
el_val_t duration_millis(el_val_t n);
|
||||
el_val_t duration_nanos(el_val_t n);
|
||||
|
||||
el_val_t el_instant_add_dur(el_val_t inst, el_val_t dur);
|
||||
el_val_t el_instant_sub_dur(el_val_t inst, el_val_t dur);
|
||||
el_val_t el_instant_diff(el_val_t a, el_val_t b);
|
||||
el_val_t el_duration_add(el_val_t a, el_val_t b);
|
||||
el_val_t el_duration_sub(el_val_t a, el_val_t b);
|
||||
el_val_t el_duration_scale(el_val_t dur, el_val_t scalar);
|
||||
el_val_t el_duration_div(el_val_t dur, el_val_t scalar);
|
||||
|
||||
el_val_t el_instant_lt(el_val_t a, el_val_t b);
|
||||
el_val_t el_instant_le(el_val_t a, el_val_t b);
|
||||
el_val_t el_instant_gt(el_val_t a, el_val_t b);
|
||||
el_val_t el_instant_ge(el_val_t a, el_val_t b);
|
||||
el_val_t el_instant_eq(el_val_t a, el_val_t b);
|
||||
el_val_t el_instant_ne(el_val_t a, el_val_t b);
|
||||
el_val_t el_duration_lt(el_val_t a, el_val_t b);
|
||||
el_val_t el_duration_le(el_val_t a, el_val_t b);
|
||||
el_val_t el_duration_gt(el_val_t a, el_val_t b);
|
||||
el_val_t el_duration_ge(el_val_t a, el_val_t b);
|
||||
el_val_t el_duration_eq(el_val_t a, el_val_t b);
|
||||
el_val_t el_duration_ne(el_val_t a, el_val_t b);
|
||||
|
||||
el_val_t instant_to_unix_seconds(el_val_t i);
|
||||
el_val_t instant_to_unix_millis(el_val_t i);
|
||||
el_val_t instant_to_iso8601(el_val_t i);
|
||||
el_val_t duration_to_seconds(el_val_t d);
|
||||
el_val_t duration_to_millis(el_val_t d);
|
||||
el_val_t duration_to_nanos(el_val_t d);
|
||||
|
||||
el_val_t el_sleep_duration(el_val_t dur);
|
||||
el_val_t unix_timestamp(void);
|
||||
|
||||
el_val_t ttl_cache_set(el_val_t key, el_val_t value);
|
||||
el_val_t ttl_cache_get(el_val_t key, el_val_t max_age);
|
||||
el_val_t ttl_cache_age(el_val_t key);
|
||||
|
||||
/* ── Calendar + CalendarTime + Rhythm + LocalDate/Time/DateTime ─────────────
|
||||
* Phase 1.5 of the time system. Calendar is pluggable: EarthCalendar (IANA
|
||||
* zones, Gregorian, DST) is the user-facing default; MarsCalendar,
|
||||
* CycleCalendar(period), NoCycleCalendar, RelativeCalendar handle non-Earth
|
||||
* domains.
|
||||
*
|
||||
* A Calendar interprets an Instant under a particular cycle convention and
|
||||
* produces a CalendarTime. CalendarTime carries the underlying Instant and
|
||||
* a back-pointer to its Calendar; arithmetic and formatting consult the
|
||||
* Calendar to convert ns since epoch into year/month/day/hour/minute/second
|
||||
* (or sol/phase, or cycle/phase, depending on kind).
|
||||
*
|
||||
* Storage convention: Calendar / CalendarTime / Rhythm / LocalDate /
|
||||
* LocalDateTime are heap-allocated structs whose pointers are cast into
|
||||
* el_val_t. A 24-bit magic header at offset 0 lets the runtime identify
|
||||
* the kind safely. LocalTime is small enough to live in the int64 slot
|
||||
* directly (nanos since midnight, signed). */
|
||||
|
||||
/* Zone — opaque IANA zone or fixed offset, used by EarthCalendar.
|
||||
* `zone_id` is either an IANA name ("America/New_York", "UTC") or a fixed
|
||||
* offset string ("+05:30", "-08:00"). The runtime resolves it via tzset()
|
||||
* on first use of the owning EarthCalendar. */
|
||||
el_val_t zone(el_val_t id);
|
||||
el_val_t zone_utc(void);
|
||||
el_val_t zone_local(void);
|
||||
el_val_t zone_offset(el_val_t hours, el_val_t minutes);
|
||||
|
||||
/* Calendar constructors. Each returns an el_val_t pointer to a heap-
|
||||
* allocated, magic-tagged Calendar struct. Calendars are interned by
|
||||
* (kind, zone_id, period_ns, epoch_ns) so identical constructors return
|
||||
* the same pointer — equality is reference equality. */
|
||||
el_val_t earth_calendar(el_val_t z);
|
||||
el_val_t earth_calendar_default(void);
|
||||
el_val_t mars_calendar(void);
|
||||
el_val_t cycle_calendar(el_val_t period_dur);
|
||||
el_val_t no_cycle_calendar(void);
|
||||
el_val_t relative_calendar(el_val_t epoch_inst);
|
||||
|
||||
/* CalendarTime constructors and methods. Returns a heap-allocated struct
|
||||
* whose pointer fits in el_val_t. */
|
||||
el_val_t now_in(el_val_t cal);
|
||||
el_val_t in_calendar(el_val_t inst, el_val_t cal);
|
||||
el_val_t cal_format(el_val_t ct, el_val_t pattern);
|
||||
el_val_t cal_to_instant(el_val_t ct);
|
||||
el_val_t cal_cycle_phase(el_val_t ct);
|
||||
el_val_t cal_in(el_val_t ct, el_val_t cal);
|
||||
|
||||
/* LocalDate / LocalTime / LocalDateTime — calendar-agnostic value types.
|
||||
* LocalTime carries nanoseconds since midnight as a signed int64 directly
|
||||
* in the el_val_t slot (no allocation). LocalDate / LocalDateTime are
|
||||
* heap-allocated structs with magic headers. */
|
||||
el_val_t local_date(el_val_t y, el_val_t m, el_val_t d);
|
||||
el_val_t local_time(el_val_t h, el_val_t m, el_val_t s, el_val_t ns);
|
||||
el_val_t local_datetime(el_val_t date, el_val_t time);
|
||||
el_val_t zoned(el_val_t date, el_val_t time, el_val_t cal);
|
||||
|
||||
el_val_t local_date_year(el_val_t ld);
|
||||
el_val_t local_date_month(el_val_t ld);
|
||||
el_val_t local_date_day(el_val_t ld);
|
||||
el_val_t local_time_hour(el_val_t lt);
|
||||
el_val_t local_time_minute(el_val_t lt);
|
||||
el_val_t local_time_second(el_val_t lt);
|
||||
el_val_t local_time_nanos(el_val_t lt);
|
||||
|
||||
el_val_t el_local_date_add_dur(el_val_t ld, el_val_t dur);
|
||||
el_val_t el_local_time_add_dur(el_val_t lt, el_val_t dur);
|
||||
el_val_t el_local_date_lt(el_val_t a, el_val_t b);
|
||||
el_val_t el_local_date_eq(el_val_t a, el_val_t b);
|
||||
|
||||
/* Rhythm — pluggable recurrence AST. Returns a heap-allocated struct
|
||||
* pointer in el_val_t; rhythms are immutable so callers may share them. */
|
||||
el_val_t rhythm_cycle_start(void);
|
||||
el_val_t rhythm_cycle_phase(el_val_t phase);
|
||||
el_val_t rhythm_duration(el_val_t d);
|
||||
el_val_t rhythm_session_start(void);
|
||||
el_val_t rhythm_event(el_val_t name);
|
||||
el_val_t rhythm_and(el_val_t a, el_val_t b);
|
||||
el_val_t rhythm_or(el_val_t a, el_val_t b);
|
||||
el_val_t rhythm_weekday(el_val_t day);
|
||||
el_val_t rhythm_weekly_at(el_val_t day, el_val_t hour, el_val_t minute);
|
||||
el_val_t rhythm_next_after(el_val_t r, el_val_t after, el_val_t cal);
|
||||
el_val_t rhythm_matches(el_val_t r, el_val_t ct);
|
||||
|
||||
/* ── UUID ────────────────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t uuid_new(void);
|
||||
el_val_t uuid_v4(void);
|
||||
|
||||
/* ── Environment ─────────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t env(el_val_t key);
|
||||
|
||||
/* ── In-process state K/V ────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t state_set(el_val_t key, el_val_t value);
|
||||
el_val_t state_get(el_val_t key);
|
||||
el_val_t state_del(el_val_t key);
|
||||
el_val_t state_keys(void);
|
||||
|
||||
/* ── Float formatting ────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t float_to_str(el_val_t f);
|
||||
el_val_t int_to_float(el_val_t n);
|
||||
el_val_t float_to_int(el_val_t f);
|
||||
el_val_t format_float(el_val_t f, el_val_t decimals);
|
||||
el_val_t decimal_round(el_val_t f, el_val_t decimals);
|
||||
el_val_t str_to_float(el_val_t s);
|
||||
|
||||
/* ── Math (Float-aware) ──────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t math_sqrt(el_val_t f);
|
||||
el_val_t math_log(el_val_t f);
|
||||
el_val_t math_ln(el_val_t f);
|
||||
el_val_t math_sin(el_val_t f);
|
||||
el_val_t math_cos(el_val_t f);
|
||||
el_val_t math_pi(void);
|
||||
|
||||
/* ── String additions ────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t str_index_of(el_val_t s, el_val_t sub);
|
||||
el_val_t str_split(el_val_t s, el_val_t sep);
|
||||
el_val_t str_char_at(el_val_t s, el_val_t i);
|
||||
el_val_t str_char_code(el_val_t s, el_val_t i);
|
||||
el_val_t str_pad_left(el_val_t s, el_val_t width, el_val_t pad);
|
||||
el_val_t str_pad_right(el_val_t s, el_val_t width, el_val_t pad);
|
||||
el_val_t str_format(el_val_t fmt, el_val_t data);
|
||||
el_val_t str_lower(el_val_t s);
|
||||
el_val_t str_upper(el_val_t s);
|
||||
|
||||
/* ── Text-processing primitives (Phase 1: byte/codepoint, ASCII char classes)
|
||||
* Phase 2 (filed): Unicode-grapheme awareness, NFC/NFD normalization, regex.
|
||||
* is_* predicates: empty input returns false; multi-char requires ALL bytes
|
||||
* to match. ASCII ranges only in Phase 1. */
|
||||
|
||||
/* Counting */
|
||||
el_val_t str_count(el_val_t s, el_val_t sub); /* non-overlapping */
|
||||
el_val_t str_count_chars(el_val_t s); /* codepoint count */
|
||||
el_val_t str_count_bytes(el_val_t s); /* alias of str_len */
|
||||
el_val_t str_count_lines(el_val_t s);
|
||||
el_val_t str_count_words(el_val_t s);
|
||||
el_val_t str_count_letters(el_val_t s); /* ASCII [A-Za-z] */
|
||||
el_val_t str_count_digits(el_val_t s); /* ASCII [0-9] */
|
||||
|
||||
/* Find / position */
|
||||
el_val_t str_index_of_all(el_val_t s, el_val_t sub); /* [Int] of byte offsets */
|
||||
el_val_t str_last_index_of(el_val_t s, el_val_t sub);
|
||||
el_val_t str_find_chars(el_val_t s, el_val_t any_of); /* first idx of any ch */
|
||||
|
||||
/* Transform */
|
||||
el_val_t str_repeat(el_val_t s, el_val_t n);
|
||||
el_val_t str_reverse(el_val_t s); /* by codepoint */
|
||||
el_val_t str_strip_prefix(el_val_t s, el_val_t prefix);
|
||||
el_val_t str_strip_suffix(el_val_t s, el_val_t suffix);
|
||||
el_val_t str_strip_chars(el_val_t s, el_val_t chars);
|
||||
el_val_t str_lstrip(el_val_t s);
|
||||
el_val_t str_rstrip(el_val_t s);
|
||||
|
||||
/* Char classification (Bool) */
|
||||
el_val_t is_letter(el_val_t s);
|
||||
el_val_t is_digit(el_val_t s);
|
||||
el_val_t is_alphanumeric(el_val_t s);
|
||||
el_val_t is_whitespace(el_val_t s);
|
||||
el_val_t is_punctuation(el_val_t s);
|
||||
el_val_t is_uppercase(el_val_t s);
|
||||
el_val_t is_lowercase(el_val_t s);
|
||||
|
||||
/* Split / join */
|
||||
el_val_t str_split_lines(el_val_t s);
|
||||
el_val_t str_split_chars(el_val_t s); /* alias of native_string_chars */
|
||||
el_val_t str_split_n(el_val_t s, el_val_t sep, el_val_t n);
|
||||
el_val_t str_join(el_val_t list, el_val_t sep); /* alias of list_join */
|
||||
|
||||
/* ── List additions ──────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t list_push(el_val_t list, el_val_t elem);
|
||||
el_val_t list_push_front(el_val_t list, el_val_t elem);
|
||||
el_val_t list_join(el_val_t list, el_val_t sep);
|
||||
el_val_t list_range(el_val_t start, el_val_t end);
|
||||
|
||||
/* ── Bool helpers ────────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t bool_to_str(el_val_t b);
|
||||
|
||||
/* ── Numeric parsing ─────────────────────────────────────────────────────── */
|
||||
|
||||
el_val_t parse_int(el_val_t s, el_val_t default_val);
|
||||
|
||||
/* ── Process ─────────────────────────────────────────────────────────────── */
|
||||
|
||||
void exit_program(el_val_t code);
|
||||
el_val_t getpid_now(void);
|
||||
|
||||
/* ── CGI identity ─────────────────────────────────────────────────────────────
|
||||
* Called at the start of main() in CGI programs (those with a `cgi {}` block).
|
||||
* Records the program's DHARMA identity before any other code executes. */
|
||||
|
||||
void el_cgi_init(el_val_t name, el_val_t dharma_id, el_val_t principal,
|
||||
el_val_t network, el_val_t engram);
|
||||
|
||||
/* ── DHARMA network builtins ─────────────────────────────────────────────────
|
||||
* Available to CGI programs (declared with a `cgi {}` block).
|
||||
*
|
||||
* Peers are addressed by `dharma_id` of the form
|
||||
* "<registry-id>@<transport-url>" e.g. "ntn-genesis@http://localhost:7770"
|
||||
* If the @<url> portion is omitted, transport defaults to
|
||||
* "http://localhost:7770" (the local CGI daemon assumption).
|
||||
*
|
||||
* Wire protocol (all peers expose):
|
||||
* POST <url>/dharma/recv { channel, from, content } → response body
|
||||
* POST <url>/dharma/event { type, payload, source, timestamp }
|
||||
* POST <url>/api/activate { query } → list of nodes
|
||||
*
|
||||
* Hosting application's responsibility: an El program with a `cgi {}` block
|
||||
* runs http_serve() with its own request handler; that handler should route
|
||||
* "/dharma/event" requests by calling el_runtime_dharma_event_arrive() so
|
||||
* incoming events feed dharma_field() queues. The runtime itself does not
|
||||
* intercept any /dharma path. */
|
||||
|
||||
el_val_t dharma_connect(el_val_t cgi_id);
|
||||
el_val_t dharma_send(el_val_t channel, el_val_t content);
|
||||
el_val_t dharma_activate(el_val_t query);
|
||||
void dharma_emit(el_val_t event_type, el_val_t payload);
|
||||
el_val_t dharma_field(el_val_t event_type);
|
||||
void dharma_strengthen(el_val_t cgi_id, el_val_t weight);
|
||||
el_val_t dharma_relationship(el_val_t cgi_id);
|
||||
el_val_t dharma_peers(void);
|
||||
|
||||
/* Public C API: called by an El program's HTTP handler when a /dharma/event
|
||||
* request arrives. Pushes onto the per-event-type queue and signals any
|
||||
* pending dharma_field() blockers. All three arguments must be NUL-terminated
|
||||
* C strings (or NULL — then treated as empty). */
|
||||
void el_runtime_dharma_event_arrive(const char* event_type,
|
||||
const char* payload,
|
||||
const char* source);
|
||||
|
||||
/* ── Engram local graph primitives ───────────────────────────────────────────
|
||||
* Operate on the CGI's local Engram knowledge graph.
|
||||
* `engram_activate` queries the local graph only; `dharma_activate` is
|
||||
* network-wide across all connected CGI graphs. */
|
||||
|
||||
el_val_t engram_node(el_val_t content, el_val_t node_type, el_val_t salience);
|
||||
el_val_t engram_node_full(el_val_t content, el_val_t node_type, el_val_t label,
|
||||
el_val_t salience, el_val_t importance, el_val_t confidence,
|
||||
el_val_t tier, el_val_t tags);
|
||||
/* Layered consciousness — see el_runtime.c for the layered architecture
|
||||
* design notes (search "Layered consciousness architecture"). The five
|
||||
* canonical layers (safety / core-identity / domain-knowledge / imprint /
|
||||
* suit) are seeded automatically; engram_add_layer extends the registry
|
||||
* with imprint or suit overlays at runtime. Nodes default to layer 1
|
||||
* (core-identity) when created via engram_node / engram_node_full. */
|
||||
el_val_t engram_node_layered(el_val_t content, el_val_t node_type, el_val_t label,
|
||||
el_val_t salience, el_val_t certainty, el_val_t confidence,
|
||||
el_val_t status, el_val_t tags, el_val_t layer_id);
|
||||
el_val_t engram_add_layer(el_val_t name, el_val_t priority, el_val_t suppressible,
|
||||
el_val_t transparent, el_val_t injectable);
|
||||
el_val_t engram_remove_layer(el_val_t layer_id);
|
||||
el_val_t engram_list_layers(void);
|
||||
el_val_t engram_get_node(el_val_t id);
|
||||
void engram_strengthen(el_val_t node_id);
|
||||
void engram_forget(el_val_t node_id);
|
||||
el_val_t engram_prune_telemetry(el_val_t older_than_ms);
|
||||
el_val_t engram_node_count(void);
|
||||
el_val_t engram_search(el_val_t query, el_val_t limit);
|
||||
el_val_t engram_scan_nodes(el_val_t limit, el_val_t offset);
|
||||
void engram_connect(el_val_t from_id, el_val_t to_id, el_val_t weight, el_val_t relation);
|
||||
el_val_t engram_edge_between(el_val_t from_id, el_val_t to_id);
|
||||
el_val_t engram_neighbors(el_val_t node_id);
|
||||
el_val_t engram_neighbors_filtered(el_val_t node_id, el_val_t max_depth, el_val_t direction);
|
||||
el_val_t engram_edge_count(void);
|
||||
/* Three-pass activation: background fan-out → working-memory promotion →
|
||||
* Layer 0 override. See "Three-pass activation" in el_runtime.c. */
|
||||
el_val_t engram_activate(el_val_t query, el_val_t depth);
|
||||
el_val_t engram_save(el_val_t path);
|
||||
el_val_t engram_load(el_val_t path);
|
||||
/* Tiered paged-store entry points (ENGRAM_STORE=1). engram_store_boot opens the
|
||||
* durable store (import-once / WAL-replay) and loads it resident; checkpoint pushes
|
||||
* the resident graph's current field state (incl. learned hebb + activation-formed
|
||||
* edges) through the WAL and flushes; close checkpoints + closes. No-ops when off. */
|
||||
el_val_t engram_store_boot(el_val_t data_dir);
|
||||
el_val_t engram_store_checkpoint(void);
|
||||
el_val_t engram_store_close(void);
|
||||
|
||||
/* JSON-string accessors — return pre-serialized JSON so HTTP handlers
|
||||
* can pass results straight through without round-tripping ElList/ElMap
|
||||
* through json_stringify. */
|
||||
el_val_t engram_get_node_json(el_val_t id);
|
||||
el_val_t engram_get_node_by_label(el_val_t label);
|
||||
el_val_t engram_search_json(el_val_t query, el_val_t limit);
|
||||
el_val_t engram_retrieve_geometric_json(el_val_t query, el_val_t limit);
|
||||
el_val_t engram_scan_nodes_json(el_val_t limit, el_val_t offset);
|
||||
el_val_t engram_scan_nodes_by_type_json(el_val_t node_type, el_val_t limit, el_val_t offset);
|
||||
el_val_t engram_scan_nodes_emb_json(el_val_t limit, el_val_t offset);
|
||||
el_val_t engram_dreams_json(el_val_t since_ms);
|
||||
/* §5 geometry operators as EL builtins (read-only; seed-id CSV args). */
|
||||
el_val_t engram_geo_descriptor_json(el_val_t seeds);
|
||||
el_val_t engram_geo_overlap_json(el_val_t a_seeds, el_val_t b_seeds);
|
||||
el_val_t engram_geo_subtract_json(el_val_t a_seeds, el_val_t b_seeds, el_val_t mode);
|
||||
el_val_t engram_geo_combine_json(el_val_t a_seeds, el_val_t b_seeds);
|
||||
el_val_t engram_geo_distance_json(el_val_t a_seeds, el_val_t b_seeds);
|
||||
el_val_t engram_geo_analogy_json(el_val_t a_seeds, el_val_t b_seeds);
|
||||
/* reasoning layer (compositions over §5 operators). ANALOGY maps cleanly to the
|
||||
* flat-CSV seed ABI; the other modes take set/point/timestamp inputs deferred from
|
||||
* this ABI (see engram_reason.h / the reasoning-operators runbook). */
|
||||
el_val_t engram_reason_analogy_json(el_val_t a_seeds, el_val_t b_seeds, el_val_t c_seeds);
|
||||
/* COGNITION (2026-08-14): THE ONE OPERATION + grounding, surfaced live. */
|
||||
el_val_t engram_think_json(el_val_t seeds, el_val_t faculty);
|
||||
el_val_t engram_ground_json(el_val_t claim, el_val_t evidence, el_val_t for_whom);
|
||||
el_val_t engram_assert_json(el_val_t claim_id, el_val_t for_whom, el_val_t floor);
|
||||
el_val_t engram_attend_json(el_val_t node_id, el_val_t observer, el_val_t salience);
|
||||
el_val_t engram_correspondence_beat_json(el_val_t seeds, el_val_t faculty, el_val_t keystone);
|
||||
el_val_t engram_consolidate_permanence(el_val_t node_id);
|
||||
el_val_t engram_age_field(el_val_t delta_ms);
|
||||
el_val_t engram_age_field_catchup(void);
|
||||
el_val_t engram_chrono_persist_tick(void);
|
||||
el_val_t engram_chrono_tick(void);
|
||||
el_val_t engram_boundary_beat(el_val_t op_name); /* API-reshape decorator-seam auto-emit */
|
||||
el_val_t engram_self_anchor_capture(void);
|
||||
el_val_t engram_self_drift_json(void);
|
||||
el_val_t engram_neighbors_json(el_val_t node_id, el_val_t max_depth, el_val_t direction);
|
||||
el_val_t engram_activate_json(el_val_t query, el_val_t depth);
|
||||
el_val_t engram_stats_json(void);
|
||||
el_val_t engram_act_stats_json(void);
|
||||
el_val_t engram_text_health_json(void);
|
||||
el_val_t engram_cosine_sim(el_val_t id_a, el_val_t id_b);
|
||||
/* M10 reified-neighborhood read-only HTTP surface (2026-08-13). List/detail of
|
||||
* the resident reify index; [] until the offline reify writer has run. */
|
||||
el_val_t engram_geo_reify_list_json(void);
|
||||
el_val_t engram_geo_reify_get_json(el_val_t id);
|
||||
/* WRITE: run reification — persist Neighborhood nodes + member edges, rebuild the
|
||||
* resident index. Wires the previously-dormant engram_geo_reify_store. */
|
||||
el_val_t engram_geo_reify_run_json(void);
|
||||
/* SELF-REIFICATION (2026-08-14). ON-BEAT autonomous neighborhood formation:
|
||||
* gated by ENGRAM_SELF_REIFY (default off → returns {"enabled":false}, writes
|
||||
* nothing — the live binary is byte-inert until the flag is set). When on, runs
|
||||
* ONE bounded, incremental, idempotent reification pass (change-detection skips
|
||||
* unchanged hubs → no re-append; grounded names; residue-preserving supersession;
|
||||
* soft/overlapping membership; nests only when something changed). Meant to be
|
||||
* pumped every heartbeat next to Hebbian consolidation. Returns
|
||||
* {"enabled":true,"reified":N,"skipped":S,"superseded":P,"nested":X,"resident":M,"wrote":b}. */
|
||||
el_val_t engram_self_reify_beat_json(void);
|
||||
/* ASYNC EXPLICIT OVERRIDE (degenerate manual case). Rename a live neighborhood
|
||||
* by id: writes a superseding record with the new name, prepends a residue entry
|
||||
* (cause="explicit-override", prior name), keeps the same geometry/members. Never
|
||||
* blocks the beat. Returns {"ok":true,"renamed":<old>,"new_id":<new>,"name":..}. */
|
||||
el_val_t engram_neighborhood_rename_json(el_val_t id, el_val_t name);
|
||||
/* Orphan prevention: form up to k semantic-similar edges to a node's nearest
|
||||
* embedded neighbors (kNN). engram_nearest_json is the read-only probe. */
|
||||
el_val_t engram_autoconnect_node(el_val_t id, el_val_t k, el_val_t min_sim_pct);
|
||||
el_val_t engram_nearest_json(el_val_t id, el_val_t k);
|
||||
/* Telemetry off-graph: append one ISE JSON line to the state-event log tier. */
|
||||
el_val_t engram_ise_log_append(el_val_t content);
|
||||
/* Destructively pop up to `max` newly-formed Hebbian associations as a JSON
|
||||
* array of {from_id,to_id,weight,hebb}. The learning process (soul daemon) is
|
||||
* not the process that owns persistence (engram HTTP server); this is how a
|
||||
* self-formed association crosses that boundary. (2026-08-07 self-review.) */
|
||||
el_val_t engram_hebb_drain_json(el_val_t max);
|
||||
/* Document frequency of a term across node labels — term-specificity signal
|
||||
* for curiosity seed selection. (2026-08-03 self-review.) */
|
||||
el_val_t engram_label_df(el_val_t term);
|
||||
/* Best curiosity seed from one node: argmax over idf·position·casing across
|
||||
* the candidate tokens of its label, falling back to its content when the
|
||||
* label is a sentinel. Excludes pipe-delimited tabu terms during selection
|
||||
* and gates candidates to the df band [min_df, max_df]. Returns "" when
|
||||
* nothing qualifies. (2026-08-13 self-review.) */
|
||||
el_val_t engram_salient_term(el_val_t node_id, el_val_t max_df,
|
||||
el_val_t min_df, el_val_t tabu);
|
||||
el_val_t engram_embed_backfill(el_val_t count);
|
||||
el_val_t engram_list_layers_json(void);
|
||||
/* Working memory introspection — count, mean weight, and top-N snapshot.
|
||||
* Ported from runtime on 2026-06-30 self-review. */
|
||||
el_val_t engram_wm_count(void);
|
||||
el_val_t engram_wm_avg_weight(void);
|
||||
el_val_t engram_wm_top_json(el_val_t n);
|
||||
/* Merge-load: add nodes/edges from a snapshot without resetting the store. */
|
||||
el_val_t engram_load_merge(el_val_t path);
|
||||
|
||||
/* ── WAL + compaction + integrity (ENGRAM_WAL=on; design doc §§3-14,§18) ──── */
|
||||
int engram_wal_enabled(void);
|
||||
el_val_t engram_crc32(el_val_t s);
|
||||
el_val_t engram_wal_boot(el_val_t dir); /* replay + open; returns records */
|
||||
el_val_t engram_wal_open_dir(el_val_t dir);
|
||||
el_val_t engram_wal_node_put(el_val_t dir, el_val_t id);
|
||||
el_val_t engram_wal_edges_since(el_val_t dir, el_val_t start_count);
|
||||
el_val_t engram_wal_hebb_batch(el_val_t dir, el_val_t start_count);
|
||||
el_val_t engram_wal_forget(el_val_t dir, el_val_t id);
|
||||
el_val_t engram_wal_compact(el_val_t dir);
|
||||
el_val_t engram_wal_maybe_compact(el_val_t dir);
|
||||
el_val_t engram_resolve_data_dir(void); /* §18.2 fail-loud default */
|
||||
el_val_t engram_is_protected(el_val_t id); /* §18.1/18.3 derived set */
|
||||
el_val_t engram_protected_json(void);
|
||||
/* engram_compile_layered_json — produce a prompt-ready text block split
|
||||
* into "[LAYER 0 — STRUCTURAL]" (non-suppressible layers, sacred fire)
|
||||
* and "[ENGRAM CONTEXT]" (standard suppressible layers). Returns "" if
|
||||
* no nodes promoted to working memory. */
|
||||
el_val_t engram_compile_layered_json(el_val_t intent, el_val_t depth);
|
||||
|
||||
/* ── LLM (Anthropic API client) ─────────────────────────────────────────────
|
||||
* All functions call https://api.anthropic.com/v1/messages with the API key
|
||||
* from env ANTHROPIC_API_KEY. Default model when empty: claude-sonnet-4-5. */
|
||||
|
||||
el_val_t llm_call(el_val_t model, el_val_t prompt);
|
||||
el_val_t llm_call_system(el_val_t model, el_val_t system_prompt, el_val_t user_prompt);
|
||||
el_val_t llm_call_agentic(el_val_t model, el_val_t system, el_val_t user, el_val_t tools);
|
||||
/* LLM token telemetry (CCR §4.4): usage.{input,output}_tokens parsed from every
|
||||
* response. Returns Map{input_tokens,output_tokens,total_input_tokens,
|
||||
* total_output_tokens,calls}. */
|
||||
el_val_t llm_last_usage(void);
|
||||
/* Fold usage.{input,output}_tokens from a raw messages response into the counters.
|
||||
* Called internally on every LLM response; exported for offline testing. */
|
||||
void llm_record_usage(const char* resp);
|
||||
el_val_t llm_vision(el_val_t model, el_val_t system, el_val_t prompt, el_val_t image_url_or_b64);
|
||||
el_val_t llm_models(void);
|
||||
|
||||
/* Register a tool handler by name. The handler is looked up via dlsym
|
||||
* (mirroring http_set_handler), so any El `fn <name>(input)` compiles to
|
||||
* a global C symbol that this function can locate at runtime.
|
||||
* Handler signature: `el_val_t handler(el_val_t input_json)` — receives
|
||||
* the tool input as a JSON-string el_val_t and returns a JSON-string
|
||||
* el_val_t result. Used by llm_call_agentic. */
|
||||
void llm_register_tool(el_val_t name, el_val_t handler_fn_name);
|
||||
|
||||
/* ── args() ─────────────────────────────────────────────────────────────────
|
||||
* Provides access to command-line arguments passed to the program.
|
||||
* Populated by el_runtime_init_args() before main() runs. */
|
||||
|
||||
el_val_t args(void);
|
||||
void el_runtime_init_args(int argc, char** argv);
|
||||
|
||||
/* ── Crypto primitives ─────────────────────────────────────────────────────
|
||||
* SHA-256, HMAC-SHA-256, and base64 (standard + URL-safe).
|
||||
* Self-contained — no OpenSSL/libcrypto dependency. The implementations are
|
||||
* adapted from public-domain reference code (Brad Conte / RFC 4648).
|
||||
*
|
||||
* Bytes-returning variants (sha256_bytes, hmac_sha256_bytes) return a string
|
||||
* value whose contents are raw binary; callers usually feed these into
|
||||
* base64_encode. Note that el_val_t strings are NUL-terminated by convention,
|
||||
* so the binary payload may contain embedded NULs — pass it directly into
|
||||
* base64_encode (which uses an explicit length) rather than treating it as
|
||||
* a printable C string.
|
||||
*
|
||||
* The "base64" variants emit/accept RFC 4648 standard alphabet with padding.
|
||||
* The "base64url" variants use URL-safe alphabet (`-`/`_`) with no padding,
|
||||
* as used in JWTs. */
|
||||
|
||||
el_val_t sha256_hex(el_val_t input);
|
||||
el_val_t sha256_bytes(el_val_t input);
|
||||
el_val_t hmac_sha256_hex(el_val_t key, el_val_t message);
|
||||
el_val_t hmac_sha256_bytes(el_val_t key, el_val_t message);
|
||||
el_val_t base64_encode(el_val_t input);
|
||||
el_val_t base64_decode(el_val_t input);
|
||||
el_val_t base64url_encode(el_val_t input);
|
||||
el_val_t base64url_decode(el_val_t input);
|
||||
|
||||
/* Length-aware variants (internal — exposed for the rare caller that already
|
||||
* has a known-length binary buffer and doesn't want to round-trip through
|
||||
* a NUL-terminated el_val_t string). Sha256_bytes and hmac_sha256_bytes feed
|
||||
* these implicitly. */
|
||||
el_val_t el_sha256_bytes_n(const unsigned char* data, size_t len);
|
||||
el_val_t el_base64_encode_n(const unsigned char* data, size_t len, int url_safe);
|
||||
|
||||
/* ── Post-quantum primitives (liboqs-backed) ────────────────────────────────
|
||||
* All inputs/outputs hex-encoded. Algorithm choices:
|
||||
* Signature: CRYSTALS-Dilithium-3 (NIST level 3, balanced)
|
||||
* KEM: CRYSTALS-Kyber-768 (NIST level 3)
|
||||
* Hash: SHA3-256 (Keccak) (PQ-aware protocols favour SHA3 over SHA2)
|
||||
*
|
||||
* If liboqs is not linked (detected via __has_include(<oqs/oqs.h>) at compile
|
||||
* time), the pq_* entry points return a JSON-shaped error string so callers
|
||||
* fail loudly rather than silently fall back to classical schemes:
|
||||
* {"error":"liboqs not linked, post-quantum primitives unavailable"}
|
||||
*
|
||||
* The hybrid handshake pairs X25519 with Kyber-768 per NIST PQ guidance and
|
||||
* CNSA 2.0. Combined shared secret is HKDF-SHA256(x25519_ss || kyber_ss).
|
||||
* Even if Kyber falls, X25519 holds; if X25519 falls under quantum attack,
|
||||
* Kyber holds. SHA3-256 also remains usable independent of liboqs (the
|
||||
* Keccak permutation is PQ-OK as a primitive). */
|
||||
|
||||
el_val_t pq_keygen_signature(void);
|
||||
el_val_t pq_sign(el_val_t secret_key_hex, el_val_t message);
|
||||
el_val_t pq_verify(el_val_t public_key_hex, el_val_t message, el_val_t signature_hex);
|
||||
|
||||
el_val_t pq_kem_keygen(void);
|
||||
el_val_t pq_kem_encaps(el_val_t public_key_hex);
|
||||
el_val_t pq_kem_decaps(el_val_t secret_key_hex, el_val_t ciphertext_hex);
|
||||
|
||||
el_val_t pq_hybrid_keygen(void);
|
||||
el_val_t pq_hybrid_handshake(el_val_t remote_pub_combined);
|
||||
|
||||
el_val_t sha3_256_hex(el_val_t input);
|
||||
|
||||
/* ── AEAD: AES-256-GCM (libcrypto-backed) ───────────────────────────────────
|
||||
* Symmetric authenticated encryption used to wrap envelopes after a KEM
|
||||
* handshake. Caller MUST supply a 32-byte key (64 hex chars) — typically the
|
||||
* Kyber-768 / hybrid shared_secret, optionally normalized via SHA3-256.
|
||||
*
|
||||
* aead_encrypt returns a JSON map {"nonce":"...","ciphertext":"..."} where
|
||||
* ciphertext is the AES-256-GCM output with the 16-byte auth tag appended.
|
||||
* Nonce is a fresh 12-byte CSPRNG draw — callers never pick the nonce, which
|
||||
* structurally rules out the GCM nonce-reuse footgun.
|
||||
*
|
||||
* aead_decrypt returns the plaintext String, or "" on any failure (including
|
||||
* auth-tag mismatch). Callers MUST check for "" before trusting the result. */
|
||||
el_val_t aead_encrypt(el_val_t key_hex, el_val_t plaintext);
|
||||
el_val_t aead_decrypt(el_val_t key_hex, el_val_t nonce_hex, el_val_t ciphertext_hex);
|
||||
|
||||
/* ── Native VM builtin aliases (for compiled El source) ─────────────────────
|
||||
* These match the El VM's native_* builtins so that El source compiled
|
||||
* to C can call the same names without modification. */
|
||||
|
||||
el_val_t native_list_get(el_val_t list, el_val_t index);
|
||||
el_val_t native_list_len(el_val_t list);
|
||||
el_val_t native_list_append(el_val_t list, el_val_t elem);
|
||||
el_val_t native_list_empty(void);
|
||||
el_val_t native_list_clone(el_val_t list);
|
||||
el_val_t native_string_chars(el_val_t s);
|
||||
el_val_t native_int_to_str(el_val_t n);
|
||||
|
||||
/* ── Method-call shorthand aliases ──────────────────────────────────────────
|
||||
* The El method-call convention `obj.method(args)` compiles to
|
||||
* `method(obj, args)`. These aliases expose the runtime functions under
|
||||
* the short names that result from method calls in El source.
|
||||
*
|
||||
* Example: `myList.append(x)` → `append(myList, x)` (calls this alias)
|
||||
* `myList.len()` → `len(myList)` (calls this alias) */
|
||||
|
||||
el_val_t append(el_val_t list, el_val_t elem); /* el_list_append */
|
||||
el_val_t len(el_val_t list); /* el_list_len */
|
||||
el_val_t get(el_val_t list, el_val_t index); /* el_list_get */
|
||||
el_val_t map_get(el_val_t map, el_val_t key); /* el_map_get */
|
||||
el_val_t map_set(el_val_t map, el_val_t key, el_val_t value); /* el_map_set */
|
||||
|
||||
/* ── OTLP/HTTP Observability ─────────────────────────────────────────────── */
|
||||
/* See bottom of el_runtime.c for the implementation.
|
||||
* Configured by env vars OTLP_ENDPOINT, OTEL_SERVICE_NAME, OTEL_SERVICE_VERSION.
|
||||
* No-op when OTLP_ENDPOINT is unset. Drop-on-failure semantics. */
|
||||
/* ── Subprocess execution ────────────────────────────────────────────────── */
|
||||
el_val_t exec_command(el_val_t cmd); /* run shell command, return exit code */
|
||||
el_val_t exec_capture(el_val_t cmd); /* run shell command, capture stdout */
|
||||
el_val_t exec(el_val_t cmd); /* exec(cmd) → stdout String (30s timeout) */
|
||||
el_val_t exec_bg(el_val_t cmd); /* exec_bg(cmd) → PID String (non-blocking) */
|
||||
|
||||
el_val_t emit_log(el_val_t level, el_val_t msg, el_val_t fields_json);
|
||||
el_val_t emit_metric(el_val_t name, el_val_t value, el_val_t tags_json);
|
||||
el_val_t trace_span_start(el_val_t name);
|
||||
el_val_t trace_span_end(el_val_t span_handle);
|
||||
el_val_t emit_event(el_val_t name, el_val_t duration_ms);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,339 @@
|
||||
/* engram_cognition.c — THE ONE OPERATION. See engram_cognition.h.
|
||||
* Pure over its inputs (think/warp/express); persistence is additive/supersede
|
||||
* only. stdlib + libm + engram_store/reason/geometry. Touches no live daemon. */
|
||||
#include "engram_cognition.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <math.h>
|
||||
|
||||
/* ── small helpers ──────────────────────────────────────────────────────────── */
|
||||
static double vdot(const float* a, const float* b, int dim) {
|
||||
double s = 0; for (int i = 0; i < dim; i++) s += (double)a[i] * (double)b[i]; return s;
|
||||
}
|
||||
static double vnorm(const float* a, int dim) { return sqrt(vdot(a, a, dim)); }
|
||||
static char* dupstr(const char* s) {
|
||||
if (!s) return NULL; size_t n = strlen(s) + 1; char* p = malloc(n);
|
||||
if (p) memcpy(p, s, n); return p;
|
||||
}
|
||||
static double clampd(double x, double lo, double hi){ return x<lo?lo:(x>hi?hi:x); }
|
||||
|
||||
/* ═══════════════════════════════════════════════ Stance lifecycle ════════════ */
|
||||
int cog_stance_init(CogStance* s, const char* id, const char* faculty,
|
||||
const char* anchor_region, const char* for_whom,
|
||||
const GeoDescriptor* region) {
|
||||
if (!s || !region) return -1;
|
||||
memset(s, 0, sizeof *s);
|
||||
s->id = dupstr(id); s->faculty = dupstr(faculty);
|
||||
s->anchor_region = dupstr(anchor_region); s->for_whom = dupstr(for_whom);
|
||||
s->dim = region->dim;
|
||||
s->n_axes = region->n_axes > COG_MAX_AXES ? COG_MAX_AXES : region->n_axes;
|
||||
for (int k = 0; k < COG_MAX_AXES; k++) s->axis_gain[k] = 1.0;
|
||||
s->ext_floor = 1.0; s->drop_frac = 0.5; s->assoc_floor = 0.2;
|
||||
s->bias_dir = NULL;
|
||||
s->reliability = 0.5; /* uninformed prior on our own track record */
|
||||
return 0;
|
||||
}
|
||||
void cog_stance_set_frozen_defaults(CogStance* s) {
|
||||
if (!s) return;
|
||||
for (int k = 0; k < COG_MAX_AXES; k++) s->axis_gain[k] = 1.0;
|
||||
s->ext_floor = 1.0; s->drop_frac = 0.5; s->assoc_floor = 0.2;
|
||||
free(s->bias_dir); s->bias_dir = NULL;
|
||||
}
|
||||
void cog_stance_free(CogStance* s) {
|
||||
if (!s) return;
|
||||
free(s->id); free(s->faculty); free(s->anchor_region); free(s->for_whom);
|
||||
free(s->bias_dir);
|
||||
s->id = s->faculty = s->anchor_region = s->for_whom = NULL; s->bias_dir = NULL;
|
||||
}
|
||||
int cog_is_keystone(const CogKeystoneSet* ks, const CogStance* s) {
|
||||
if (!s) return 0;
|
||||
if (s->keystone) return 1;
|
||||
if (!ks || !s->id) return 0;
|
||||
for (int i = 0; i < ks->n; i++)
|
||||
if (ks->ids[i] && (strcmp(ks->ids[i], s->id) == 0 ||
|
||||
(s->anchor_region && strcmp(ks->ids[i], s->anchor_region) == 0))) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════ warped fit (think step 2) ══ */
|
||||
int cog_warped_fit(const GeoDescriptor* g, const float* x,
|
||||
const CogStance* st, GeoFit* out) {
|
||||
if (!g || !x || !out || g->dim <= 0 || !g->centroid) return -1;
|
||||
double ext_floor = (st && st->ext_floor > 0) ? st->ext_floor : 1.0;
|
||||
int dim = g->dim;
|
||||
double rr = 0;
|
||||
float* r = malloc((size_t)dim * sizeof(float));
|
||||
if (!r) return -1;
|
||||
for (int i = 0; i < dim; i++) { double d = (double)x[i] - (double)g->centroid[i]; r[i] = (float)d; rr += d * d; }
|
||||
double maha2 = 0, ss_in = 0;
|
||||
for (int k = 0; k < g->n_axes; k++) {
|
||||
const float* ax = g->axes[k].axis; if (!ax) continue;
|
||||
double proj = vdot(r, ax, dim);
|
||||
double gain = (st && k < st->n_axes && st->axis_gain[k] > 0) ? st->axis_gain[k] : 1.0;
|
||||
double den = g->axes[k].extent * gain; if (den < ext_floor) den = ext_floor;
|
||||
maha2 += (proj / den) * (proj / den);
|
||||
ss_in += proj * proj;
|
||||
}
|
||||
double ortho2 = rr - ss_in; if (ortho2 < 0) ortho2 = 0;
|
||||
double dist2 = maha2 + ortho2 / (ext_floor * ext_floor);
|
||||
out->mahalanobis = sqrt(maha2); out->ortho_residual = sqrt(ortho2);
|
||||
out->distance = sqrt(dist2); out->score = 1.0 / (1.0 + dist2);
|
||||
free(r);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════ think (the ONE operation) ══ */
|
||||
void engram_gradient_free(GeoGradient* g) {
|
||||
if (!g) return; free(g->direction); g->direction = NULL;
|
||||
}
|
||||
int engram_think(const GeoDescriptor* region, const float* anchor,
|
||||
const CogStance* stance, GeoGradient* out) {
|
||||
if (!region || !out || region->dim <= 0 || !region->centroid) return -1;
|
||||
int dim = region->dim;
|
||||
memset(out, 0, sizeof *out);
|
||||
out->dim = dim;
|
||||
const float* x = anchor ? anchor : region->centroid; /* re-origin (step 1) */
|
||||
|
||||
GeoFit f;
|
||||
if (cog_warped_fit(region, x, stance, &f) != 0) return -1; /* fit (step 2) */
|
||||
|
||||
/* step 3 — emit a GRADIENT: warped steepest DESCENT of the fit distance². */
|
||||
double ext_floor = (stance && stance->ext_floor > 0) ? stance->ext_floor : 1.0;
|
||||
float* grad = calloc((size_t)dim, sizeof(float)); /* ∇ dist² wrt x */
|
||||
float* r = malloc((size_t)dim * sizeof(float));
|
||||
out->direction = malloc((size_t)dim * sizeof(float));
|
||||
if (!grad || !r || !out->direction) { free(grad); free(r); free(out->direction); out->direction = NULL; return -1; }
|
||||
for (int i = 0; i < dim; i++) r[i] = (float)((double)x[i] - (double)region->centroid[i]);
|
||||
/* in-subspace: Σ_k 2 (proj/den²) a_k ; also accumulate Σ proj a_k for ortho part */
|
||||
float* proj_sum = calloc((size_t)dim, sizeof(float));
|
||||
if (!proj_sum) { free(grad); free(r); free(out->direction); out->direction = NULL; return -1; }
|
||||
for (int k = 0; k < region->n_axes; k++) {
|
||||
const float* ax = region->axes[k].axis; if (!ax) continue;
|
||||
double proj = vdot(r, ax, dim);
|
||||
double gain = (stance && k < stance->n_axes && stance->axis_gain[k] > 0) ? stance->axis_gain[k] : 1.0;
|
||||
double den = region->axes[k].extent * gain; if (den < ext_floor) den = ext_floor;
|
||||
double coef = 2.0 * proj / (den * den);
|
||||
for (int i = 0; i < dim; i++) { grad[i] += (float)(coef * ax[i]); proj_sum[i] += (float)(proj * ax[i]); }
|
||||
}
|
||||
/* orthogonal: (2 r − 2 Σ proj a_k) / ext_floor² */
|
||||
double inv_f2 = 1.0 / (ext_floor * ext_floor);
|
||||
for (int i = 0; i < dim; i++)
|
||||
grad[i] += (float)((2.0 * (double)r[i] - 2.0 * (double)proj_sum[i]) * inv_f2);
|
||||
free(proj_sum);
|
||||
|
||||
/* steering = −grad (descent), seeded by the stance's bias_dir. */
|
||||
for (int i = 0; i < dim; i++) out->direction[i] = -grad[i];
|
||||
if (stance && stance->bias_dir) {
|
||||
double gn = vnorm(grad, dim), bn = vnorm(stance->bias_dir, dim);
|
||||
if (bn > 1e-12) {
|
||||
double scale = (gn > 1e-12 ? gn : 1.0); /* seed at the gradient's scale */
|
||||
for (int i = 0; i < dim; i++)
|
||||
out->direction[i] += (float)(scale * (double)stance->bias_dir[i] / bn);
|
||||
}
|
||||
}
|
||||
double dn = vnorm(out->direction, dim);
|
||||
if (dn > 1e-12) for (int i = 0; i < dim; i++) out->direction[i] /= (float)dn;
|
||||
else for (int i = 0; i < dim; i++) out->direction[i] = 0.0f; /* at rest */
|
||||
|
||||
out->spread = f.distance; /* spiked (0) .. diffuse */
|
||||
out->confidence = stance ? stance->reliability : 0.5;
|
||||
out->magnitude = f.score; /* the read's membership */
|
||||
out->anchor_id = region->hub_id; /* borrowed vantage id */
|
||||
out->n_support = region->n_members;
|
||||
out->stance_id = stance ? stance->id : NULL;
|
||||
free(grad); free(r);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* EXPRESSION — the ONLY collapse to a point (a separate faculty from think). */
|
||||
int engram_express(const GeoGradient* g, const float* anchor, float* out_point) {
|
||||
if (!g || !anchor || !out_point || !g->direction) return -1;
|
||||
double commit = clampd(g->confidence, 0.0, 1.0); /* confident => commit far */
|
||||
for (int i = 0; i < g->dim; i++)
|
||||
out_point[i] = anchor[i] + g->direction[i] * (float)commit;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════ Stance serialization ════════ */
|
||||
/* Compact line schema "STNC1" (mirrors the reify "GEO1" precedent). */
|
||||
char* cog_stance_to_metadata(const CogStance* s) {
|
||||
if (!s) return NULL;
|
||||
size_t cap = 256 + (size_t)s->n_axes * 24 + (size_t)(s->bias_dir ? s->dim * 16 : 0);
|
||||
char* buf = malloc(cap); if (!buf) return NULL;
|
||||
size_t o = 0;
|
||||
o += (size_t)snprintf(buf + o, cap - o, "%s\n", COG_STANCE_META_MAGIC);
|
||||
o += (size_t)snprintf(buf + o, cap - o, "f %s\n", s->faculty ? s->faculty : "-");
|
||||
o += (size_t)snprintf(buf + o, cap - o, "r %s\n", s->anchor_region ? s->anchor_region : "-");
|
||||
o += (size_t)snprintf(buf + o, cap - o, "w %s\n", s->for_whom ? s->for_whom : "-");
|
||||
o += (size_t)snprintf(buf + o, cap - o, "k %d\n", s->keystone);
|
||||
o += (size_t)snprintf(buf + o, cap - o, "d %d %d\n", s->dim, s->n_axes);
|
||||
o += (size_t)snprintf(buf + o, cap - o, "s %.9g %.9g %.9g\n", s->ext_floor, s->drop_frac, s->assoc_floor);
|
||||
o += (size_t)snprintf(buf + o, cap - o, "g");
|
||||
for (int k = 0; k < s->n_axes; k++) o += (size_t)snprintf(buf + o, cap - o, " %.9g", s->axis_gain[k]);
|
||||
o += (size_t)snprintf(buf + o, cap - o, "\n");
|
||||
o += (size_t)snprintf(buf + o, cap - o, "c %lld %.9g %.9g %.9g %.9g\n",
|
||||
(long long)s->n_trials, s->brier_sum, s->reliability, s->ema_error, s->last_error);
|
||||
if (s->bias_dir) {
|
||||
o += (size_t)snprintf(buf + o, cap - o, "b");
|
||||
for (int i = 0; i < s->dim; i++) o += (size_t)snprintf(buf + o, cap - o, " %.9g", (double)s->bias_dir[i]);
|
||||
o += (size_t)snprintf(buf + o, cap - o, "\n");
|
||||
}
|
||||
(void)o;
|
||||
return buf;
|
||||
}
|
||||
int cog_stance_to_node(const CogStance* s, StoreNode* out) {
|
||||
if (!s || !out) return -1;
|
||||
memset(out, 0, sizeof *out);
|
||||
out->id = dupstr(s->id);
|
||||
out->node_type = dupstr(COG_STANCE_NODE_TYPE);
|
||||
out->content = dupstr(s->faculty ? s->faculty : "stance");
|
||||
out->label = dupstr(s->faculty ? s->faculty : "stance");
|
||||
out->metadata = cog_stance_to_metadata(s);
|
||||
out->importance = s->reliability; /* cached denormalized readout (§2.1) */
|
||||
out->confidence = s->reliability;
|
||||
out->temporal_decay_rate = 0.0;
|
||||
return (out->id && out->node_type && out->metadata) ? 0 : -1;
|
||||
}
|
||||
static int parse_floats(const char* line, double* out, int max) {
|
||||
int n = 0; const char* p = line;
|
||||
while (*p && n < max) {
|
||||
while (*p == ' ') p++;
|
||||
if (!*p) break;
|
||||
char* end; double v = strtod(p, &end);
|
||||
if (end == p) break;
|
||||
out[n++] = v; p = end;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
int cog_stance_from_node(const StoreNode* n, CogStance* out) {
|
||||
if (!n || !out || !n->metadata) return -1;
|
||||
memset(out, 0, sizeof *out);
|
||||
for (int k = 0; k < COG_MAX_AXES; k++) out->axis_gain[k] = 1.0;
|
||||
out->ext_floor = 1.0; out->drop_frac = 0.5; out->assoc_floor = 0.2; out->reliability = 0.5;
|
||||
out->id = dupstr(n->id);
|
||||
/* verify magic on first line */
|
||||
const char* m = n->metadata;
|
||||
if (strncmp(m, COG_STANCE_META_MAGIC, strlen(COG_STANCE_META_MAGIC)) != 0) return -1;
|
||||
char* copy = dupstr(m); if (!copy) return -1;
|
||||
for (char* line = strtok(copy, "\n"); line; line = strtok(NULL, "\n")) {
|
||||
if (line[0] == '\0' || line[1] != ' ') {
|
||||
if (line[0] == 'g' || line[0] == 'b') { /* vector lines: tag then values */ }
|
||||
else continue;
|
||||
}
|
||||
char tag = line[0];
|
||||
const char* rest = line + 1; while (*rest == ' ') rest++;
|
||||
if (tag == 'f') { free(out->faculty); out->faculty = (strcmp(rest, "-") ? dupstr(rest) : NULL); }
|
||||
else if (tag == 'r') { free(out->anchor_region); out->anchor_region = (strcmp(rest, "-") ? dupstr(rest) : NULL); }
|
||||
else if (tag == 'w') { free(out->for_whom); out->for_whom = (strcmp(rest, "-") ? dupstr(rest) : NULL); }
|
||||
else if (tag == 'k') { out->keystone = atoi(rest); }
|
||||
else if (tag == 'd') { int a=0,b=0; sscanf(rest, "%d %d", &a, &b); out->dim = a; out->n_axes = b > COG_MAX_AXES ? COG_MAX_AXES : b; }
|
||||
else if (tag == 's') { double v[3]={1,0.5,0.2}; parse_floats(rest, v, 3); out->ext_floor=v[0]; out->drop_frac=v[1]; out->assoc_floor=v[2]; }
|
||||
else if (tag == 'g') { double v[COG_MAX_AXES]; int c=parse_floats(rest, v, COG_MAX_AXES); for(int k=0;k<c;k++) out->axis_gain[k]=v[k]; }
|
||||
else if (tag == 'c') { double v[5]={0,0,0.5,0,0}; parse_floats(rest, v, 5); out->n_trials=(int64_t)v[0]; out->brier_sum=v[1]; out->reliability=v[2]; out->ema_error=v[3]; out->last_error=v[4]; }
|
||||
else if (tag == 'b') { if (out->dim>0){ out->bias_dir=calloc((size_t)out->dim,sizeof(float)); double v[4096]; int c=parse_floats(rest,v,out->dim<4096?out->dim:4096); for(int i=0;i<c;i++) out->bias_dir[i]=(float)v[i]; } }
|
||||
}
|
||||
free(copy);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════ grounding as a RELATION ═════ */
|
||||
static int put_edge(EngramPagedStore* s, const char* id, const char* from, const char* to,
|
||||
const char* relation, double weight, const char* meta) {
|
||||
StoreEdge e; memset(&e, 0, sizeof e);
|
||||
e.id = (char*)id; e.from_id = (char*)from; e.to_id = (char*)to;
|
||||
e.relation = (char*)relation; e.weight = weight; e.confidence = weight;
|
||||
e.metadata = (char*)meta;
|
||||
return store_put_edge(s, &e);
|
||||
}
|
||||
int cog_ground_edge(EngramPagedStore* s, const char* claim_id,
|
||||
const char* evidence_id, double grounding, const char* for_whom) {
|
||||
if (!s || !claim_id || !evidence_id) return -1;
|
||||
char id[512], meta[256];
|
||||
snprintf(id, sizeof id, "gb-%s-%s-%s", claim_id, evidence_id, for_whom ? for_whom : "global");
|
||||
snprintf(meta, sizeof meta, "for_whom=%s", for_whom ? for_whom : "-");
|
||||
return put_edge(s, id, claim_id, evidence_id, COG_GROUNDED_BY_RELATION, grounding, meta);
|
||||
}
|
||||
int cog_salient_edge(EngramPagedStore* s, const char* node_id,
|
||||
const char* observer_id, double salience) {
|
||||
if (!s || !node_id || !observer_id) return -1;
|
||||
char id[512];
|
||||
snprintf(id, sizeof id, "st-%s-%s", node_id, observer_id);
|
||||
return put_edge(s, id, node_id, observer_id, COG_SALIENT_TO_RELATION, salience, NULL);
|
||||
}
|
||||
int cog_assert_gate(EngramPagedStore* s, const char* claim_id,
|
||||
const char* for_whom, double floor) {
|
||||
if (!s || !claim_id) return -1;
|
||||
if (!(floor > 0)) floor = 0.5;
|
||||
StoreEdge* edges = NULL; size_t n = 0;
|
||||
if (store_get_edges_from(s, claim_id, &edges, &n) < 0) return -1;
|
||||
double best = 0.0; int found = 0;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
if (!edges[i].relation || strcmp(edges[i].relation, COG_GROUNDED_BY_RELATION) != 0) continue;
|
||||
/* grounded-for-whom: match observer if requested; global (for_whom=-) always counts */
|
||||
int match = 1;
|
||||
if (for_whom && edges[i].metadata) {
|
||||
const char* fw = strstr(edges[i].metadata, "for_whom=");
|
||||
if (fw) { fw += 9; if (strcmp(fw, for_whom) != 0 && strcmp(fw, "-") != 0) match = 0; }
|
||||
}
|
||||
if (match) { found = 1; if (edges[i].weight > best) best = edges[i].weight; }
|
||||
}
|
||||
store_edges_free(edges, n);
|
||||
if (!found) return 0; /* ungrounded => refuse assertion (still held) */
|
||||
return (best >= floor) ? 1 : 0;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════ THE CORRESPONDENCE-LOOP ═════ */
|
||||
int engram_correspondence_beat(const GeoDescriptor* region, const float* anchor,
|
||||
double outcome_y, CogStance* stance,
|
||||
int learn, double max_step, CogBeatResult* out) {
|
||||
if (!region || !stance || !out) return -1;
|
||||
memset(out, 0, sizeof *out);
|
||||
if (stance->keystone) { learn = 0; out->wrote_keystone = 1; } /* §6: never write a keystone */
|
||||
|
||||
GeoGradient g;
|
||||
if (engram_think(region, anchor, stance, &g) != 0) return -1; /* PREDICTION */
|
||||
double p = g.magnitude;
|
||||
double y = clampd(outcome_y, 0.0, 1.0);
|
||||
double err = fabs(p - y);
|
||||
out->correspondence = 1.0 - err;
|
||||
out->error = err;
|
||||
out->brier = (p - y) * (p - y);
|
||||
|
||||
if (learn) {
|
||||
/* refine warp: gradient descent of (p−y)² wrt each axis_gain.
|
||||
* p = 1/(1+D²); ∂p/∂gain_k = 2 p² proj_k² / (ext_k² gain_k³) (>=0)
|
||||
* ∂(err²)/∂gain_k = 2 (p−y) ∂p/∂gain_k
|
||||
* step = −lr · ∂(err²)/∂gain_k, bounded to ±max_step (metastability). */
|
||||
int dim = region->dim;
|
||||
const float* x = anchor ? anchor : region->centroid;
|
||||
float* r = malloc((size_t)dim * sizeof(float));
|
||||
if (r) {
|
||||
for (int i = 0; i < dim; i++) r[i] = (float)((double)x[i] - (double)region->centroid[i]);
|
||||
double lr = 0.5;
|
||||
double bound = (max_step > 0) ? max_step : 0.05; /* bounded update rate */
|
||||
for (int k = 0; k < region->n_axes && k < stance->n_axes; k++) {
|
||||
const float* ax = region->axes[k].axis; if (!ax) continue;
|
||||
double proj = vdot(r, ax, dim);
|
||||
double ext = region->axes[k].extent; if (ext < 1e-9) ext = 1e-9;
|
||||
double gain = stance->axis_gain[k]; if (gain < 1e-6) gain = 1e-6;
|
||||
double dp_dgain = 2.0 * p * p * (proj * proj) / (ext * ext * gain * gain * gain);
|
||||
double dErr_dgain = 2.0 * (p - y) * dp_dgain;
|
||||
double step = -lr * dErr_dgain;
|
||||
step = clampd(step, -bound, bound);
|
||||
stance->axis_gain[k] = clampd(gain + step, 0.1, 50.0);
|
||||
}
|
||||
free(r);
|
||||
}
|
||||
/* calibration */
|
||||
stance->n_trials += 1;
|
||||
stance->brier_sum += out->brier;
|
||||
stance->last_error = err;
|
||||
stance->ema_error = (stance->n_trials == 1) ? err : 0.9 * stance->ema_error + 0.1 * err;
|
||||
double mean_brier = stance->brier_sum / (double)stance->n_trials;
|
||||
stance->reliability = clampd(1.0 - sqrt(mean_brier), 0.0, 1.0);
|
||||
}
|
||||
out->reliability = stance->reliability;
|
||||
engram_gradient_free(&g);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
/* engram_cognition.h — THE ONE OPERATION.
|
||||
*
|
||||
* The buildable form of the "cognition is one operation" theory (design doc
|
||||
* engram/spec/cognitive-architecture.design.md; memory bdc8a488 / d582a766).
|
||||
*
|
||||
* Cognition is ONE operation — think — a directed traversal-READ of the geometry
|
||||
* from an anchor, steered by a learned STANCE, whose output is a GRADIENT (a
|
||||
* direction + spread over the geometry), never a point. The named faculties
|
||||
* (reason / induce / abduce / analogy / relate / plan / ground) are human LABELS
|
||||
* on regions of think's steering space: each faculty == { think + a named stance }.
|
||||
* Collapse-to-a-point happens only at EXPRESSION (a separate faculty), never in think.
|
||||
*
|
||||
* NAMING (Will's directive): the surface verbs name the cognitive ACT being
|
||||
* performed (think / reason / induce / ground / verify), not the internal function
|
||||
* shape. The single frozen primitive underneath every faculty is engram_think,
|
||||
* which composes over engram_reason_point_fit + the §5 geo-algebra. Those never
|
||||
* learn. Only the STANCE learns.
|
||||
*
|
||||
* "Stance" is the theory's steering PRIOR, deliberately named distinctly: in this
|
||||
* codebase the token "prior" already means previous-VERSION (supersession). A
|
||||
* Stance is a learnable bias/disposition over the geometry — which axes matter,
|
||||
* which way pays off, plus a calibrated track record — attached to a faculty-label
|
||||
* and a region, and grounded-for-whom.
|
||||
*
|
||||
* PURE + (mostly) READ-ONLY, stdlib + libm only. think() and the warp are pure
|
||||
* over their inputs. Persistence (Stance <-> StoreNode, grounded-by edges) is the
|
||||
* only part that touches the store, and it is additive / supersede / tombstone —
|
||||
* never mutate-in-place, never delete. It NEVER touches the live daemon: all
|
||||
* offline against a scratch store, per the design's rails.
|
||||
*/
|
||||
#ifndef ENGRAM_COGNITION_H
|
||||
#define ENGRAM_COGNITION_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "engram_geometry.h"
|
||||
#include "engram_reason.h"
|
||||
#include "engram_store.h"
|
||||
|
||||
/* Max principal axes a stance warps (matches GeoParams.top_axes default budget). */
|
||||
#define COG_MAX_AXES 32
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* §1 GeoGradient — the OUTPUT of think. A direction + spread over the geometry,
|
||||
* plus the calibrated confidence and the read it was computed against. NOT a point.
|
||||
* A spiked gradient (spread→0) = "exact" (deduction); a spread gradient = "fuzzy"
|
||||
* (prediction). The gradient is ALSO the next steering direction (closed-loop flow).
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct {
|
||||
int dim;
|
||||
float* direction; /* unit steering vector in the anchor's frame (owned) */
|
||||
double spread; /* 0 = spiked/exact ... large = diffuse/fuzzy */
|
||||
double confidence; /* calibrated, from the stance's track record (reliab.) */
|
||||
double magnitude; /* THIS read's own membership/fit estimate ∈(0,1].
|
||||
* The scalar an expression faculty would SAMPLE; kept
|
||||
* on the gradient but never used AS a decision by think.*/
|
||||
const char* anchor_id; /* borrowed: the vantage this was read from */
|
||||
int n_support; /* neighborhood members that shaped the read */
|
||||
const char* stance_id; /* borrowed: which stance steered this (provenance) */
|
||||
} GeoGradient;
|
||||
|
||||
void engram_gradient_free(GeoGradient* g);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* §2 Stance — the learnable steering prior, as a first-class object. In memory
|
||||
* here; persisted as a StoreNode (node_type "Stance") via cog_stance_*serialize.
|
||||
*
|
||||
* warp: axis_gain[] per-principal-axis multiplier on extents (which axes
|
||||
* matter — gain>1 WIDENS an axis so it penalizes less);
|
||||
* bias_dir[] a steering-direction seed in the region's frame;
|
||||
* scalars faculty constants this stance overrides (ext_floor, etc).
|
||||
* calibration: the track record — the ONLY thing the loop (§4) updates
|
||||
* besides warp: n_trials, a Brier accumulator, reliability
|
||||
* (→ GeoGradient.confidence), and an EMA error.
|
||||
* keystone: if set, the correspondence-loop MUST NEVER write warp or
|
||||
* calibration — read-mostly (self / values). §6 metastability.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct {
|
||||
char* id; /* stance node id (owned) */
|
||||
char* faculty; /* the act this stance serves: "induce"|"relate"|... */
|
||||
char* anchor_region; /* node/neighborhood id this stance is attached to */
|
||||
char* for_whom; /* observer id — grounding is relational (NULL=global) */
|
||||
int keystone; /* 1 = read-mostly, loop never writes it (§6) */
|
||||
|
||||
int dim; /* embedding dim of the region */
|
||||
int n_axes; /* how many axis_gain entries are live (<= COG_MAX_AXES)*/
|
||||
double axis_gain[COG_MAX_AXES]; /* per-axis extent multipliers (init 1.0) */
|
||||
float* bias_dir; /* dim floats, steering seed (owned; NULL = none) */
|
||||
double ext_floor; /* faculty scalar: the extent floor (init 1.0) */
|
||||
double drop_frac; /* faculty scalar (causal): confound drop (init 0.5) */
|
||||
double assoc_floor; /* faculty scalar (causal): assoc floor (init 0.2) */
|
||||
|
||||
/* calibration / track record */
|
||||
int64_t n_trials;
|
||||
double brier_sum; /* Σ (p − y)² */
|
||||
double reliability; /* calibrated ∈[0,1] → GeoGradient.confidence */
|
||||
double ema_error; /* EMA of per-trial error */
|
||||
double last_error;
|
||||
} CogStance;
|
||||
|
||||
/* Initialize a neutral stance (all gains 1.0, default scalars, reliability 0.5).
|
||||
* dim/n_axes taken from the region descriptor. faculty/id/for_whom are copied. */
|
||||
int cog_stance_init(CogStance* s, const char* id, const char* faculty,
|
||||
const char* anchor_region, const char* for_whom,
|
||||
const GeoDescriptor* region);
|
||||
void cog_stance_free(CogStance* s);
|
||||
|
||||
/* A stance set to today's hard-coded constants == behavioral parity with the
|
||||
* pre-stance operators (axis_gain all 1.0, ext_floor default, drop_frac 0.5,
|
||||
* assoc_floor 0.2). This is the FROZEN CONTROL used by the validation. */
|
||||
void cog_stance_set_frozen_defaults(CogStance* s);
|
||||
|
||||
/* ── Serialization: Stance <-> StoreNode (compact line schema "STNC1", mirroring
|
||||
* the reify "GEO1" precedent). Additive; the node's importance field caches the
|
||||
* reliability readout. Round-trips exactly (reboot-prove). ──────────────────── */
|
||||
char* cog_stance_to_metadata(const CogStance* s); /* owned string */
|
||||
int cog_stance_to_node(const CogStance* s, StoreNode* out);/* fills a StoreNode */
|
||||
int cog_stance_from_node(const StoreNode* n, CogStance* out);/* parse STNC1 */
|
||||
|
||||
#define COG_STANCE_NODE_TYPE "Stance"
|
||||
#define COG_STANCE_META_MAGIC "STNC1"
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* §1.2 think — the ONE operation. Frozen procedure over three steps:
|
||||
* 1. re-origin on the anchor point (the vantage; the manifold is the read
|
||||
* neighborhood, passed as `region`);
|
||||
* 2. fit the anchor under the stance's WARP (engram_reason_point_fit with the
|
||||
* axis extents multiplied by axis_gain and ext_floor substituted);
|
||||
* 3. emit a GRADIENT: direction = the warped steepest-descent that reduces the
|
||||
* fit distance (the "which way pays off" seed + bias_dir), spread from the
|
||||
* fit distance, confidence from the stance's reliability, magnitude = the
|
||||
* read's membership estimate. NO point-collapse — that is expression.
|
||||
*
|
||||
* `region` — the read neighborhood (built by vantage_read / geometry descriptor).
|
||||
* `anchor` — the point to read FROM (dim floats). NULL = region centroid (self).
|
||||
* `stance` — the steering prior. NULL = neutral (frozen defaults) => parity.
|
||||
* Returns 0 and fills `out` (engram_gradient_free), <0 on error.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
int engram_think(const GeoDescriptor* region, const float* anchor,
|
||||
const CogStance* stance, GeoGradient* out);
|
||||
|
||||
/* The warped fit itself (step 2), exposed for the loop + verifier reuse. Identical
|
||||
* to engram_reason_point_fit when stance==NULL or all gains==1 && ext_floor default. */
|
||||
int cog_warped_fit(const GeoDescriptor* region, const float* x,
|
||||
const CogStance* stance, GeoFit* out);
|
||||
|
||||
/* EXPRESSION — the ONLY place a gradient collapses to a point. Samples the gradient
|
||||
* off the anchor along its steering direction, scaled by (1 − spread) so a spiked
|
||||
* (confident) gradient lands a definite point and a diffuse one barely moves.
|
||||
* This is deliberately a SEPARATE faculty from think (§1.2, M5). */
|
||||
int engram_express(const GeoGradient* g, const float* anchor, float* out_point);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* §5 HOLD vs GROUND vs ASSERT. Holding is unconditional (the store gates nothing).
|
||||
* Grounding is a RELATION — a "grounded-by" edge, probabilistic, grounded-for-whom.
|
||||
* The honesty floor is checked only at ASSERTION.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
#define COG_GROUNDED_BY_RELATION "grounded-by"
|
||||
#define COG_SALIENT_TO_RELATION "salient-to"
|
||||
|
||||
/* Write a grounded-by edge (additive). weight = grounding ∈(0,1] from the verifier;
|
||||
* for_whom recorded in edge metadata (grounding is relational). Never a node flag. */
|
||||
int cog_ground_edge(EngramPagedStore* s, const char* claim_id,
|
||||
const char* evidence_id, double grounding, const char* for_whom);
|
||||
|
||||
/* Write/refresh a salient-to edge: salience is RELATIONAL (grounded-for-whom),
|
||||
* carried on the edge to the observer — not baked into the node scalar (§2.1). */
|
||||
int cog_salient_edge(EngramPagedStore* s, const char* node_id,
|
||||
const char* observer_id, double salience);
|
||||
|
||||
/* The honesty floor — a QUERY at assertion time, NOT a schema constraint. Reads the
|
||||
* claim's stored grounded-by edges (for the given observer) and returns:
|
||||
* 1 = may assert (best grounding >= floor),
|
||||
* 0 = REFUSE assertion (holds unconditionally; only asserting is gated),
|
||||
* <0 = error. The content remains held either way. */
|
||||
int cog_assert_gate(EngramPagedStore* s, const char* claim_id,
|
||||
const char* for_whom, double floor);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* §4 THE REFLEXIVE CORRESPONDENCE-LOOP — the learning engine. think scores its
|
||||
* OWN gradient against outcome, refines the stance on the error, and (optionally)
|
||||
* writes the (gradient, outcome, error) back as self-describing geometry. This is
|
||||
* the dormant verifier turned INWARD.
|
||||
*
|
||||
* grade(1) SELF-CONSISTENCY (no external world-labels): the outcome is what the
|
||||
* geometry itself says — the membership determined by the region's SIGNAL subspace
|
||||
* (the axes reality actually weights). The stance's cheap warped read is graded
|
||||
* against that geometric truth; error refines the warp so the read corresponds.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct {
|
||||
double correspondence; /* ∈[0,1]: 1 − |p − y| for this trial */
|
||||
double error; /* 1 − correspondence */
|
||||
double brier; /* running mean (p − y)² across the stance's trials */
|
||||
double reliability; /* the stance's current calibrated reliability */
|
||||
int wrote_keystone; /* 1 iff a keystone update was BLOCKED (safety audit) */
|
||||
} CogBeatResult;
|
||||
|
||||
/* One correspondence beat for ONE trial:
|
||||
* think(region, anchor, stance) -> gradient (a PREDICTION, ungrounded)
|
||||
* outcome y := grade-1 self-consistency target (in [0,1])
|
||||
* error = |magnitude − y|; refine stance.warp + calibration on the error
|
||||
* (bounded step; NEVER writes a keystone stance)
|
||||
* `learn`==0 grades WITHOUT updating (the frozen-control path). `max_step` bounds
|
||||
* the per-beat warp change (metastability; §6). Returns 0 / <0. */
|
||||
int engram_correspondence_beat(const GeoDescriptor* region, const float* anchor,
|
||||
double outcome_y, CogStance* stance,
|
||||
int learn, double max_step, CogBeatResult* out);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* §6 METASTABILITY. Keystones (self/values) are read-mostly: the loop reads but
|
||||
* never writes them. Mark by stance flag or by a keystone-id set the loop consults.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct { const char** ids; int n; } CogKeystoneSet;
|
||||
int cog_is_keystone(const CogKeystoneSet* ks, const CogStance* s);
|
||||
|
||||
#endif /* ENGRAM_COGNITION_H */
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,449 @@
|
||||
/* engram_geometry.h — M9 FOUNDATION: the relational-neighborhood GEOMETRY
|
||||
* DESCRIPTOR (design doc §3, §5; memory node e94371bd).
|
||||
*
|
||||
* Computes, for a relational neighborhood grown from a seed set, the compact
|
||||
* (KB-not-MB) joint geometry Will specified: the SEMANTIC geometry (centroid,
|
||||
* covariance / principal axes, radius) braided with the RELATIONAL geometry
|
||||
* (k-core skeleton, hub->periphery centrality gradient), plus soft membership.
|
||||
*
|
||||
* Two coordinate systems, one shape — "a constellation: bright prototype at the
|
||||
* center, a cloud of members at varying distance, the strongest edges as a
|
||||
* backbone, fading at the edges."
|
||||
*
|
||||
* Built ON the two standalone M-era modules only:
|
||||
* - engram_vindex : semantic neighbors (the cloud) via ANN.
|
||||
* - engram_store : node embeddings + hebb adjacency (the skeleton), read-only.
|
||||
* It does NOT link or touch el_runtime.c, and it is a pure READ over the graph:
|
||||
* it never modifies nodes, edges, activation, the index, or any retrieval path.
|
||||
*
|
||||
* Pure C11, stdlib + libm only. The descriptor is a foundation object; it is NOT
|
||||
* wired into retrieval/priming yet (that is the next M9 step).
|
||||
*/
|
||||
#ifndef ENGRAM_GEOMETRY_H
|
||||
#define ENGRAM_GEOMETRY_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "engram_store.h"
|
||||
#include "engram_vindex.h"
|
||||
|
||||
/* One member of the neighborhood + its place in the gradient. */
|
||||
typedef struct {
|
||||
char* id;
|
||||
double membership; /* soft membership in [0,1] (semantic+relational blend) */
|
||||
double centrality; /* skeleton weighted-degree — relational salience */
|
||||
double salience; /* the node's own stored salience */
|
||||
int core; /* k-core number (0 = fringe / not in any core) */
|
||||
double dist_centroid; /* cosine distance of member emb to centroid (semantic)*/
|
||||
int embedded; /* 1 if the member carried an emb vector */
|
||||
} GeoMember;
|
||||
|
||||
/* One skeleton edge (indices into members[]). eff_weight = weight*(1+0.5*hebb),
|
||||
* clamped to 1.0 — the effective propagation strength eg_edge_eff_weight uses. */
|
||||
typedef struct { uint32_t a, b; double eff_weight; double hebb; } GeoEdge;
|
||||
|
||||
/* A compact principal axis of the ellipsoid: unit direction in R^dim + extent
|
||||
* (sqrt of the covariance eigenvalue = the ellipsoid's half-width along it). */
|
||||
typedef struct { float* axis; double extent; } GeoAxis;
|
||||
|
||||
typedef struct {
|
||||
int dim;
|
||||
/* ── anchor ── */
|
||||
char* hub_id; /* highest-centrality member: the relational hub */
|
||||
float* centroid; /* v̄ ∈ R^dim: mean of the member embeddings in the
|
||||
* frame the descriptor operated in. When centered
|
||||
* (global_mean != NULL) this is the CENTERED
|
||||
* centroid (mean of L2-normalized embs minus the
|
||||
* global mean): the neighborhood's location in the
|
||||
* isotropic/whitened frame. Add global_mean back to
|
||||
* recover the raw prototype point. When uncentered
|
||||
* it is the raw mean of L2-normalized member embs. */
|
||||
float* global_mean; /* the centering offset actually applied (dim floats),
|
||||
* or NULL if the descriptor ran in raw space. The §5
|
||||
* operators (distance/overlap/Wasserstein) are only
|
||||
* discriminative in the centered frame — see notes. */
|
||||
/* ── shape (compact covariance): top principal axes + extents ── */
|
||||
int n_axes;
|
||||
GeoAxis* axes; /* orientation + extents of the ellipsoid */
|
||||
double total_variance; /* trace(Σ) = mean squared member dist to centroid*/
|
||||
/* ── scale ── */
|
||||
double radius; /* sqrt(total_variance) — the neighborhood breadth*/
|
||||
/* ── members + gradient ── */
|
||||
int n_members;
|
||||
GeoMember* members; /* soft membership {id->weight} + centrality/salience */
|
||||
/* ── skeleton ── */
|
||||
int n_edges;
|
||||
GeoEdge* edges; /* strong internal hebb edges = the backbone */
|
||||
int k_core; /* the maximum core number present in the skeleton*/
|
||||
/* ── diagnostics ── */
|
||||
double co_registration;/* corr(hebb strength, semantic proximity) over */
|
||||
/* internal edges: >0 = geometries agree (reify); */
|
||||
/* <0 = disagree (surprising links / dream cands). */
|
||||
int n_embedded; /* members that carried an emb vector */
|
||||
} GeoDescriptor;
|
||||
|
||||
typedef struct {
|
||||
int ann_k; /* semantic expansion: ANN neighbors per seed (0=off) */
|
||||
int hop_relational; /* 1 = include seeds' hebb neighbors as members */
|
||||
double edge_min_weight; /* skeleton: ignore internal edges below this eff wt */
|
||||
int kcore_k; /* target k for the reported k-core (0 = auto/max) */
|
||||
int top_axes; /* principal axes to retain (default 8) */
|
||||
int max_members; /* cap neighborhood size (guards the eigensolve cost) */
|
||||
} GeoParams;
|
||||
|
||||
/* Fill p with sane defaults: ann_k=24, hop_relational=1, edge_min_weight=0.05,
|
||||
* kcore_k=0 (auto), top_axes=8, max_members=400. */
|
||||
void engram_geo_default_params(GeoParams* p);
|
||||
|
||||
/* ── Global-mean cache (mean-centering / whitening the anisotropic emb space) ──
|
||||
* The nomic-embed-text space over the engram corpus is strongly ANISOTROPIC:
|
||||
* every embedding sits in a narrow cone (mean pairwise cosine ~0.55), which
|
||||
* compresses cosine-based domain separation almost to nothing. Subtracting the
|
||||
* GLOBAL MEAN of the (L2-normalized) embeddings recenters the cloud on the
|
||||
* origin (mean pairwise cosine -> ~0), restoring isotropy so the §5 operators
|
||||
* discriminate. The mean is a store-level derived quantity, like the ANN index:
|
||||
* built once from the paged store, cached, and refreshed when the embedded set
|
||||
* drifts. It lives here (not in the store) so this stays a contained, read-only
|
||||
* addition; a runtime owns one GeoMeanCache per open store alongside its VIndex. */
|
||||
typedef struct GeoMeanCache GeoMeanCache;
|
||||
|
||||
/* Scan every live node in `store` and compute the mean of the L2-normalized
|
||||
* embeddings over the embed-eligible set (nodes carrying an emb vector; the
|
||||
* unembedded telemetry/system nodes are skipped). Returns a malloc'd cache, or
|
||||
* NULL on error / no embedded nodes. The offset vector is NOT renormalized — it
|
||||
* is a translation, applied by subtraction. */
|
||||
GeoMeanCache* engram_geo_mean_build(EngramPagedStore* store);
|
||||
|
||||
/* The cached offset (dim floats) — pass to engram_geometry_descriptor as
|
||||
* global_mean. Valid until the cache is freed/refreshed. */
|
||||
const float* engram_geo_mean_vec(const GeoMeanCache* c);
|
||||
int engram_geo_mean_dim(const GeoMeanCache* c);
|
||||
uint64_t engram_geo_mean_count(const GeoMeanCache* c); /* #embedded nodes used */
|
||||
|
||||
/* Recompute the mean IN PLACE iff the embedded-node count has drifted by more
|
||||
* than `frac` (e.g. 0.10 = 10%) since the cache was built — "recompute on
|
||||
* significant change". Returns 1 if it rebuilt, 0 if unchanged, <0 on error. */
|
||||
int engram_geo_mean_maybe_refresh(GeoMeanCache* c, EngramPagedStore* store,
|
||||
double frac);
|
||||
|
||||
void engram_geo_mean_free(GeoMeanCache* c);
|
||||
|
||||
/* Compute the geometry descriptor of the neighborhood grown from seed_ids.
|
||||
* READ-ONLY over store + vindex.
|
||||
* store — an opened store (borrowed; not modified).
|
||||
* vindex — optional ANN index for semantic expansion; NULL disables it.
|
||||
* vids — the ordinal->store-id map returned by vindex_build_from_store
|
||||
* (vids[node_id] == store id). Required iff vindex != NULL.
|
||||
* n_vids — length of vids.
|
||||
* params — NULL to use engram_geo_default_params.
|
||||
* global_mean — optional centering offset (dim floats, from engram_geo_mean_*).
|
||||
* When non-NULL the SEMANTIC geometry is computed in mean-centered
|
||||
* (isotropic) space: every normalized member emb has global_mean
|
||||
* subtracted before the centroid / cosine-distance / co-registration
|
||||
* math, so those operators discriminate. NULL = raw space (legacy).
|
||||
* NOTE: the ANN neighbor query still runs in RAW unit-vector space —
|
||||
* centering is a rigid translation that ~preserves neighborhood
|
||||
* MEMBERSHIP, so the index needs no rebuild; only the descriptor
|
||||
* STATISTICS move to the centered frame (co-registration choice (b)).
|
||||
* The eigen/covariance shape (axes, radius) is translation-invariant
|
||||
* and therefore identical in either frame.
|
||||
* Returns a malloc'd descriptor (free with engram_geo_free), or NULL on error
|
||||
* (no seeds resolvable, OOM). */
|
||||
GeoDescriptor* engram_geometry_descriptor(
|
||||
EngramPagedStore* store, VIndex* vindex,
|
||||
char** vids, int n_vids,
|
||||
const char* const* seed_ids, size_t n_seeds,
|
||||
const GeoParams* params,
|
||||
const float* global_mean);
|
||||
|
||||
void engram_geo_free(GeoDescriptor* g);
|
||||
|
||||
/* ── M-INTEROCEPTION P3: drift-sensor primitive (descriptor displacement) ────
|
||||
* Read-only. GROWTH vs CORRUPTION split of how far B drifted from baseline A.
|
||||
* See engram_geometry.c for the honesty note on the missing SelfAnchor. */
|
||||
typedef struct {
|
||||
double centroid_sep; /* L2 distance between centroids (same frame) */
|
||||
double centroid_cos; /* 1 - cosine(centroidA, centroidB) */
|
||||
double radius_delta; /* |radiusA - radiusB| — neighborhood scale change */
|
||||
double core_disp; /* mean radial displacement of the invariant core */
|
||||
double periph_disp; /* mean radial displacement of the periphery */
|
||||
int core_matched; /* # core members matched by id across A,B */
|
||||
int periph_matched; /* # periphery members matched by id across A,B */
|
||||
} GeoDisplacement;
|
||||
|
||||
void engram_geo_displacement(const GeoDescriptor* a, const GeoDescriptor* b,
|
||||
double core_frac, GeoDisplacement* out);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* §5 GEOMETRY OPERATORS — a relational ALGEBRA over neighborhood descriptors.
|
||||
* These are the reusable primitives Will specified: "primitives any CGI
|
||||
* application should be able to use." READ-ONLY and PURE (stdlib + libm only) —
|
||||
* they consume GeoDescriptor(s) and never touch the store, index, or activation.
|
||||
*
|
||||
* FRAME CONTRACT: both inputs MUST have been built in the SAME frame — identical
|
||||
* emb `dim` and identical `global_mean` (centered against the one true store-wide
|
||||
* mean). The reify path builds every neighborhood that way, so descriptors are
|
||||
* directly comparable. An operator returns <0 / NULL if the dims disagree.
|
||||
*
|
||||
* REPRESENTATION: the C descriptor lives in the FULL emb dim with a LOW-RANK
|
||||
* covariance Σ = Σ_k extent_k² · a_k a_kᵀ over its retained principal axes
|
||||
* (top_axes; the discarded tail variance is not modeled). Every operator mirrors
|
||||
* the viz-proxy (engram-geometry-proxy.py §5) FORMULA exactly, but evaluates it on
|
||||
* this representation — so semantics match the proxy while absolute numbers differ
|
||||
* (proxy works in a 24-dim global-PCA reduced dense frame; C in full-dim low-rank).
|
||||
* The Wasserstein / combine eigen-work is done inside the small JOINT axis subspace
|
||||
* (dimension ≤ nA+nB+1), which is EXACT for the low-rank covariances there.
|
||||
* Each result struct is released by its engram_geo_*_free.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
|
||||
/* overlap(A,B): shared-member set + Jaccard + centroid/scale proximity score. */
|
||||
typedef struct {
|
||||
char** shared_ids; /* ids present in BOTH neighborhoods (owned) */
|
||||
int n_shared;
|
||||
int n_union; /* |A ∪ B| by id */
|
||||
double jaccard; /* |A∩B| / |A∪B| */
|
||||
double centroid_distance; /* L2 between the (centered) centroids */
|
||||
double overlap_score; /* jacc*0.5 + max(0,1−d/(rA+rB))*0.5 (proxy form)*/
|
||||
float* intersection_centroid; /* midpoint of the two centroids (dim, owned) */
|
||||
int dim;
|
||||
} GeoOverlap;
|
||||
int engram_geo_overlap(const GeoDescriptor* a, const GeoDescriptor* b, GeoOverlap* out);
|
||||
void engram_geo_overlap_free(GeoOverlap* o);
|
||||
|
||||
/* subtract(A,B) — ORTHOGONAL-COMPLEMENT residual: project A onto I − V_B V_Bᵀ
|
||||
* (V_B = B's top `b_dims` principal axes) — "A with B's framing removed". Returns
|
||||
* A's residual centroid + residual ellipsoid, the fraction of A's energy that lives
|
||||
* inside B's subspace, and the centroid-difference vector. b_dims<=0 → min(3,nB). */
|
||||
typedef struct {
|
||||
int dim;
|
||||
float* residual_centroid; /* P⊥ c_A (owned) */
|
||||
float* centroid_diff; /* c_A − c_B (owned) */
|
||||
double centroid_diff_mag;
|
||||
double variance_explained_by_B; /* (‖Qc_A‖²+Tr(QΣ_A)) / (‖c_A‖²+Tr Σ_A) ∈[0,1]*/
|
||||
int removed_dims; /* # of B axes used as V_B */
|
||||
double residual_scale; /* sqrt(Tr(P⊥ Σ_A P⊥)) */
|
||||
int n_axes; /* residual principal axes (owned) */
|
||||
GeoAxis* axes;
|
||||
} GeoResidual;
|
||||
int engram_geo_subtract(const GeoDescriptor* a, const GeoDescriptor* b,
|
||||
int b_dims, GeoResidual* out);
|
||||
void engram_geo_residual_free(GeoResidual* r);
|
||||
|
||||
/* set-diff variant of subtract: members in A but not in B + the centroid arrow. */
|
||||
typedef struct {
|
||||
char** only_ids; /* member ids in A and not in B (owned) */
|
||||
int n_only;
|
||||
int removed; /* |A ∩ B| (dropped) */
|
||||
float* centroid_diff; /* c_A − c_B (dim, owned) */
|
||||
double centroid_diff_mag;
|
||||
int dim;
|
||||
} GeoSetDiff;
|
||||
int engram_geo_setdiff(const GeoDescriptor* a, const GeoDescriptor* b, GeoSetDiff* out);
|
||||
void engram_geo_setdiff_free(GeoSetDiff* s);
|
||||
|
||||
/* combine(A,B): a merged descriptor — POOLED centroid + POOLED covariance
|
||||
* (exact law-of-total-variance: the covariance you'd get by concatenating the two
|
||||
* member clouds), re-eigendecomposed for its principal axes. Members = id-union
|
||||
* (membership = max). top_axes<=0 → 8. Returns a malloc'd GeoDescriptor (free with
|
||||
* engram_geo_free) in the same frame as A, or NULL on error. */
|
||||
GeoDescriptor* engram_geo_combine(const GeoDescriptor* a, const GeoDescriptor* b,
|
||||
int top_axes);
|
||||
|
||||
/* distance(A,B): centroid L2 + centroid cosine + closed-form Wasserstein-2
|
||||
* (Bures metric) between the two Gaussians — mirrors the proxy's _wasserstein2. */
|
||||
typedef struct {
|
||||
double centroid_distance;
|
||||
double centroid_cosine;
|
||||
double wasserstein2;
|
||||
int dim;
|
||||
} GeoDistance;
|
||||
int engram_geo_distance(const GeoDescriptor* a, const GeoDescriptor* b, GeoDistance* out);
|
||||
|
||||
/* analogy(A,B): orthogonal PROCRUSTES transform min_R ‖A − B R‖_F, RᵀR=I (SVD)
|
||||
* aligning A's principal frame to B's (extent-scaled axes, paired by rank). R is
|
||||
* returned COMPACTLY as an r×r rotation within the joint axis subspace `basis`
|
||||
* (r vectors of dim floats); it acts as the identity on the orthogonal complement.
|
||||
* Apply it to a vector with engram_geo_analogy_apply. */
|
||||
typedef struct {
|
||||
int dim;
|
||||
int r; /* subspace rank; R is r×r */
|
||||
float* basis; /* r×dim row-major orthonormal basis Q (owned) */
|
||||
double* R; /* r×r rotation in Q-coords, row-major (owned) */
|
||||
double residual; /* ‖A − B R‖_F over the extent-scaled frames */
|
||||
} GeoAnalogy;
|
||||
int engram_geo_analogy(const GeoDescriptor* a, const GeoDescriptor* b, GeoAnalogy* out);
|
||||
/* out_vec = R·v for v ∈ R^dim: v + Σ_i (R̂c − c)_i q_i, c_i = q_i·v. dim floats. */
|
||||
void engram_geo_analogy_apply(const GeoAnalogy* an, const float* v, float* out_vec);
|
||||
void engram_geo_analogy_free(GeoAnalogy* an);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* M10 — REIFICATION: densely co-wired relational neighborhoods crystallized into
|
||||
* FIRST-CLASS, PERSISTED store records (design doc §2; memory 885f5945). This is
|
||||
* NOT a cache — it is durable structure. A reified neighborhood is a real store
|
||||
* NODE (node_type "Neighborhood") that survives restart, is loaded on boot, and
|
||||
* EVOLVES via supersede+provenance when the pattern shifts. The geometry-priming
|
||||
* HOT PATH reads these persisted records (never computes geometry on the
|
||||
* activation path). Ad-hoc/transient geometries still use the on-the-fly
|
||||
* engram_geometry_descriptor above.
|
||||
*
|
||||
* Two record types, both ordinary TLV store nodes (no new on-disk format):
|
||||
* - "GeoMeanFrame" : the store-wide centering mean, persisted ONCE (emb = mean
|
||||
* vector, id ENGRAM_GEO_MEANFRAME_ID). Referenced by every
|
||||
* neighborhood so priming centers against the SAME true mean.
|
||||
* - "Neighborhood" : one reified neighborhood. emb = the RAW centroid (prototype
|
||||
* point, so it stays centroid-ANN-able; centered_centroid =
|
||||
* emb - meanframe). metadata = the compact "GEO1" schema:
|
||||
* hub id, meanframe ref, scalar shape (radius, total_variance,
|
||||
* k_core, co_registration, n_embedded), axis EXTENTS (ellipsoid
|
||||
* half-widths), and the MEMBER list {id -> membership, centrality,
|
||||
* core}. Member links are also persisted as edges relation="member".
|
||||
*
|
||||
* v1 honest simplifications (documented; extensible without migration): axis
|
||||
* DIRECTION vectors are not persisted (extents capture the ellipsoid scale; the
|
||||
* directions are recomputable via the on-the-fly descriptor for viz/operators);
|
||||
* with hebb potentiation ~0 on today's store the "hebb-weighted" degree reduces to
|
||||
* AUTHORED edge weight, so detected neighborhoods currently reflect authored edges —
|
||||
* the design is unchanged and self-correcting once hebb accrues.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
|
||||
#define ENGRAM_GEO_NBHD_TYPE "Neighborhood"
|
||||
#define ENGRAM_GEO_MEANFRAME_TYPE "GeoMeanFrame"
|
||||
#define ENGRAM_GEO_MEANFRAME_ID "geo-meanframe" /* stable id of the singleton */
|
||||
#define ENGRAM_GEO_NBHD_ID_PREFIX "nbhd-" /* id = nbhd-<hub>-<built_at> */
|
||||
#define ENGRAM_GEO_MEMBER_RELATION "member"
|
||||
/* ── One-level nesting (containment DAG). A "super" neighborhood is itself a
|
||||
* Neighborhood node whose GEO1 metadata carries `level 1` + `c <child_id>` lines
|
||||
* and which is joined to each child by a "contains" edge (child→parent
|
||||
* "nested-in"). Its id also begins with the "nbhd-" prefix, so the boot path
|
||||
* routes it into the resident reify index and skips its edges from activation
|
||||
* adjacency, exactly like a flat neighborhood. ──────────────────────────────── */
|
||||
#define ENGRAM_GEO_SUPER_ID_PREFIX "nbhd-super-"
|
||||
#define ENGRAM_GEO_SUPER_CONTENT "reified-super-neighborhood"
|
||||
#define ENGRAM_GEO_CONTAINS_RELATION "contains"
|
||||
#define ENGRAM_GEO_NESTED_RELATION "nested-in"
|
||||
|
||||
/* Per-run counters for the on-beat self-reification operation. All fields are
|
||||
* out-params filled by engram_geo_reify_store when GeoReifyParams.stats != NULL.
|
||||
* reified — neighborhoods WRITTEN this run (new or materially changed hubs)
|
||||
* skipped — hubs whose signature was UNCHANGED vs their live neighborhood
|
||||
* (the convergence signal: on a settled store this trends to the
|
||||
* hub count and `reified` trends to 0 → zero appends per beat)
|
||||
* superseded — prior neighborhood records tombstoned into the residue chain
|
||||
* member_edges — relation="member" edges written this run */
|
||||
typedef struct {
|
||||
int reified;
|
||||
int skipped;
|
||||
int superseded;
|
||||
int member_edges;
|
||||
} GeoReifyStats;
|
||||
|
||||
typedef struct {
|
||||
int min_weighted_degree; /* hub qualifies iff strong-edge weighted degree >= this
|
||||
* (0 = no floor: just rank + take top max_neighborhoods) */
|
||||
int max_neighborhoods; /* homeostatic budget cap (default 128) */
|
||||
double cover_membership; /* skip a hub already a member (w>=this) of an accepted
|
||||
* neighborhood — greedy non-redundant cover (default 0.5) */
|
||||
int persist_member_edges; /* 1 = also write relation="member" edges (default 1) */
|
||||
GeoParams descriptor; /* per-neighborhood params (top_axes may be 0 = skip eigensolve) */
|
||||
|
||||
/* ── SELF-REIFICATION extensions (default 0/NULL = legacy behavior) ──────────
|
||||
* When these are off, engram_geo_reify_store is byte-for-byte its pre-2026-08-14
|
||||
* behavior — the ENGRAM_SELF_REIFY gate keeps the live binary inert until set. */
|
||||
int incremental; /* 1 = CHANGE-DETECTION: skip a hub whose neighborhood
|
||||
* signature (member-set + memberships + coarse geometry)
|
||||
* is unchanged vs its current live record — no re-append,
|
||||
* no supersede. This is what makes on-beat reification
|
||||
* idempotent/convergent under the write-barrier. */
|
||||
int grounded_name; /* 1 = NAME the neighborhood from its most-central member
|
||||
* labels (grounded, provenance-stamped) instead of the
|
||||
* fixed content "reified-neighborhood". */
|
||||
const char* cause; /* supersession CAUSE tag written into the residue chain
|
||||
* ("autonomous-drift" on the beat, "explicit-override" /
|
||||
* "rename" for the async manual override). NULL = "reify". */
|
||||
GeoReifyStats* stats; /* nullable: per-run counters (see above). */
|
||||
} GeoReifyParams;
|
||||
|
||||
/* Defaults: min_weighted_degree=0, max_neighborhoods=128, cover_membership=0.5,
|
||||
* persist_member_edges=1, descriptor = engram_geo_default_params but top_axes=4,
|
||||
* max_members=256 (reified neighborhoods stay compact). */
|
||||
void engram_geo_reify_default_params(GeoReifyParams* p);
|
||||
|
||||
/* WRITE PATH (offline / consolidation — NEVER the activation hot path).
|
||||
* Detect dense hub neighborhoods on the hebb-weighted graph, compute each one's
|
||||
* CENTERED descriptor ONCE against the true store-wide mean, and PERSIST them as
|
||||
* first-class records: the GeoMeanFrame (once) + one Neighborhood node per detected
|
||||
* neighborhood (+ member edges), superseding any prior same-hub record with
|
||||
* provenance. Read-then-write over `store`. Returns #neighborhoods persisted, or <0.
|
||||
* Skips existing Neighborhood/GeoMeanFrame nodes when detecting (idempotent re-reify). */
|
||||
int engram_geo_reify_store(EngramPagedStore* store, VIndex* vindex,
|
||||
char** vids, int n_vids,
|
||||
const GeoReifyParams* params);
|
||||
|
||||
/* NESTING (one level). Reads the already-persisted flat Neighborhood records,
|
||||
* agglomerates them by centroid cosine >= `min_cos` into groups, and persists one
|
||||
* PARENT "super" Neighborhood node per group of >= 2 (geometry = mean of child
|
||||
* centroids; `contains`/`nested-in` edges to children). Tombstones prior super
|
||||
* records first (idempotent). Returns #parents persisted, or <0. Run AFTER
|
||||
* engram_geo_reify_store. `min_cos` <= 0 uses the default (0.30). */
|
||||
int engram_geo_reify_nest(EngramPagedStore* store, double min_cos);
|
||||
|
||||
/* ASYNC EXPLICIT OVERRIDE (degenerate manual case). Rename the live neighborhood
|
||||
* `nbhd_id` to `new_name`: writes a fresh superseding Neighborhood record that
|
||||
* carries the SAME geometry + members but the new name, tombstones the prior
|
||||
* record, and PREPENDS a residue entry (cause="explicit-override", the prior
|
||||
* name) so the maturation trail is preserved. Never blocks the autonomous beat;
|
||||
* it simply supersedes whatever the beat last wrote. Returns the new record id
|
||||
* (caller frees) or NULL on failure (id not a live neighborhood). */
|
||||
char* engram_geo_neighborhood_rename(EngramPagedStore* store,
|
||||
const char* nbhd_id, const char* new_name);
|
||||
|
||||
/* ── Resident loaded form of the persisted records (boot-time; READ-ONLY) ─────
|
||||
* The durable Neighborhood/GeoMeanFrame records are the source of truth; this
|
||||
* index is their LOADED form (like the resident node array is the loaded form of
|
||||
* the node records, or adjacency the loaded form of edges). It never recomputes
|
||||
* geometry — it parses. Build it by feeding the runtime's boot node scan, or in
|
||||
* one pass with engram_geo_reify_load. */
|
||||
typedef struct GeoReifyIndex GeoReifyIndex;
|
||||
|
||||
GeoReifyIndex* engram_geo_reify_index_new(void);
|
||||
/* Feed one store node; if it is a Neighborhood or GeoMeanFrame record it is parsed
|
||||
* and absorbed (else ignored). The node is BORROWED (copied as needed). 0/<0. */
|
||||
int engram_geo_reify_index_add(GeoReifyIndex* ix, const StoreNode* n);
|
||||
/* Build the member->neighborhood hash after all adds. Call once. 0/<0. */
|
||||
int engram_geo_reify_index_finalize(GeoReifyIndex* ix);
|
||||
/* One-pass convenience: scan the store and build the finalized index. NULL if the
|
||||
* store holds no reified records. */
|
||||
GeoReifyIndex* engram_geo_reify_load(EngramPagedStore* store);
|
||||
|
||||
/* A borrowed view of one persisted neighborhood (owned by the index). */
|
||||
typedef struct {
|
||||
const char* id;
|
||||
const char* hub_id;
|
||||
int n_members;
|
||||
char* const* member_ids; /* parallel arrays, length n_members */
|
||||
const double* member_w; /* membership in [0,1] */
|
||||
double radius;
|
||||
double co_registration;
|
||||
int k_core;
|
||||
int n_embedded;
|
||||
} GeoNeighborhood;
|
||||
|
||||
/* HOT-PATH LOOKUP (no geometry compute): resolve the seed set to the best
|
||||
* persisted neighborhood — the one with the greatest summed seed membership; on a
|
||||
* miss (no seed is a member of any neighborhood) fall back to the centroid nearest
|
||||
* the query embedding (centered by the loaded mean frame). q_emb may be NULL (then
|
||||
* a miss returns NULL). Returns a BORROWED handle (do NOT free) or NULL. */
|
||||
const GeoNeighborhood* engram_geo_reify_lookup(
|
||||
const GeoReifyIndex* ix,
|
||||
const char* const* seed_ids, size_t n_seeds,
|
||||
const float* q_emb, int q_dim);
|
||||
|
||||
/* M10 read-only JSON serializers of the resident reify index (caller owns the
|
||||
* returned malloc'd string; get_cstr returns NULL when id is not found). */
|
||||
char* engram_geo_reify_list_cstr(const GeoReifyIndex* ix);
|
||||
char* engram_geo_reify_get_cstr(const GeoReifyIndex* ix, const char* id);
|
||||
int engram_geo_reify_count(const GeoReifyIndex* ix);
|
||||
const float* engram_geo_reify_mean(const GeoReifyIndex* ix, int* dim); /* loaded true mean or NULL */
|
||||
void engram_geo_reify_index_free(GeoReifyIndex* ix);
|
||||
|
||||
#endif /* ENGRAM_GEOMETRY_H */
|
||||
@@ -0,0 +1,287 @@
|
||||
/* engram_reason.c — the REASONING layer. Pure compositions over engram_geometry.h.
|
||||
* stdlib + libm only; READ-ONLY over its descriptor inputs; touches no store/index. */
|
||||
#include "engram_reason.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
/* ── small float-vector helpers ─────────────────────────────────────────────── */
|
||||
static double vdot(const float* a, const float* b, int dim) {
|
||||
double s = 0; for (int i = 0; i < dim; i++) s += (double)a[i] * (double)b[i]; return s;
|
||||
}
|
||||
static double vnorm(const float* a, int dim) { return sqrt(vdot(a, a, dim)); }
|
||||
static double vcos(const float* a, const float* b, int dim) {
|
||||
double na = vnorm(a, dim), nb = vnorm(b, dim);
|
||||
if (na < 1e-12 || nb < 1e-12) return 0.0; /* a null vector ⇒ no direction */
|
||||
double c = vdot(a, b, dim) / (na * nb);
|
||||
if (c > 1.0) c = 1.0; if (c < -1.0) c = -1.0;
|
||||
return c;
|
||||
}
|
||||
static double l2(const float* a, const float* b, int dim) {
|
||||
double s = 0; for (int i = 0; i < dim; i++) { double d = (double)a[i] - (double)b[i]; s += d * d; }
|
||||
return sqrt(s);
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════ SHARED — point-to-manifold FIT ══ */
|
||||
int engram_reason_point_fit(const GeoDescriptor* g, const float* x,
|
||||
double ext_floor, GeoFit* out) {
|
||||
if (!g || !x || !out || g->dim <= 0 || !g->centroid) return -1;
|
||||
if (!(ext_floor > 0)) ext_floor = 1.0;
|
||||
int dim = g->dim;
|
||||
/* residual r = x − centroid */
|
||||
double rr = 0; /* ‖r‖² */
|
||||
float* r = malloc((size_t)dim * sizeof(float));
|
||||
if (!r) return -1;
|
||||
for (int i = 0; i < dim; i++) { double d = (double)x[i] - (double)g->centroid[i]; r[i] = (float)d; rr += d * d; }
|
||||
double maha2 = 0, ss_in = 0; /* Mahalanobis² and in-subspace energy */
|
||||
for (int k = 0; k < g->n_axes; k++) {
|
||||
const float* ax = g->axes[k].axis; if (!ax) continue;
|
||||
double proj = vdot(r, ax, dim); /* axes are orthonormal directions */
|
||||
double den = g->axes[k].extent; if (den < ext_floor) den = ext_floor;
|
||||
maha2 += (proj / den) * (proj / den);
|
||||
ss_in += proj * proj;
|
||||
}
|
||||
double ortho2 = rr - ss_in; if (ortho2 < 0) ortho2 = 0; /* off-subspace energy */
|
||||
double dist2 = maha2 + ortho2 / (ext_floor * ext_floor);
|
||||
out->mahalanobis = sqrt(maha2);
|
||||
out->ortho_residual = sqrt(ortho2);
|
||||
out->distance = sqrt(dist2);
|
||||
out->score = 1.0 / (1.0 + dist2);
|
||||
free(r);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════ ANALOGY ════ */
|
||||
int engram_reason_analogy(const GeoDescriptor* A, const GeoDescriptor* B,
|
||||
const GeoDescriptor* C,
|
||||
const GeoDescriptor* const* candidates, int n_candidates,
|
||||
GeoAnalogyResult* out) {
|
||||
if (!A || !B || !C || !out) return -1;
|
||||
if (!A->centroid || !B->centroid || !C->centroid) return -1;
|
||||
int dim = A->dim;
|
||||
if (B->dim != dim || C->dim != dim) return -1;
|
||||
memset(out, 0, sizeof *out);
|
||||
out->dim = dim; out->best = -1;
|
||||
|
||||
/* Learn R_{A→B}. engram_geo_analogy(X,Y) yields R with apply(R, Y-axis) ≈ X-axis
|
||||
* (R maps Y's frame → X's frame); so R that maps A→B is engram_geo_analogy(B,A). */
|
||||
GeoAnalogy an;
|
||||
if (engram_geo_analogy(B, A, &an) != 0) return -1;
|
||||
out->analogy_residual = an.residual;
|
||||
|
||||
/* mapped = R·c_C + (c_B − R·c_A) : the A→B affine (rotation + residual shift). */
|
||||
float* RcA = malloc((size_t)dim * sizeof(float));
|
||||
float* RcC = malloc((size_t)dim * sizeof(float));
|
||||
out->mapped_point = malloc((size_t)dim * sizeof(float));
|
||||
if (!RcA || !RcC || !out->mapped_point) { free(RcA); free(RcC); free(out->mapped_point); out->mapped_point = NULL; engram_geo_analogy_free(&an); return -1; }
|
||||
engram_geo_analogy_apply(&an, A->centroid, RcA);
|
||||
engram_geo_analogy_apply(&an, C->centroid, RcC);
|
||||
for (int i = 0; i < dim; i++)
|
||||
out->mapped_point[i] = (float)((double)RcC[i] + ((double)B->centroid[i] - (double)RcA[i]));
|
||||
free(RcA); free(RcC);
|
||||
engram_geo_analogy_free(&an);
|
||||
|
||||
/* nearest candidate to the mapped point (centroid L2). */
|
||||
if (candidates && n_candidates > 0) {
|
||||
out->n_candidates = n_candidates;
|
||||
out->distances = malloc((size_t)n_candidates * sizeof(double));
|
||||
if (!out->distances) return -1;
|
||||
double best = -1; int bi = -1;
|
||||
for (int i = 0; i < n_candidates; i++) {
|
||||
const GeoDescriptor* cd = candidates[i];
|
||||
double d = (cd && cd->centroid && cd->dim == dim) ? l2(out->mapped_point, cd->centroid, dim) : INFINITY;
|
||||
out->distances[i] = d;
|
||||
if (bi < 0 || d < best) { best = d; bi = i; }
|
||||
}
|
||||
out->best = bi; out->best_distance = best;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
void engram_reason_analogy_free(GeoAnalogyResult* r) {
|
||||
if (!r) return;
|
||||
free(r->mapped_point); free(r->distances);
|
||||
r->mapped_point = NULL; r->distances = NULL;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════ INDUCTION ══ */
|
||||
int engram_reason_induce(const GeoDescriptor* const* examples, int n_examples,
|
||||
int top_axes, double ext_floor, GeoInduction* out) {
|
||||
if (!examples || n_examples < 1 || !out) return -1;
|
||||
if (top_axes <= 0) top_axes = 8;
|
||||
memset(out, 0, sizeof *out);
|
||||
|
||||
/* fold the examples left→right through the pooled-Gaussian combine. n==1 pools
|
||||
* the single example with itself (identical cov ⇒ same shape, id-union = itself). */
|
||||
GeoDescriptor* acc = engram_geo_combine(examples[0],
|
||||
examples[n_examples > 1 ? 1 : 0], top_axes);
|
||||
if (!acc) return -1;
|
||||
for (int i = 2; i < n_examples; i++) {
|
||||
GeoDescriptor* nxt = engram_geo_combine(acc, examples[i], top_axes);
|
||||
engram_geo_free(acc);
|
||||
if (!nxt) return -1;
|
||||
acc = nxt;
|
||||
}
|
||||
out->rule = acc;
|
||||
out->n_examples = n_examples;
|
||||
out->ext_floor = (ext_floor > 0) ? ext_floor
|
||||
: (acc->radius > 0 ? acc->radius * 0.25 : 1.0);
|
||||
return 0;
|
||||
}
|
||||
double engram_reason_membership(const GeoInduction* ind, const float* x) {
|
||||
if (!ind || !ind->rule || !x) return -1;
|
||||
GeoFit f;
|
||||
if (engram_reason_point_fit(ind->rule, x, ind->ext_floor, &f) != 0) return -1;
|
||||
return f.score;
|
||||
}
|
||||
void engram_reason_induction_free(GeoInduction* out) {
|
||||
if (!out) return;
|
||||
if (out->rule) engram_geo_free(out->rule);
|
||||
out->rule = NULL;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════ ABDUCTION ══ */
|
||||
int engram_reason_abduce(const float* obs, int dim,
|
||||
const GeoDescriptor* const* hypotheses, int n,
|
||||
double ext_floor, GeoAbduction* out) {
|
||||
if (!obs || !hypotheses || n < 1 || dim <= 0 || !out) return -1;
|
||||
if (!(ext_floor > 0)) ext_floor = 1.0;
|
||||
memset(out, 0, sizeof *out);
|
||||
out->n = n; out->best = -1;
|
||||
out->scores = malloc((size_t)n * sizeof(double));
|
||||
out->distances = malloc((size_t)n * sizeof(double));
|
||||
out->rank = malloc((size_t)n * sizeof(int));
|
||||
if (!out->scores || !out->distances || !out->rank) { engram_reason_abduction_free(out); return -1; }
|
||||
|
||||
double best = -1; int bi = -1;
|
||||
for (int i = 0; i < n; i++) {
|
||||
out->rank[i] = i;
|
||||
const GeoDescriptor* h = hypotheses[i];
|
||||
GeoFit f;
|
||||
if (!h || h->dim != dim || engram_reason_point_fit(h, obs, ext_floor, &f) != 0) {
|
||||
out->scores[i] = 0.0; out->distances[i] = INFINITY;
|
||||
} else {
|
||||
out->scores[i] = f.score; out->distances[i] = f.distance;
|
||||
}
|
||||
if (bi < 0 || out->scores[i] > best) { best = out->scores[i]; bi = i; }
|
||||
}
|
||||
out->best = bi; out->best_score = (bi >= 0) ? out->scores[bi] : 0.0;
|
||||
|
||||
/* rank indices best→worst by score (insertion sort — n is small). */
|
||||
for (int i = 1; i < n; i++) {
|
||||
int key = out->rank[i]; int j = i - 1;
|
||||
while (j >= 0 && out->scores[out->rank[j]] < out->scores[key]) { out->rank[j + 1] = out->rank[j]; j--; }
|
||||
out->rank[j + 1] = key;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
void engram_reason_abduction_free(GeoAbduction* out) {
|
||||
if (!out) return;
|
||||
free(out->scores); free(out->distances); free(out->rank);
|
||||
out->scores = NULL; out->distances = NULL; out->rank = NULL;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════ CAUSAL ══ */
|
||||
/* |cos| of two descriptors' centroids after removing confounder Z's subspace. */
|
||||
static double controlled_assoc(const GeoDescriptor* x, const GeoDescriptor* y,
|
||||
const GeoDescriptor* z) {
|
||||
GeoResidual rx, ry; double c = 0;
|
||||
int ox = engram_geo_subtract(x, z, 0, &rx);
|
||||
int oy = engram_geo_subtract(y, z, 0, &ry);
|
||||
if (ox == 0 && oy == 0 && rx.residual_centroid && ry.residual_centroid)
|
||||
c = fabs(vcos(rx.residual_centroid, ry.residual_centroid, x->dim));
|
||||
if (ox == 0) engram_geo_residual_free(&rx);
|
||||
if (oy == 0) engram_geo_residual_free(&ry);
|
||||
return c;
|
||||
}
|
||||
int engram_reason_causal(const GeoDescriptor* x, const GeoDescriptor* y,
|
||||
const GeoDescriptor* const* confounders, int n_conf,
|
||||
int64_t t_x, int64_t t_y,
|
||||
double drop_frac, GeoCausal* out) {
|
||||
if (!x || !y || !out || !x->centroid || !y->centroid || x->dim != y->dim) return -1;
|
||||
if (!(drop_frac > 0 && drop_frac < 1)) drop_frac = 0.5;
|
||||
memset(out, 0, sizeof *out);
|
||||
const double assoc_floor = 0.2; /* below this = no meaningful association */
|
||||
|
||||
out->assoc_raw = fabs(vcos(x->centroid, y->centroid, x->dim));
|
||||
/* control for each confounder; the strongest single explainer wins (min assoc). */
|
||||
double ctrl = out->assoc_raw;
|
||||
for (int i = 0; i < n_conf; i++) {
|
||||
if (!confounders[i]) continue;
|
||||
double c = controlled_assoc(x, y, confounders[i]);
|
||||
if (c < ctrl) ctrl = c;
|
||||
}
|
||||
out->assoc_controlled = ctrl;
|
||||
out->temporal_dir = (t_x < t_y) ? 1 : (t_x > t_y) ? -1 : 0;
|
||||
|
||||
if (out->assoc_raw < assoc_floor) {
|
||||
out->verdict = GEO_CAUSAL_NONE;
|
||||
} else if (ctrl < (1.0 - drop_frac) * out->assoc_raw && ctrl < assoc_floor) {
|
||||
out->verdict = GEO_CAUSAL_CONFOUNDED; out->confounded = 1;
|
||||
} else if (out->temporal_dir != 0) {
|
||||
out->verdict = GEO_CAUSAL_DIRECTED; out->strength = ctrl;
|
||||
} else {
|
||||
out->verdict = GEO_CAUSAL_NONE; /* associated + robust but unorientable */
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════ PLANNING ══ */
|
||||
int engram_reason_plan(const GeoDescriptor* const* nodes, int n,
|
||||
int start, int goal, double neighbor_radius,
|
||||
int use_wasserstein, GeoPlan* out) {
|
||||
if (!nodes || n < 1 || !out) return -1;
|
||||
if (start < 0 || start >= n || goal < 0 || goal >= n) return -1;
|
||||
if (!(neighbor_radius > 0)) return -1;
|
||||
memset(out, 0, sizeof *out);
|
||||
|
||||
/* dense edge weights (i<j symmetric); INFINITY = not adjacent. */
|
||||
double* W = malloc((size_t)n * (size_t)n * sizeof(double));
|
||||
if (!W) return -1;
|
||||
for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) W[(size_t)i * n + j] = (i == j) ? 0.0 : INFINITY;
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = i + 1; j < n; j++) {
|
||||
GeoDistance d;
|
||||
if (nodes[i] && nodes[j] && engram_geo_distance(nodes[i], nodes[j], &d) == 0) {
|
||||
double w = use_wasserstein ? d.wasserstein2 : d.centroid_distance;
|
||||
if (w <= neighbor_radius) { W[(size_t)i * n + j] = w; W[(size_t)j * n + i] = w; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* O(n²) Dijkstra. */
|
||||
double* dist = malloc((size_t)n * sizeof(double));
|
||||
int* prev = malloc((size_t)n * sizeof(int));
|
||||
char* done = calloc((size_t)n, 1);
|
||||
if (!dist || !prev || !done) { free(W); free(dist); free(prev); free(done); return -1; }
|
||||
for (int i = 0; i < n; i++) { dist[i] = INFINITY; prev[i] = -1; }
|
||||
dist[start] = 0;
|
||||
for (int it = 0; it < n; it++) {
|
||||
int u = -1; double bd = INFINITY;
|
||||
for (int i = 0; i < n; i++) if (!done[i] && dist[i] < bd) { bd = dist[i]; u = i; }
|
||||
if (u < 0) break;
|
||||
done[u] = 1;
|
||||
if (u == goal) break;
|
||||
for (int v = 0; v < n; v++) {
|
||||
double w = W[(size_t)u * n + v];
|
||||
if (w < INFINITY && !done[v] && dist[u] + w < dist[v]) { dist[v] = dist[u] + w; prev[v] = u; }
|
||||
}
|
||||
}
|
||||
|
||||
if (dist[goal] < INFINITY) {
|
||||
int len = 0; for (int v = goal; v != -1; v = prev[v]) len++;
|
||||
out->path = malloc((size_t)len * sizeof(int));
|
||||
if (out->path) {
|
||||
out->path_len = len;
|
||||
int idx = len - 1;
|
||||
for (int v = goal; v != -1; v = prev[v]) out->path[idx--] = v;
|
||||
out->total_cost = dist[goal];
|
||||
out->reached = 1;
|
||||
}
|
||||
}
|
||||
free(W); free(dist); free(prev); free(done);
|
||||
return 0;
|
||||
}
|
||||
void engram_reason_plan_free(GeoPlan* out) {
|
||||
if (!out) return;
|
||||
free(out->path); out->path = NULL;
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
/* engram_reason.h — the REASONING layer: compositions over the §5 geometry
|
||||
* OPERATORS (engram_geometry.h). Where the operators are a relational ALGEBRA over
|
||||
* neighborhood descriptors, these are reasoning MODES built by CHAINING that algebra:
|
||||
*
|
||||
* ANALOGY A:B :: C:? — learn the A→B transform (Procrustes), apply to C.
|
||||
* INDUCTION {E_i} → rule — pool example geometries; a generalizing structure
|
||||
* + a membership test.
|
||||
* ABDUCTION x → best H — the structure whose geometry best PLACES an
|
||||
* observation in-distribution (inverse of prediction).
|
||||
* CAUSAL x ? y | Z, t — separate mere overlap (correlation) from directed
|
||||
* influence (temporal precedence + association that
|
||||
* SURVIVES controlling for confounders via subtract).
|
||||
* PLANNING start → goal — a trajectory (sequence of neighborhoods) through the
|
||||
* manifold: shortest path over geo-distance edges.
|
||||
*
|
||||
* PURE + READ-ONLY (stdlib + libm only): every function consumes GeoDescriptor(s)
|
||||
* (+ a few scalars / timestamps) and NEVER touches the store, index, or activation.
|
||||
* All geometry is delegated to the engram_geo_* primitives; this file only composes.
|
||||
*
|
||||
* FRAME CONTRACT (inherited): descriptors passed together MUST share emb `dim` and
|
||||
* `global_mean` frame — exactly the §5 operator contract. A function returns <0 on
|
||||
* a dim/frame mismatch or bad argument.
|
||||
*/
|
||||
#ifndef ENGRAM_REASON_H
|
||||
#define ENGRAM_REASON_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include "engram_geometry.h"
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* SHARED PRIMITIVE — point-to-manifold FIT. How well does a single point x sit
|
||||
* inside a neighborhood's ellipsoid? Splits the residual (x − centroid) into:
|
||||
* - the IN-SUBSPACE part, scaled by each axis extent → a Mahalanobis distance
|
||||
* (how many "radii" out along the modeled directions), and
|
||||
* - the ORTHOGONAL part outside the retained axes → energy the model does not
|
||||
* explain at all (charged at the extent floor).
|
||||
* This is the common engine under INDUCTION's membership test and ABDUCTION's
|
||||
* explanation ranking. ext_floor (>0) guards zero-extent axes / the null model.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct {
|
||||
double mahalanobis; /* sqrt( Σ_k ((a_k·(x−c)) / max(ext_k,floor))² ) */
|
||||
double ortho_residual; /* ‖(x−c) projected off the retained axes‖ (raw L2) */
|
||||
double distance; /* sqrt( maha² + (ortho_residual/floor)² ) — full fit */
|
||||
double score; /* 1 / (1 + distance²) ∈ (0,1] (1 = dead-center) */
|
||||
} GeoFit;
|
||||
int engram_reason_point_fit(const GeoDescriptor* g, const float* x,
|
||||
double ext_floor, GeoFit* out);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* ANALOGY — "A:B :: C:?". Learn the transform that carries A to B (orthogonal
|
||||
* Procrustes rotation R between their principal frames + the residual translation),
|
||||
* apply it to C, and return the mapped point + the nearest candidate neighborhood.
|
||||
* Composes: engram_geo_analogy (R) + engram_geo_analogy_apply + engram_geo_distance.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct {
|
||||
int dim;
|
||||
float* mapped_point; /* predicted D location = R·c_C + (c_B − R·c_A) (owned)*/
|
||||
double analogy_residual;/* Procrustes ‖A−B R‖_F — frame-alignment quality */
|
||||
int best; /* index of nearest candidate to mapped_point, or −1 */
|
||||
double best_distance; /* centroid L2 from mapped_point to the winner */
|
||||
int n_candidates;
|
||||
double* distances; /* centroid L2 mapped_point→candidate[i] (owned)*/
|
||||
} GeoAnalogyResult;
|
||||
/* candidates may be NULL/0 (then best=−1 and only mapped_point is filled). */
|
||||
int engram_reason_analogy(const GeoDescriptor* A, const GeoDescriptor* B,
|
||||
const GeoDescriptor* C,
|
||||
const GeoDescriptor* const* candidates, int n_candidates,
|
||||
GeoAnalogyResult* out);
|
||||
void engram_reason_analogy_free(GeoAnalogyResult* r);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* INDUCTION — from a SET of example neighborhoods to the generalizing structure.
|
||||
* Pools the examples (law-of-total-variance via engram_geo_combine, folded left to
|
||||
* right) into a single "rule" descriptor whose top principal axes are the directions
|
||||
* CONSISTENTLY present across the examples (the shared subspace surfaces as the
|
||||
* dominant pooled axes; idiosyncratic per-example directions fall to the tail).
|
||||
* The rule carries a membership test (point-to-manifold fit against the pool).
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct {
|
||||
GeoDescriptor* rule; /* induced generalizing geometry (owned; geo_free) */
|
||||
double ext_floor; /* extent floor used by the membership test */
|
||||
int n_examples;/* how many examples were pooled */
|
||||
} GeoInduction;
|
||||
/* top_axes<=0 → 8. ext_floor<=0 → derived from the pooled radius. */
|
||||
int engram_reason_induce(const GeoDescriptor* const* examples, int n_examples,
|
||||
int top_axes, double ext_floor, GeoInduction* out);
|
||||
/* Membership of a point in the induced rule ∈ (0,1] (the fit score). <0 on error. */
|
||||
double engram_reason_membership(const GeoInduction* ind, const float* x);
|
||||
void engram_reason_induction_free(GeoInduction* out);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* ABDUCTION — inference to the best explanation. Given an observation POINT, rank a
|
||||
* set of candidate structures by how well each PLACES the observation in-distribution
|
||||
* (min point-to-manifold distance = the structure that, if assumed, best accounts for
|
||||
* the observation). The inverse of prediction.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct {
|
||||
int best; /* index of best-explaining hypothesis, or −1 */
|
||||
double best_score;
|
||||
int n;
|
||||
double* scores; /* fit score per hypothesis (higher = better) (owned)*/
|
||||
double* distances; /* explanation distance per hypothesis (owned)*/
|
||||
int* rank; /* hypothesis indices sorted best→worst (owned)*/
|
||||
} GeoAbduction;
|
||||
int engram_reason_abduce(const float* obs, int dim,
|
||||
const GeoDescriptor* const* hypotheses, int n,
|
||||
double ext_floor, GeoAbduction* out);
|
||||
void engram_reason_abduction_free(GeoAbduction* out);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* CAUSAL — correlation vs causation. Over two variables' geometries (+ candidate
|
||||
* confounders + temporal order), distinguish:
|
||||
* - mere co-occurrence / overlap (correlation), from
|
||||
* - directed influence: association that (a) SURVIVES controlling for confounders
|
||||
* (subtract each Z's subspace from both centroids, re-measure) and (b) is oriented
|
||||
* by temporal PRECEDENCE.
|
||||
* Composes: centroid cosine (correlation) + engram_geo_subtract (control) + timestamps.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef enum {
|
||||
GEO_CAUSAL_NONE = 0, /* no meaningful association */
|
||||
GEO_CAUSAL_DIRECTED = 1, /* survives control + temporally ordered → cause→eff */
|
||||
GEO_CAUSAL_CONFOUNDED = 2 /* correlated but association dies under control */
|
||||
} GeoCausalVerdict;
|
||||
typedef struct {
|
||||
double assoc_raw; /* |cos(c_x,c_y)| — the raw correlation */
|
||||
double assoc_controlled; /* |cos| of residual centroids after control */
|
||||
int temporal_dir; /* +1 x→y, −1 y→x, 0 tie/unknown */
|
||||
GeoCausalVerdict verdict;
|
||||
int confounded; /* 1 iff verdict==CONFOUNDED (the flag) */
|
||||
double strength; /* directed influence estimate ∈[0,1] (0 else)*/
|
||||
} GeoCausal;
|
||||
/* confounders may be NULL/0. t_x,t_y are comparable timestamps (any monotone unit);
|
||||
* pass equal values for "unknown order". drop_frac∈(0,1): a controlled association
|
||||
* below (1−drop_frac)·assoc_raw AND below an absolute floor ⇒ CONFOUNDED. */
|
||||
int engram_reason_causal(const GeoDescriptor* x, const GeoDescriptor* y,
|
||||
const GeoDescriptor* const* confounders, int n_conf,
|
||||
int64_t t_x, int64_t t_y,
|
||||
double drop_frac, GeoCausal* out);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* PLANNING — trajectory construction. Given a set of neighborhoods (manifold nodes),
|
||||
* a start and a goal, build a PATH (sequence of intermediate neighborhoods) by
|
||||
* shortest path over the graph whose edges connect neighborhoods within
|
||||
* neighbor_radius, weighted by geo-distance. Long straight jumps are not edges, so
|
||||
* the path follows the manifold's curvature through intermediates (a discrete geodesic).
|
||||
* Composes: engram_geo_distance (edge weights) + Dijkstra.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct {
|
||||
int* path; /* node indices start..goal (owned) */
|
||||
int path_len;
|
||||
double total_cost; /* summed centroid-distance edge weights along path */
|
||||
int reached; /* 1 if goal reachable within neighbor_radius graph */
|
||||
} GeoPlan;
|
||||
/* neighbor_radius>0: max centroid distance for two neighborhoods to be adjacent.
|
||||
* Use "wasserstein"!=0 to weight edges by Wasserstein-2 instead of centroid L2. */
|
||||
int engram_reason_plan(const GeoDescriptor* const* nodes, int n,
|
||||
int start, int goal, double neighbor_radius,
|
||||
int use_wasserstein, GeoPlan* out);
|
||||
void engram_reason_plan_free(GeoPlan* out);
|
||||
|
||||
#endif /* ENGRAM_REASON_H */
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,330 @@
|
||||
/* engram_store.h — M1 of the engram tiered storage engine.
|
||||
*
|
||||
* The FINAL on-disk paged store format: superblock (+ mirror), slotted pages,
|
||||
* self-describing TLV records, overflow chains, and two B+-tree indexes
|
||||
* (primary id->loc, adjacency from_id/to_id->edge-locs) over a free-listed
|
||||
* page file. See docs/architecture/design/engram-tiered-storage-engine.md §2.
|
||||
*
|
||||
* This is a self-contained module (plain C, standard libs only). It defines its
|
||||
* own serializable views of a node/edge (StoreNode/StoreEdge) that mirror every
|
||||
* persisted field of EngramNode/EngramEdge in el_runtime.c. M3 maps between the
|
||||
* live runtime structs and these; M1 does not touch el_runtime.c.
|
||||
*
|
||||
* Format id: magic "ENGST01", format_version 1. This format is PERMANENT — the
|
||||
* TLV record scheme means new fields never force a migration.
|
||||
*/
|
||||
#ifndef ENGRAM_STORE_H
|
||||
#define ENGRAM_STORE_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* Fixed for the life of a store; recorded in the superblock. */
|
||||
#define STORE_PAGE_SIZE 16384u
|
||||
#define STORE_MAGIC "ENGST01" /* 7 chars + NUL stored in an 8-byte field */
|
||||
#define STORE_FORMAT_VERSION 1u
|
||||
|
||||
/* Ring-buffer length for ACT-R base-level access timestamps.
|
||||
* MUST equal ENGRAM_BLL_K in el_runtime.c (currently 10). Static-checked in .c. */
|
||||
#define STORE_BLL_K 10
|
||||
|
||||
/* Page types (page header byte). */
|
||||
enum {
|
||||
STORE_PT_NODE = 1,
|
||||
STORE_PT_EDGE = 2,
|
||||
STORE_PT_INDEX = 3,
|
||||
STORE_PT_OVERFLOW = 4,
|
||||
STORE_PT_FREE = 5
|
||||
};
|
||||
|
||||
/* store_check flags. */
|
||||
#define STORE_CHECK_CRC 1u
|
||||
|
||||
/* ── Serializable node view: every persisted EngramNode field ─────────────── */
|
||||
typedef struct StoreNode {
|
||||
char* id;
|
||||
char* content;
|
||||
char* node_type;
|
||||
char* label;
|
||||
char* tier;
|
||||
char* tags;
|
||||
char* metadata;
|
||||
double salience;
|
||||
double importance;
|
||||
double confidence;
|
||||
double temporal_decay_rate;
|
||||
int64_t activation_count;
|
||||
int64_t last_activated;
|
||||
int64_t created_at;
|
||||
int64_t updated_at;
|
||||
double background_activation;
|
||||
double working_memory_weight;
|
||||
int32_t suppression_count;
|
||||
uint32_t layer_id;
|
||||
int64_t access_ts[STORE_BLL_K];
|
||||
int32_t access_head;
|
||||
int32_t access_filled;
|
||||
double wm_anchor;
|
||||
float* emb; /* owned; NULL if not embedded */
|
||||
int32_t emb_dim;
|
||||
/* Forward-compat: raw bytes of any TLV fields the reader did not recognise,
|
||||
* concatenated verbatim ([tag][u32 len][bytes]...). Re-emitted on write so
|
||||
* an old reader never drops a newer writer's fields. */
|
||||
uint8_t* unknown;
|
||||
size_t unknown_len;
|
||||
int tombstoned; /* set by store_get_* if the located record is dead */
|
||||
/* hebb_elig / hebb_elig_ts are DELIBERATELY NOT persisted (see EngramNode). */
|
||||
} StoreNode;
|
||||
|
||||
/* ── Serializable edge view: every persisted EngramEdge field ─────────────── */
|
||||
typedef struct StoreEdge {
|
||||
char* id;
|
||||
char* from_id;
|
||||
char* to_id;
|
||||
char* relation;
|
||||
char* metadata;
|
||||
double weight;
|
||||
double hebb;
|
||||
double confidence;
|
||||
int64_t created_at;
|
||||
int64_t updated_at;
|
||||
int64_t last_fired;
|
||||
int32_t inhibitory;
|
||||
uint32_t layer_id;
|
||||
uint8_t* unknown;
|
||||
size_t unknown_len;
|
||||
int tombstoned;
|
||||
} StoreEdge;
|
||||
|
||||
typedef struct EngramPagedStore EngramPagedStore;
|
||||
|
||||
/* Lifecycle. */
|
||||
EngramPagedStore* store_create(const char* path); /* fails if file exists */
|
||||
EngramPagedStore* store_open(const char* path); /* recovers via mirror SB */
|
||||
int store_close(EngramPagedStore* s); /* syncs + frees */
|
||||
int store_sync(EngramPagedStore* s); /* fsync + rewrite both superblocks */
|
||||
|
||||
/* Nodes. store_get_node returns 1 on hit (fills *out, caller store_node_free),
|
||||
* 0 if absent or tombstoned, <0 on error. */
|
||||
int store_put_node(EngramPagedStore* s, const StoreNode* n);
|
||||
int store_get_node(EngramPagedStore* s, const char* id, StoreNode* out);
|
||||
int store_tombstone(EngramPagedStore* s, const char* id);
|
||||
|
||||
/* Edges. *out is malloc'd (store_edges_free); *n set to count. */
|
||||
int store_put_edge(EngramPagedStore* s, const StoreEdge* e);
|
||||
int store_get_edges_from(EngramPagedStore* s, const char* from_id, StoreEdge** out, size_t* n);
|
||||
int store_get_edges_to(EngramPagedStore* s, const char* to_id, StoreEdge** out, size_t* n);
|
||||
|
||||
/* Integrity: verify every page's crc (and both superblocks). Returns the number
|
||||
* of corrupt pages (0 = clean), or <0 on I/O error. */
|
||||
int store_check(EngramPagedStore* s, unsigned flags);
|
||||
|
||||
/* Ownership helpers. */
|
||||
void store_node_free(StoreNode* n);
|
||||
void store_edge_free(StoreEdge* e);
|
||||
void store_edges_free(StoreEdge* arr, size_t n);
|
||||
|
||||
/* Test-only hook (NOT a format property — B+-tree nodes are self-describing via
|
||||
* their stored key count). Caps entries/keys per index node to force splits on
|
||||
* small datasets. 0 = natural full-page fanout. */
|
||||
void store__set_btree_order(EngramPagedStore* s, int leaf_max, int internal_max);
|
||||
|
||||
/* Introspection for tests/tools. */
|
||||
uint64_t store_page_count(const EngramPagedStore* s);
|
||||
|
||||
/* ── M2: WAL + checkpoint + crash recovery + one-time legacy import ─────────────
|
||||
*
|
||||
* The durable engram is `neuron.egm` (paged) fronted by `neuron.wal`
|
||||
* (append-only). A mutation is durable once its WAL record is fsync'd
|
||||
* (group-commit). Pages are held write-back in RAM (no-steal) and flushed to the
|
||||
* store only at a checkpoint, so the store file on disk always reflects a
|
||||
* consistent point (`last_checkpoint_lsn`) and the WAL owns everything since.
|
||||
* Recovery = open store, replay WAL forward, redo a record only where the target
|
||||
* record's home page LSN < record LSN (idempotent). JSON is ONLY an import
|
||||
* source / export artifact — never the ongoing store. */
|
||||
|
||||
typedef enum { ENGRAM_WAL_ALWAYS = 0, ENGRAM_WAL_GROUP = 1, ENGRAM_WAL_OFF = 2 } EngramWalSync;
|
||||
|
||||
/* Serializable layer-registry view (the `layers` array of the legacy snapshot). */
|
||||
typedef struct StoreLayer {
|
||||
uint32_t layer_id;
|
||||
char* name;
|
||||
uint32_t activation_priority;
|
||||
int32_t suppressible;
|
||||
int32_t transparent;
|
||||
int32_t injectable;
|
||||
uint8_t* unknown;
|
||||
size_t unknown_len;
|
||||
int tombstoned;
|
||||
} StoreLayer;
|
||||
|
||||
/* Boot the durable engram in `data_dir` (holds neuron.egm + neuron.wal). If the
|
||||
* store is absent but a legacy snapshot.json exists, it is imported ONCE into a
|
||||
* fresh store; thereafter the store is authoritative and JSON is never read again.
|
||||
* On open, the WAL is replayed to recover any post-checkpoint mutations. */
|
||||
EngramPagedStore* engram_open(const char* data_dir);
|
||||
int engram_close(EngramPagedStore* s); /* checkpoint + close */
|
||||
|
||||
/* Force a checkpoint: flush dirty pages → fsync store → advance checkpoint LSN →
|
||||
* reclaim the WAL prefix. Also threshold-triggered automatically on the write path. */
|
||||
int engram_checkpoint(EngramPagedStore* s);
|
||||
|
||||
/* WAL commit policy. engram_open honours env ENGRAM_WAL_SYNC=always|group|off. */
|
||||
void engram_set_wal_sync(EngramPagedStore* s, EngramWalSync policy);
|
||||
|
||||
/* Layer registry. */
|
||||
int store_put_layer(EngramPagedStore* s, const StoreLayer* L);
|
||||
int store_get_layer(EngramPagedStore* s, uint32_t layer_id, StoreLayer* out);
|
||||
int store_del_layer(EngramPagedStore* s, uint32_t layer_id);
|
||||
int store_list_layers(EngramPagedStore* s, StoreLayer** out, size_t* n);
|
||||
void store_layer_free(StoreLayer* L);
|
||||
void store_layers_free(StoreLayer* arr, size_t n);
|
||||
|
||||
/* Edge lookup by id (for hebb updates + idempotency). 1 hit / 0 absent / <0 err. */
|
||||
int store_get_edge(EngramPagedStore* s, const char* id, StoreEdge* out);
|
||||
|
||||
/* HEBB batch: one WAL record updating hebb (+ last_fired) on a set of edges. */
|
||||
typedef struct StoreHebbDelta { const char* edge_id; double hebb; int64_t last_fired; } StoreHebbDelta;
|
||||
int store_hebb_batch(EngramPagedStore* s, const StoreHebbDelta* d, size_t n);
|
||||
|
||||
/* Supersede: logs the (old,new) pair and tombstones old_id at the store; the new
|
||||
* node + `supersedes` edge are logged separately (neuron-layer immutability). */
|
||||
int store_supersede(EngramPagedStore* s, const char* old_id, const char* new_id);
|
||||
|
||||
/* Forget (GC): tombstone id at the store (hard-free deferred to compaction). */
|
||||
int store_forget(EngramPagedStore* s, const char* id);
|
||||
|
||||
/* ── M3: full live enumeration (for the CALLER's resident load + JSON export) ──
|
||||
* Walk the whole store and invoke `cb` once per DISTINCT live node/edge with a
|
||||
* borrowed view (the engine frees it after cb returns — the callback must copy
|
||||
* anything it keeps). De-duplicated by id (canonical latest-live per id, matching
|
||||
* point-read semantics). Returns the count emitted, or <0 on error. The engine
|
||||
* hands out StoreNode/StoreEdge only — it never sees a soul struct (design §10). */
|
||||
typedef void (*StoreNodeScanCb)(const StoreNode* n, void* ctx);
|
||||
typedef void (*StoreEdgeScanCb)(const StoreEdge* e, void* ctx);
|
||||
int store_scan_nodes(EngramPagedStore* s, StoreNodeScanCb cb, void* ctx);
|
||||
int store_scan_edges(EngramPagedStore* s, StoreEdgeScanCb cb, void* ctx);
|
||||
|
||||
/* Introspection / test hooks. */
|
||||
uint64_t engram_wal_next_lsn(const EngramPagedStore* s);
|
||||
uint64_t engram_last_checkpoint_lsn(const EngramPagedStore* s);
|
||||
|
||||
/* ── M4: demand-paging buffer pool (additive residency; on-disk format UNCHANGED) ──
|
||||
*
|
||||
* The write-back, no-steal cache of M2 becomes a bounded, demand-paged buffer
|
||||
* pool. A fixed frame budget (env ENGRAM_POOL_FRAMES; 0 = unlimited; default
|
||||
* large ⇒ whole store resident ⇒ identical to Phase 1) keeps only hot pages in
|
||||
* RAM; a page access that is not resident faults in from neuron.egm, and under
|
||||
* pressure a CLEAN, unpinned frame is evicted (LRU). Dirty frames are never
|
||||
* stolen (M2 no-steal / WAL durability), and superblocks + index root/interior
|
||||
* pages are auto-pinned. Prefetch (env ENGRAM_PREFETCH) reads ahead on scans. */
|
||||
|
||||
/* Pin / unpin an individual page (faults it in and keeps it resident until
|
||||
* unpinned). Pin a hot layer's pages (WM/core) as a set. Idempotent counts. */
|
||||
int store_pin_page(EngramPagedStore* s, uint64_t page_id);
|
||||
int store_unpin_page(EngramPagedStore* s, uint64_t page_id);
|
||||
int store_pin_layer(EngramPagedStore* s, uint32_t layer); /* returns #pages pinned */
|
||||
int store_unpin_layer(EngramPagedStore* s, uint32_t layer);
|
||||
|
||||
/* Buffer-pool introspection. */
|
||||
typedef struct StorePoolStats {
|
||||
size_t cap; /* frame budget (0 = unlimited) */
|
||||
size_t resident; /* frames currently resident */
|
||||
size_t pinned; /* frames that cannot be evicted (dirty/pinned/structural) */
|
||||
size_t dirty; /* dirty (un-checkpointed) frames */
|
||||
unsigned prefetch; /* read-ahead window */
|
||||
uint64_t hits, misses; /* page_read cache hits / demand faults */
|
||||
uint64_t evictions; /* clean frames reclaimed */
|
||||
uint64_t prefetch_reads; /* pages brought in by read-ahead */
|
||||
} StorePoolStats;
|
||||
void store_pool_stats(const EngramPagedStore* s, StorePoolStats* out);
|
||||
int store_pool_resident(const EngramPagedStore* s, uint64_t page_id);
|
||||
|
||||
/* Test hooks: set the frame budget / prefetch window at runtime (NOT format). */
|
||||
void store__set_pool_frames(EngramPagedStore* s, size_t frames);
|
||||
void store__set_prefetch(EngramPagedStore* s, unsigned window);
|
||||
|
||||
/* Crash-test hooks (writes only under a throwaway dir).
|
||||
* store__crash — abandon all RAM state without flush/fsync (power loss).
|
||||
* store__flush_pages — pwrite dirty pages to disk WITHOUT a checkpoint (steal).
|
||||
* store__checkpoint_crashat — run checkpoint but stop (then power-loss) after
|
||||
* `phase` (0..4); phase<0 = full checkpoint. */
|
||||
void store__crash(EngramPagedStore* s);
|
||||
int store__flush_pages(EngramPagedStore* s);
|
||||
int store__checkpoint_crashat(EngramPagedStore* s, int phase);
|
||||
|
||||
/* ── M5: online compaction + background checkpointer (additive; format UNCHANGED) ──
|
||||
*
|
||||
* COMPACTION reclaims the space held by DEAD records — tombstoned nodes/edges
|
||||
* (telemetry prune, forget), superseded ids, and the stale prior versions a
|
||||
* re-put/hebb-batch leaves behind — plus the overflow pages they orphaned. It
|
||||
* rewrites only the LIVE records (bit-exact) into a fresh, densely packed image
|
||||
* with fresh id + adjacency indexes, then commits the swap atomically, so the
|
||||
* .egm file physically SHRINKS and the freed pages are reclaimed. Crash-safe:
|
||||
* a crash at any instant recovers to either the pre- or the post-compaction
|
||||
* store, never a corrupt mix (atomic rename is the commit point). It cooperates
|
||||
* with the M4 pool (no-steal, pins) by building into a separate store whose own
|
||||
* pool honours ENGRAM_POOL_FRAMES, then INVALIDATING every frame of the live
|
||||
* pool so no stale frame survives for a relocated page.
|
||||
*
|
||||
* Requires a quiesce point: store_compact performs a checkpoint (or sync) at
|
||||
* entry, so it is called between mutations, not concurrently with one. */
|
||||
int store_compact(EngramPagedStore* s);
|
||||
|
||||
/* Test hook: run compaction but stop (then power-loss) after `phase`:
|
||||
* 0 = after the entry checkpoint, before building (→ recovers pre-compaction)
|
||||
* 1 = after building+fsync the new image, before rename (→ pre-compaction)
|
||||
* 2 = after the atomic rename, before reopening RAM state (→ post-compaction)
|
||||
* phase<0 = full compaction. Frees `s` on a crash phase (like the checkpoint hook). */
|
||||
int store__compact_crashat(EngramPagedStore* s, int phase);
|
||||
|
||||
/* BACKGROUND CHECKPOINTER policy. A checkpoint fires automatically on the write
|
||||
* path when ANY armed trigger trips, reclaiming the WAL prefix without an explicit
|
||||
* engram_checkpoint. 0 disables that trigger. Same checkpoint semantics as M2.
|
||||
* ops — mutations since last checkpoint (default 100000)
|
||||
* dirty_pages — dirty (un-checkpointed) pool frames
|
||||
* wal_bytes — bytes appended to the WAL since it was last reclaimed
|
||||
* interval_ms — wall-clock ms since the last checkpoint (checked on writes) */
|
||||
void store_set_checkpoint_policy(EngramPagedStore* s, uint64_t ops,
|
||||
size_t dirty_pages, uint64_t wal_bytes,
|
||||
long long interval_ms);
|
||||
|
||||
/* Introspection: number of pages currently on the free-list. */
|
||||
uint64_t store_free_page_count(const EngramPagedStore* s);
|
||||
|
||||
/* ── CCR §4 managed-memory layer (write-barrier + minor GC + observability) ─────
|
||||
*
|
||||
* All flag-gated at store open (default OFF ⇒ byte-for-byte legacy behaviour):
|
||||
* ENGRAM_WRITE_BARRIER=1 arm the durable-content write-barrier: a store_put_node
|
||||
* whose DURABLE fields (content/type/label/tier/tags/metadata/importance/
|
||||
* confidence/decay/layer/emb) are byte-identical to the last persisted copy
|
||||
* is SKIPPED entirely — no LSN, no WAL, no record, no tombstone. This kills
|
||||
* the ~99.78% checkpoint full-walk garbage at the source (ephemeral
|
||||
* activation/WM state is intentionally not re-persisted on think-only cycles).
|
||||
* ENGRAM_GC=1 (a) node re-puts supersede prior copies (mark DEAD, as edges do)
|
||||
* so stale versions become reclaimable, and (b) a MINOR GC runs at the head
|
||||
* of every checkpoint, returning whole dead NODE/EDGE pages to the free list.
|
||||
* The MAJOR GC is the existing merge-safe store_compact (schedule on a dead-ratio
|
||||
* threshold from the soul). */
|
||||
|
||||
/* Run one minor-GC sweep now: reclaim whole dead NODE/EDGE pages to the free list.
|
||||
* Returns the number of pages reclaimed (>=0). Safe to call between mutations;
|
||||
* automatically invoked at each checkpoint when ENGRAM_GC is armed. */
|
||||
int store_minor_gc(EngramPagedStore* s);
|
||||
|
||||
/* GC / cache observability census (CCR §4.4). Page tallies are point-in-time;
|
||||
* the *_writes / *_skips / *_runs / *_reclaimed counters are cumulative since open. */
|
||||
typedef struct StoreGcStats {
|
||||
uint64_t node_pages, edge_pages, index_pages, overflow_pages, free_pages;
|
||||
uint64_t live_nodes, live_edges; /* live slots on NODE / EDGE pages */
|
||||
uint64_t dead_slots; /* superseded/tombstoned slots awaiting reclaim */
|
||||
uint64_t live_bytes, dead_bytes; /* on-page record bytes, live vs dead */
|
||||
uint64_t durable_writes; /* node puts that actually appended a record */
|
||||
uint64_t barrier_skips; /* node puts skipped by the write-barrier */
|
||||
uint64_t minor_gc_runs; /* minor-GC invocations */
|
||||
uint64_t pages_reclaimed; /* whole pages returned to the free list by minor GC */
|
||||
int barrier_on, gc_on; /* which gates are armed */
|
||||
} StoreGcStats;
|
||||
void store_gc_stats(EngramPagedStore* s, StoreGcStats* out);
|
||||
|
||||
#endif /* ENGRAM_STORE_H */
|
||||
@@ -0,0 +1,157 @@
|
||||
/* engram_verify.c — the VERIFIER layer. Pure compositions over engram_reason.h +
|
||||
* engram_geometry.h. stdlib + libm only; READ-ONLY over its inputs; touches no
|
||||
* store/index/activation. See engram_verify.h for the design and the frame contract. */
|
||||
#include "engram_verify.h"
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
/* ── small float-vector helpers (mirror engram_reason.c) ────────────────────── */
|
||||
static double vdot(const float* a, const float* b, int dim) {
|
||||
double s = 0; for (int i = 0; i < dim; i++) s += (double)a[i] * (double)b[i]; return s;
|
||||
}
|
||||
static double l2(const float* a, const float* b, int dim) {
|
||||
double s = 0; for (int i = 0; i < dim; i++) { double d = (double)a[i] - (double)b[i]; s += d * d; }
|
||||
return sqrt(s);
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════ GROUNDING ══════════ */
|
||||
int engram_verify_grounding(const float* claim, int dim,
|
||||
const GeoDescriptor* const* evidence, int n_evidence,
|
||||
double ext_floor, double ground_threshold,
|
||||
GeoGrounding* out) {
|
||||
if (!claim || dim <= 0 || !evidence || n_evidence < 1 || !out) return -1;
|
||||
if (!(ext_floor > 0)) ext_floor = 1.0;
|
||||
if (!(ground_threshold > 0 && ground_threshold < 1)) ground_threshold = 0.5;
|
||||
memset(out, 0, sizeof *out);
|
||||
out->n_evidence = n_evidence;
|
||||
out->best = -1;
|
||||
out->nearest_centroid_l2 = INFINITY;
|
||||
out->scores = malloc((size_t)n_evidence * sizeof(double));
|
||||
if (!out->scores) return -1;
|
||||
|
||||
double best = -1;
|
||||
for (int i = 0; i < n_evidence; i++) {
|
||||
const GeoDescriptor* e = evidence[i];
|
||||
GeoFit f;
|
||||
if (!e || e->dim != dim || !e->centroid ||
|
||||
engram_reason_point_fit(e, claim, ext_floor, &f) != 0) {
|
||||
out->scores[i] = 0.0;
|
||||
continue;
|
||||
}
|
||||
out->scores[i] = f.score;
|
||||
double cl2 = l2(claim, e->centroid, dim);
|
||||
if (cl2 < out->nearest_centroid_l2) out->nearest_centroid_l2 = cl2;
|
||||
if (out->best < 0 || f.score > best) {
|
||||
best = f.score;
|
||||
out->best = i;
|
||||
out->grounding = f.score;
|
||||
out->best_distance = f.distance;
|
||||
out->best_ortho = f.ortho_residual;
|
||||
}
|
||||
}
|
||||
if (out->best < 0) { out->grounding = 0.0; out->best_distance = INFINITY; }
|
||||
out->grounded = (out->grounding >= ground_threshold) ? 1 : 0;
|
||||
return 0;
|
||||
}
|
||||
void engram_verify_grounding_free(GeoGrounding* out) {
|
||||
if (!out) return;
|
||||
free(out->scores); out->scores = NULL;
|
||||
}
|
||||
|
||||
/* ═══════════════════════════════════════════════════════ CONSISTENCY ════════ */
|
||||
int engram_verify_consistency(const float* claim, int dim,
|
||||
const GeoDescriptor* context,
|
||||
const GeoDescriptor* pole_pos, const GeoDescriptor* pole_neg,
|
||||
const GeoDescriptor* forbidden,
|
||||
double ext_floor, double deadzone_frac,
|
||||
double forbidden_thresh, double max_distance,
|
||||
GeoConsistency* out) {
|
||||
if (!claim || dim <= 0 || !out) return -1;
|
||||
if (!(ext_floor > 0)) ext_floor = 1.0;
|
||||
if (!(deadzone_frac >= 0 && deadzone_frac < 1)) deadzone_frac = 0.10;
|
||||
if (!(forbidden_thresh > 0 && forbidden_thresh < 1)) forbidden_thresh = 0.5;
|
||||
memset(out, 0, sizeof *out);
|
||||
out->verdict = GEO_CONSIST_OK;
|
||||
out->consistency = 1.0;
|
||||
|
||||
int do_polarity = (pole_pos && pole_neg);
|
||||
int do_distance = (max_distance > 0);
|
||||
if ((do_polarity || do_distance) &&
|
||||
(!context || context->dim != dim || !context->centroid)) return -1;
|
||||
if (do_polarity && (pole_pos->dim != dim || pole_neg->dim != dim ||
|
||||
!pole_pos->centroid || !pole_neg->centroid)) return -1;
|
||||
if (forbidden && (forbidden->dim != dim || !forbidden->centroid)) return -1;
|
||||
|
||||
double pol_score = 1.0, geo_score = 1.0;
|
||||
|
||||
/* ── (a) POLARITY / negation inversion ─────────────────────────────────── */
|
||||
if (do_polarity) {
|
||||
/* axis p = (c_pos − c_neg); midpoint o = ½(c_pos + c_neg). */
|
||||
float* p = malloc((size_t)dim * sizeof(float));
|
||||
float* o = malloc((size_t)dim * sizeof(float));
|
||||
if (!p || !o) { free(p); free(o); return -1; }
|
||||
double pn2 = 0;
|
||||
for (int i = 0; i < dim; i++) {
|
||||
double dpos = (double)pole_pos->centroid[i], dneg = (double)pole_neg->centroid[i];
|
||||
p[i] = (float)(dpos - dneg);
|
||||
o[i] = (float)(0.5 * (dpos + dneg));
|
||||
pn2 += (dpos - dneg) * (dpos - dneg);
|
||||
}
|
||||
double pn = sqrt(pn2);
|
||||
out->polarity_separation = 0.5 * pn;
|
||||
if (pn > 1e-12) {
|
||||
/* signed positions along the axis (projection of (x − o) onto unit p). */
|
||||
float* cdo = malloc((size_t)dim * sizeof(float)); /* claim − o */
|
||||
float* rdo = malloc((size_t)dim * sizeof(float)); /* context − o */
|
||||
if (!cdo || !rdo) { free(p); free(o); free(cdo); free(rdo); return -1; }
|
||||
for (int i = 0; i < dim; i++) {
|
||||
cdo[i] = (float)((double)claim[i] - (double)o[i]);
|
||||
rdo[i] = (float)((double)context->centroid[i] - (double)o[i]);
|
||||
}
|
||||
double claim_side = vdot(cdo, p, dim) / pn; /* units: emb-space length */
|
||||
double ref_side = vdot(rdo, p, dim) / pn;
|
||||
out->polarity_claim = claim_side;
|
||||
out->polarity_reference = ref_side;
|
||||
double dz = deadzone_frac * out->polarity_separation; /* neutral band */
|
||||
if (fabs(claim_side) > dz && fabs(ref_side) > dz &&
|
||||
(claim_side > 0) != (ref_side > 0)) {
|
||||
out->inverted = 1;
|
||||
pol_score = 0.0; /* opposite poles ⇒ zero consistency */
|
||||
} else if (fabs(claim_side) <= dz || fabs(ref_side) <= dz) {
|
||||
pol_score = 0.5; /* neutral / undecided */
|
||||
} else {
|
||||
pol_score = 1.0; /* same pole ⇒ consistent */
|
||||
}
|
||||
free(cdo); free(rdo);
|
||||
}
|
||||
free(p); free(o);
|
||||
}
|
||||
|
||||
/* ── (b) GEOMETRIC contradiction ───────────────────────────────────────── */
|
||||
if (forbidden) {
|
||||
GeoFit f;
|
||||
if (engram_reason_point_fit(forbidden, claim, ext_floor, &f) == 0) {
|
||||
out->forbidden_fit = f.score;
|
||||
if (f.score >= forbidden_thresh) {
|
||||
out->geo_violation = 1;
|
||||
double g = 1.0 - f.score; if (g < 0) g = 0;
|
||||
if (g < geo_score) geo_score = g;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (do_distance) {
|
||||
out->context_distance = l2(claim, context->centroid, dim);
|
||||
if (out->context_distance > max_distance) {
|
||||
out->geo_violation = 1;
|
||||
geo_score = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── verdict + scalar (polarity is the headline; both flags stay visible) ─ */
|
||||
out->consistency = (pol_score < geo_score) ? pol_score : geo_score;
|
||||
if (out->inverted) out->verdict = GEO_CONSIST_POLARITY;
|
||||
else if (out->geo_violation) out->verdict = GEO_CONSIST_GEOMETRIC;
|
||||
else out->verdict = GEO_CONSIST_OK;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
/* engram_verify.h — the VERIFIER layer: GROUNDING + CONSISTENCY over the live
|
||||
* geometry (engram_geometry.h) and reasoning (engram_reason.h) operators.
|
||||
*
|
||||
* The geometry PROPOSES (cheap, creative, sometimes wrong); the verifier DISPOSES.
|
||||
* This layer catches the class of failure a grammar check never sees: a fluent,
|
||||
* confident, WRONG output — the "plausible lie". The motivating case: a translation
|
||||
* that DELETED a negation so "you never fought" became "you argued" — reassurance
|
||||
* inverted into accusation, grammatical and invisible, catchable ONLY by the geometry.
|
||||
*
|
||||
* GROUNDING claim → is there ANY real structure that supports it, or is it
|
||||
* floating free of the manifold? (anti-hallucination gate)
|
||||
* CONSISTENCY claim → does it CONTRADICT the established structure? Two catches:
|
||||
* (a) POLARITY: the claim lands on the OPPOSITE side of a negation
|
||||
* axis from the grounded truth (the reassurance→accusation catch),
|
||||
* (b) GEOMETRIC: the claim sits inside a region it must be far from,
|
||||
* or violates a max-distance constraint to its context.
|
||||
*
|
||||
* PURE + READ-ONLY (stdlib + libm only): every function consumes a claim POINT
|
||||
* (float* in R^dim) plus GeoDescriptor(s), and NEVER touches the store, index, or
|
||||
* activation. All geometry is delegated to engram_reason_point_fit / engram_geo_*;
|
||||
* this file only composes and applies thresholds.
|
||||
*
|
||||
* FRAME CONTRACT (inherited): the claim point and every descriptor passed together
|
||||
* MUST share emb `dim` and the same `global_mean` frame — exactly the §5 operator
|
||||
* contract. A function returns <0 on a dim/frame mismatch or bad argument.
|
||||
*/
|
||||
#ifndef ENGRAM_VERIFY_H
|
||||
#define ENGRAM_VERIFY_H
|
||||
|
||||
#include "engram_geometry.h"
|
||||
#include "engram_reason.h"
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* GROUNDING — anti-hallucination. Score how well a claimed POINT is supported by
|
||||
* the ACTUAL structure: fit the claim against every real evidence neighborhood
|
||||
* (engram_reason_point_fit → in-distribution Mahalanobis + off-model orthogonal
|
||||
* residual) and take the BEST supporter. A claim that sits inside real structure
|
||||
* scores high (grounded); a claim floating far from every neighborhood scores low
|
||||
* on all of them → flagged UNGROUNDED (a hallucination).
|
||||
*
|
||||
* This is an ABSOLUTE-THRESHOLD gate, deliberately distinct from ABDUCTION (which
|
||||
* always RANKS and picks a winner among competing hypotheses): grounding asks the
|
||||
* prior question — "is there any real support at all?" — and is allowed to answer no.
|
||||
* The off-model `ortho_residual` is the sharpest hallucination signal: energy in a
|
||||
* direction the manifold does not even span.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef struct {
|
||||
double grounding; /* ∈[0,1]: overall support = best fit score */
|
||||
int grounded; /* 1 iff grounding >= ground_threshold */
|
||||
int best; /* index of best-supporting evidence structure, or −1 */
|
||||
double best_distance; /* full point-to-manifold distance to the best */
|
||||
double best_ortho; /* off-model orthogonal residual of the best fit */
|
||||
double nearest_centroid_l2;/* raw L2 to the nearest evidence centroid (coarse) */
|
||||
int n_evidence;
|
||||
double* scores; /* per-evidence fit score, higher = better (owned)*/
|
||||
} GeoGrounding;
|
||||
/* ext_floor>0 guards zero-extent axes (default 1.0). ground_threshold∈(0,1): the
|
||||
* minimum best-fit score to call the claim grounded (default 0.5). */
|
||||
int engram_verify_grounding(const float* claim, int dim,
|
||||
const GeoDescriptor* const* evidence, int n_evidence,
|
||||
double ext_floor, double ground_threshold,
|
||||
GeoGrounding* out);
|
||||
void engram_verify_grounding_free(GeoGrounding* out);
|
||||
|
||||
/* ═══════════════════════════════════════════════════════════════════════════
|
||||
* CONSISTENCY — contradiction detection. Does the claim contradict the established
|
||||
* structure? Two independent sub-checks (either can fire; both flags are reported):
|
||||
*
|
||||
* (a) POLARITY / negation inversion. A polarity axis p is defined by two REAL
|
||||
* poles — pole_pos (asserts X) and pole_neg (asserts ¬X):
|
||||
* p = (c_pos − c_neg)/‖·‖ , midpoint o = ½(c_pos + c_neg).
|
||||
* The claim's side = p·(claim − o); the reference's side = p·(c_context − o).
|
||||
* If the two sides have OPPOSITE sign AND both clear the neutral deadzone, the
|
||||
* claim asserts the polarity opposite to the grounded truth → INVERSION flagged.
|
||||
* This is the "you never fought"→"you argued" catch: the truth ("never fought")
|
||||
* sits on the negate pole, the claim ("argued") on the affirm pole → opposite
|
||||
* sides → flagged, though every word is grammatical.
|
||||
*
|
||||
* (b) GEOMETRIC contradiction. The claim sits INSIDE a `forbidden` region it must
|
||||
* be far from (point_fit score to forbidden ≥ forbidden_thresh), OR it violates
|
||||
* a max-distance constraint to its context centroid (L2 > max_distance).
|
||||
*
|
||||
* pole_pos/pole_neg may both be NULL to skip the polarity check; forbidden may be
|
||||
* NULL and max_distance≤0 to skip the geometric check. `context` (the grounded truth
|
||||
* region) is required whenever polarity or the distance constraint is used.
|
||||
* ═══════════════════════════════════════════════════════════════════════════ */
|
||||
typedef enum {
|
||||
GEO_CONSIST_OK = 0, /* consistent with context */
|
||||
GEO_CONSIST_POLARITY = 1, /* polarity/negation inversion (asserts ¬X where X) */
|
||||
GEO_CONSIST_GEOMETRIC = 2 /* geometric contradiction (in forbidden / too far) */
|
||||
} GeoConsistencyVerdict;
|
||||
typedef struct {
|
||||
GeoConsistencyVerdict verdict; /* headline (polarity takes precedence) */
|
||||
double consistency; /* ∈[0,1]: min over the checks (1 = fully consistent)*/
|
||||
/* polarity sub-check */
|
||||
int inverted; /* 1 iff a polarity inversion was detected */
|
||||
double polarity_claim; /* p·(claim − o) (signed position on the axis)*/
|
||||
double polarity_reference; /* p·(c_context − o) (the grounded truth's side) */
|
||||
double polarity_separation; /* ½‖c_pos − c_neg‖ (the axis half-length / scale)*/
|
||||
/* geometric sub-check */
|
||||
int geo_violation; /* 1 iff a geometric contradiction was detected */
|
||||
double forbidden_fit; /* claim's point_fit score to the forbidden region*/
|
||||
double context_distance; /* L2(claim, c_context) */
|
||||
} GeoConsistency;
|
||||
/* ext_floor>0 (default 1.0). deadzone_frac∈[0,1): a polarity side within
|
||||
* deadzone_frac·separation of the midpoint is "neutral" and never triggers inversion
|
||||
* (default 0.10). forbidden_thresh∈(0,1): fit-to-forbidden at/above which the claim
|
||||
* counts as inside the forbidden region (default 0.5). max_distance>0 enables the
|
||||
* distance constraint; ≤0 disables it. */
|
||||
int engram_verify_consistency(const float* claim, int dim,
|
||||
const GeoDescriptor* context,
|
||||
const GeoDescriptor* pole_pos, const GeoDescriptor* pole_neg,
|
||||
const GeoDescriptor* forbidden,
|
||||
double ext_floor, double deadzone_frac,
|
||||
double forbidden_thresh, double max_distance,
|
||||
GeoConsistency* out);
|
||||
|
||||
#endif /* ENGRAM_VERIFY_H */
|
||||
@@ -0,0 +1,649 @@
|
||||
/* engram_vindex.c — HNSW ANN index over f32 embedding vectors (design §9 M8).
|
||||
*
|
||||
* Self-contained: plain C11, stdlib + libm (-lm for sqrtf/logf) only. No
|
||||
* dependency on el_runtime; the store is read via its PERMANENT on-disk format
|
||||
* (design §2.4), decoded read-only here so engram_store.{c,h} stay untouched.
|
||||
*
|
||||
* Algorithm: Malkov & Yashunin, "Efficient and robust approximate nearest
|
||||
* neighbor search using Hierarchical Navigable Small World graphs" (2016).
|
||||
* - multi-layer graph; level ~ Exp(1/ln M), assigned by a per-node seeded PRNG
|
||||
* (deterministic: seed = FIXED_SEED ^ node_ordinal) so a rebuild is bit-for-
|
||||
* bit reproducible regardless of wall-clock or global rand() state.
|
||||
* - greedy descent through upper layers to an entry point, then an ef-bounded
|
||||
* best-first search at each layer (Algorithm 2).
|
||||
* - neighbour selection by the diversity heuristic (Algorithm 4), not plain
|
||||
* k-nearest, with keep-pruned backfill for connectivity.
|
||||
* - bidirectional links; a neighbour whose degree exceeds M (2M on layer 0) is
|
||||
* re-pruned with the same heuristic.
|
||||
*
|
||||
* Metric: vectors are L2-normalised on entry, so cosine similarity == dot
|
||||
* product; distance = 1 - dot (in [0,2], smaller == nearer). Deterministic tie-
|
||||
* breaks are by element index so results are stable across identical builds.
|
||||
*/
|
||||
#include "engram_vindex.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
/* Deterministic PRNG seed base (fixed constant — never wall-clock/rand). */
|
||||
#define VINDEX_FIXED_SEED 0x9E3779B97F4A7C15ULL
|
||||
|
||||
/* ── deterministic PRNG (splitmix64) ──────────────────────────────────────── */
|
||||
static inline uint64_t splitmix64(uint64_t* s){
|
||||
uint64_t z = (*s += 0x9E3779B97F4A7C15ULL);
|
||||
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ULL;
|
||||
z = (z ^ (z >> 27)) * 0x94D049BB133111EBULL;
|
||||
return z ^ (z >> 31);
|
||||
}
|
||||
/* Uniform double in (0,1]. */
|
||||
static inline double sm_uniform(uint64_t* s){
|
||||
/* 53-bit mantissa; +1 keeps it in (0,1] so log() never sees 0. */
|
||||
return ((double)((splitmix64(s) >> 11) + 1)) * (1.0 / 9007199254740993.0);
|
||||
}
|
||||
|
||||
/* ── element + index structures ───────────────────────────────────────────── */
|
||||
typedef struct {
|
||||
int count;
|
||||
int cap;
|
||||
int* ids; /* neighbour element indices */
|
||||
} NeighList;
|
||||
|
||||
typedef struct {
|
||||
uint64_t node_id;
|
||||
int level; /* top layer this element appears on (>=0) */
|
||||
float* vec; /* dim floats, L2-normalised */
|
||||
NeighList* links; /* level+1 lists; links[l] = neighbours at layer l */
|
||||
} Elem;
|
||||
|
||||
struct VIndex {
|
||||
int dim;
|
||||
int M; /* max neighbours per node, upper layers */
|
||||
int M0; /* == 2*M, layer 0 */
|
||||
int ef_construction;
|
||||
double mL; /* level normaliser = 1/ln(M) */
|
||||
|
||||
Elem* elems;
|
||||
size_t n;
|
||||
size_t cap;
|
||||
|
||||
int entry; /* entry-point element index, -1 if empty */
|
||||
int max_level; /* current top layer */
|
||||
|
||||
/* scratch: version-stamped visited set (O(1) reset). */
|
||||
uint32_t* visited;
|
||||
uint32_t visit_epoch;
|
||||
size_t visited_cap;
|
||||
};
|
||||
|
||||
/* ── small helpers ────────────────────────────────────────────────────────── */
|
||||
static float* vec_normalise_copy(const float* v, int dim){
|
||||
float* out = (float*)malloc((size_t)dim * sizeof(float));
|
||||
if (!out) return NULL;
|
||||
double ss = 0.0;
|
||||
for (int i=0;i<dim;i++) ss += (double)v[i]*(double)v[i];
|
||||
if (ss > 0.0){
|
||||
float inv = (float)(1.0 / sqrt(ss));
|
||||
for (int i=0;i<dim;i++) out[i] = v[i]*inv;
|
||||
} else {
|
||||
for (int i=0;i<dim;i++) out[i] = 0.0f; /* zero vector stays zero */
|
||||
}
|
||||
return out;
|
||||
}
|
||||
/* Cosine distance between two normalised vectors: 1 - dot. In [0,2].
|
||||
* Float accumulation in 4 lanes so the compiler auto-vectorises the hot path
|
||||
* (this is the dominant cost of both build and search). */
|
||||
static float vdist(const VIndex* ix, const float* a, const float* b){
|
||||
int dim = ix->dim;
|
||||
float s0=0,s1=0,s2=0,s3=0;
|
||||
int i=0;
|
||||
for (; i+4<=dim; i+=4){
|
||||
s0 += a[i]*b[i]; s1 += a[i+1]*b[i+1];
|
||||
s2 += a[i+2]*b[i+2]; s3 += a[i+3]*b[i+3];
|
||||
}
|
||||
float dot = (s0+s1)+(s2+s3);
|
||||
for (; i<dim; i++) dot += a[i]*b[i];
|
||||
return 1.0f - dot;
|
||||
}
|
||||
|
||||
static int nl_push(NeighList* nl, int id){
|
||||
if (nl->count == nl->cap){
|
||||
int nc = nl->cap ? nl->cap*2 : 4;
|
||||
int* np = (int*)realloc(nl->ids, (size_t)nc*sizeof(int));
|
||||
if (!np) return -1;
|
||||
nl->ids = np; nl->cap = nc;
|
||||
}
|
||||
nl->ids[nl->count++] = id;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ── binary heaps over (dist,elem) pairs ──────────────────────────────────── */
|
||||
typedef struct { float d; int e; } Pair;
|
||||
typedef struct { Pair* a; int n, cap; } Heap;
|
||||
|
||||
static int heap_reserve(Heap* h, int need){
|
||||
if (need <= h->cap) return 0;
|
||||
int nc = h->cap ? h->cap*2 : 16;
|
||||
while (nc < need) nc *= 2;
|
||||
Pair* na = (Pair*)realloc(h->a, (size_t)nc*sizeof(Pair));
|
||||
if (!na) return -1;
|
||||
h->a = na; h->cap = nc; return 0;
|
||||
}
|
||||
/* Order predicate: for a MAX-heap on distance, "higher priority" = larger dist;
|
||||
* ties broken by larger element index (deterministic + stable). is_max selects. */
|
||||
static inline int pair_before(Pair x, Pair y, int is_max){
|
||||
if (x.d != y.d) return is_max ? (x.d > y.d) : (x.d < y.d);
|
||||
return is_max ? (x.e > y.e) : (x.e < y.e);
|
||||
}
|
||||
static int heap_push(Heap* h, Pair v, int is_max){
|
||||
if (heap_reserve(h, h->n+1)) return -1;
|
||||
int i = h->n++;
|
||||
h->a[i] = v;
|
||||
while (i > 0){
|
||||
int p = (i-1)/2;
|
||||
if (pair_before(h->a[i], h->a[p], is_max)){
|
||||
Pair t=h->a[i]; h->a[i]=h->a[p]; h->a[p]=t; i=p;
|
||||
} else break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
static Pair heap_pop(Heap* h, int is_max){
|
||||
Pair top = h->a[0];
|
||||
h->a[0] = h->a[--h->n];
|
||||
int i = 0;
|
||||
for (;;){
|
||||
int l=2*i+1, r=2*i+2, best=i;
|
||||
if (l<h->n && pair_before(h->a[l], h->a[best], is_max)) best=l;
|
||||
if (r<h->n && pair_before(h->a[r], h->a[best], is_max)) best=r;
|
||||
if (best==i) break;
|
||||
Pair t=h->a[i]; h->a[i]=h->a[best]; h->a[best]=t; i=best;
|
||||
}
|
||||
return top;
|
||||
}
|
||||
|
||||
/* ── visited set ──────────────────────────────────────────────────────────── */
|
||||
static int visited_ensure(VIndex* ix){
|
||||
if (ix->visited_cap >= ix->cap && ix->visited) return 0;
|
||||
size_t nc = ix->cap ? ix->cap : 16;
|
||||
uint32_t* nv = (uint32_t*)realloc(ix->visited, nc*sizeof(uint32_t));
|
||||
if (!nv) return -1;
|
||||
if (nc > ix->visited_cap) memset(nv + ix->visited_cap, 0, (nc-ix->visited_cap)*sizeof(uint32_t));
|
||||
ix->visited = nv; ix->visited_cap = nc;
|
||||
return 0;
|
||||
}
|
||||
static inline void visited_reset(VIndex* ix){
|
||||
if (++ix->visit_epoch == 0){ /* wrapped: clear all */
|
||||
memset(ix->visited, 0, ix->visited_cap*sizeof(uint32_t));
|
||||
ix->visit_epoch = 1;
|
||||
}
|
||||
}
|
||||
static inline int is_visited(VIndex* ix, int e){ return ix->visited[e]==ix->visit_epoch; }
|
||||
static inline void mark_visited(VIndex* ix, int e){ ix->visited[e]=ix->visit_epoch; }
|
||||
|
||||
/* ── search one layer (Algorithm 2): best-first, ef-bounded ───────────────── */
|
||||
/* Returns results as an unsorted Heap (max-heap on distance, size<=ef). Caller
|
||||
* owns res->a. `q` is a normalised query. */
|
||||
static int search_layer(VIndex* ix, const float* q, const int* eps, int neps,
|
||||
int ef, int layer, Heap* res /*out, max-heap*/){
|
||||
Heap cand = {0,0,0}; /* min-heap: nearest to expand */
|
||||
res->a=NULL; res->n=0; res->cap=0;
|
||||
visited_reset(ix);
|
||||
for (int i=0;i<neps;i++){
|
||||
int e = eps[i];
|
||||
if (is_visited(ix,e)) continue;
|
||||
mark_visited(ix,e);
|
||||
float d = vdist(ix, q, ix->elems[e].vec);
|
||||
Pair p = { d, e };
|
||||
if (heap_push(&cand,p,0) || heap_push(res,p,1)){ free(cand.a); return -1; }
|
||||
}
|
||||
while (res->n > ef) heap_pop(res,1); /* trim to ef */
|
||||
|
||||
while (cand.n > 0){
|
||||
Pair c = heap_pop(&cand,0);
|
||||
float worst = res->a[0].d; /* farthest kept result */
|
||||
if (res->n >= ef && c.d > worst) break;
|
||||
Elem* ce = &ix->elems[c.e];
|
||||
if (layer <= ce->level){
|
||||
NeighList* nl = &ce->links[layer];
|
||||
for (int i=0;i<nl->count;i++){
|
||||
int e = nl->ids[i];
|
||||
if (is_visited(ix,e)) continue;
|
||||
mark_visited(ix,e);
|
||||
float d = vdist(ix, q, ix->elems[e].vec);
|
||||
if (res->n < ef || d < res->a[0].d){
|
||||
Pair p = { d, e };
|
||||
if (heap_push(&cand,p,0) || heap_push(res,p,1)){ free(cand.a); return -1; }
|
||||
if (res->n > ef) heap_pop(res,1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
free(cand.a);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ── neighbour selection heuristic (Algorithm 4) ──────────────────────────── */
|
||||
/* From candidate pairs W (any order), pick up to M diverse neighbours of q.
|
||||
* Keep c only if it is nearer to q than to every already-chosen neighbour;
|
||||
* backfill from the pruned set (nearest first) to reach M for connectivity.
|
||||
* Writes chosen element indices into out[], returns the count. */
|
||||
static int select_neighbors(VIndex* ix, const float* q, Pair* W, int nW, int M, int* out){
|
||||
(void)q; /* q's distances are precomputed in W[].d; kept for call-site clarity */
|
||||
/* sort W ascending by (dist,elem) — deterministic. */
|
||||
for (int i=1;i<nW;i++){ /* insertion sort (nW small) */
|
||||
Pair key=W[i]; int j=i-1;
|
||||
while (j>=0 && !pair_before(W[j],key,0)){ W[j+1]=W[j]; j--; }
|
||||
W[j+1]=key;
|
||||
}
|
||||
int nout = 0;
|
||||
Pair* pruned = (Pair*)malloc((size_t)(nW?nW:1)*sizeof(Pair));
|
||||
int npr = 0;
|
||||
if (!pruned) return -1;
|
||||
for (int i=0;i<nW && nout<M;i++){
|
||||
int good = 1;
|
||||
for (int j=0;j<nout;j++){
|
||||
float d = vdist(ix, ix->elems[W[i].e].vec, ix->elems[out[j]].vec);
|
||||
if (d < W[i].d){ good = 0; break; } /* nearer an existing pick → drop */
|
||||
}
|
||||
if (good) out[nout++] = W[i].e;
|
||||
else pruned[npr++] = W[i];
|
||||
}
|
||||
for (int i=0;i<npr && nout<M;i++) out[nout++] = pruned[i].e; /* keep-pruned backfill */
|
||||
free(pruned);
|
||||
return nout;
|
||||
}
|
||||
|
||||
/* Re-prune a neighbour's over-full adjacency list back to `Mmax`. */
|
||||
static void prune_links(VIndex* ix, int e, int layer, int Mmax){
|
||||
NeighList* nl = &ix->elems[e].links[layer];
|
||||
if (nl->count <= Mmax) return;
|
||||
const float* base = ix->elems[e].vec;
|
||||
Pair* W = (Pair*)malloc((size_t)nl->count*sizeof(Pair));
|
||||
if (!W) return;
|
||||
int nW = nl->count;
|
||||
for (int i=0;i<nW;i++) W[i] = (Pair){ vdist(ix, base, ix->elems[nl->ids[i]].vec), nl->ids[i] };
|
||||
int* keep = (int*)malloc((size_t)nW*sizeof(int));
|
||||
if (!keep){ free(W); return; }
|
||||
int nk = select_neighbors(ix, base, W, nW, Mmax, keep);
|
||||
if (nk >= 0){ nl->count = nk; for (int i=0;i<nk;i++) nl->ids[i]=keep[i]; }
|
||||
free(keep); free(W);
|
||||
}
|
||||
|
||||
/* ── insert ───────────────────────────────────────────────────────────────── */
|
||||
static int elems_reserve(VIndex* ix){
|
||||
if (ix->n < ix->cap) return 0;
|
||||
size_t nc = ix->cap ? ix->cap*2 : 64;
|
||||
Elem* ne = (Elem*)realloc(ix->elems, nc*sizeof(Elem));
|
||||
if (!ne) return -1;
|
||||
ix->elems = ne; ix->cap = nc;
|
||||
return visited_ensure(ix);
|
||||
}
|
||||
|
||||
int vindex_insert(VIndex* ix, uint64_t node_id, const float* vec){
|
||||
if (!ix || !vec) return -1;
|
||||
if (elems_reserve(ix)) return -1;
|
||||
|
||||
int cur = (int)ix->n;
|
||||
/* deterministic level assignment, seeded per-node. */
|
||||
uint64_t seed = VINDEX_FIXED_SEED ^ (node_id + 0x2545F4914F6CDD1DULL*(uint64_t)cur);
|
||||
int level = (int)(-log(sm_uniform(&seed)) * ix->mL);
|
||||
if (level < 0) level = 0;
|
||||
|
||||
Elem* el = &ix->elems[cur];
|
||||
el->node_id = node_id;
|
||||
el->level = level;
|
||||
el->vec = vec_normalise_copy(vec, ix->dim);
|
||||
el->links = (NeighList*)calloc((size_t)level+1, sizeof(NeighList));
|
||||
if (!el->vec || !el->links){ free(el->vec); free(el->links); return -1; }
|
||||
ix->n++;
|
||||
|
||||
if (ix->entry < 0){ /* first element */
|
||||
ix->entry = cur; ix->max_level = level;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int ep = ix->entry;
|
||||
int L = ix->max_level;
|
||||
/* greedy descent through layers above `level` to refine the entry point. */
|
||||
for (int lc = L; lc > level; lc--){
|
||||
Heap r = {0,0,0};
|
||||
int eps1[1] = { ep };
|
||||
if (search_layer(ix, el->vec, eps1, 1, 1, lc, &r)){ return -1; }
|
||||
if (r.n){ ep = r.a[0].e; float bd=r.a[0].d;
|
||||
for (int i=1;i<r.n;i++) if (r.a[i].d<bd){bd=r.a[i].d; ep=r.a[i].e;} }
|
||||
free(r.a);
|
||||
}
|
||||
/* from min(L,level) down to 0: connect. Each layer's ef-results seed the next
|
||||
* layer's entry set; `eps` is heap-owned below the top and freed each step. */
|
||||
int start = (L < level) ? L : level;
|
||||
int eps_stack[1] = { ep };
|
||||
int* eps = eps_stack; /* not owned (stack) until reassigned to malloc'd */
|
||||
int* eps_owned = NULL;
|
||||
int neps = 1;
|
||||
int rc = 0;
|
||||
for (int lc = start; lc >= 0; lc--){
|
||||
int Mmax = (lc==0) ? ix->M0 : ix->M;
|
||||
Heap W = {0,0,0};
|
||||
if (search_layer(ix, el->vec, eps, neps, ix->ef_construction, lc, &W)){ rc=-1; break; }
|
||||
int* chosen = (int*)malloc((size_t)(W.n?W.n:1)*sizeof(int));
|
||||
if (!chosen){ free(W.a); rc=-1; break; }
|
||||
int nc = select_neighbors(ix, el->vec, W.a, W.n, Mmax, chosen);
|
||||
if (nc < 0){ free(chosen); free(W.a); rc=-1; break; }
|
||||
/* link cur <-> chosen (bidirectional), prune neighbours if over-full. */
|
||||
for (int i=0;i<nc;i++){
|
||||
int nb = chosen[i];
|
||||
if (nl_push(&el->links[lc], nb) || nl_push(&ix->elems[nb].links[lc], cur)){
|
||||
free(chosen); free(W.a); rc=-1; goto done;
|
||||
}
|
||||
prune_links(ix, nb, lc, Mmax);
|
||||
}
|
||||
free(chosen);
|
||||
/* next layer's entry points = this layer's ef results. */
|
||||
if (lc > 0){
|
||||
int* neweps = (int*)malloc((size_t)(W.n?W.n:1)*sizeof(int));
|
||||
if (!neweps){ free(W.a); rc=-1; break; }
|
||||
for (int i=0;i<W.n;i++) neweps[i]=W.a[i].e;
|
||||
neps = W.n ? W.n : 1;
|
||||
if (!W.n) neweps[0] = eps[0]; /* fall back to prior ep if empty */
|
||||
free(eps_owned);
|
||||
eps = eps_owned = neweps;
|
||||
}
|
||||
free(W.a);
|
||||
}
|
||||
done:
|
||||
free(eps_owned);
|
||||
if (rc) return -1;
|
||||
if (level > ix->max_level){ ix->max_level = level; ix->entry = cur; }
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ── search ───────────────────────────────────────────────────────────────── */
|
||||
int vindex_search(VIndex* ix, const float* query, int k, int ef_search,
|
||||
uint64_t* node_id_out, float* dist_out){
|
||||
if (!ix || !query || k <= 0) return -1;
|
||||
if (ix->entry < 0) return 0;
|
||||
if (ef_search <= 0) ef_search = VINDEX_DEFAULT_EF_SEARCH;
|
||||
if (ef_search < k) ef_search = k;
|
||||
|
||||
float* q = vec_normalise_copy(query, ix->dim);
|
||||
if (!q) return -1;
|
||||
|
||||
int ep = ix->entry;
|
||||
for (int lc = ix->max_level; lc > 0; lc--){
|
||||
Heap r = {0,0,0};
|
||||
int eps[1] = { ep };
|
||||
if (search_layer(ix, q, eps, 1, 1, lc, &r)){ free(q); return -1; }
|
||||
if (r.n){ int b=r.a[0].e; float bd=r.a[0].d;
|
||||
for (int i=1;i<r.n;i++) if (r.a[i].d<bd){bd=r.a[i].d; b=r.a[i].e;}
|
||||
ep = b; }
|
||||
free(r.a);
|
||||
}
|
||||
Heap res = {0,0,0};
|
||||
int eps[1] = { ep };
|
||||
if (search_layer(ix, q, eps, 1, ef_search, 0, &res)){ free(res.a); free(q); return -1; }
|
||||
free(q);
|
||||
|
||||
/* res is a max-heap of size<=ef; pop into ascending order, keep nearest k. */
|
||||
int total = res.n;
|
||||
Pair* sorted = (Pair*)malloc((size_t)(total?total:1)*sizeof(Pair));
|
||||
if (!sorted){ free(res.a); return -1; }
|
||||
for (int i=total-1;i>=0;i--) sorted[i] = heap_pop(&res,1); /* farthest first out → fill from end */
|
||||
free(res.a);
|
||||
|
||||
int out_n = (k < total) ? k : total;
|
||||
for (int i=0;i<out_n;i++){
|
||||
if (node_id_out) node_id_out[i] = ix->elems[sorted[i].e].node_id;
|
||||
if (dist_out) dist_out[i] = sorted[i].d;
|
||||
}
|
||||
free(sorted);
|
||||
return out_n;
|
||||
}
|
||||
|
||||
size_t vindex_size(const VIndex* ix){ return ix ? ix->n : 0; }
|
||||
|
||||
VIndex* vindex_create(int dim, int M, int ef_construction){
|
||||
if (dim <= 0) return NULL;
|
||||
if (M <= 0) M = VINDEX_DEFAULT_M;
|
||||
if (ef_construction <= 0) ef_construction = VINDEX_DEFAULT_EF_CONSTRUCTION;
|
||||
VIndex* ix = (VIndex*)calloc(1, sizeof(VIndex));
|
||||
if (!ix) return NULL;
|
||||
ix->dim = dim;
|
||||
ix->M = M;
|
||||
ix->M0 = 2*M;
|
||||
ix->ef_construction = ef_construction;
|
||||
ix->mL = 1.0 / log((double)M > 1.0 ? (double)M : 2.0);
|
||||
ix->entry = -1;
|
||||
ix->max_level = 0;
|
||||
ix->visit_epoch = 0;
|
||||
return ix;
|
||||
}
|
||||
|
||||
void vindex_free(VIndex* ix){
|
||||
if (!ix) return;
|
||||
for (size_t i=0;i<ix->n;i++){
|
||||
Elem* e = &ix->elems[i];
|
||||
if (e->links) for (int l=0;l<=e->level;l++) free(e->links[l].ids);
|
||||
free(e->links);
|
||||
free(e->vec);
|
||||
}
|
||||
free(ix->elems);
|
||||
free(ix->visited);
|
||||
free(ix);
|
||||
}
|
||||
|
||||
/* ── read-only decode of the paged store node format (design §2.4) ─────────── */
|
||||
/* Mirrors engram_store.c constants; the on-disk format is PERMANENT so these are
|
||||
* safe to duplicate for a read-only harvest of emb vectors. */
|
||||
#define VS_PAGE_SIZE 16384u
|
||||
#define VS_HDR 32u
|
||||
#define VS_SLOT_SIZE 6u
|
||||
#define VS_SLOT_LIVE 1u
|
||||
#define VS_REC_HDR 4u
|
||||
#define VS_REC_OVERFLOW 1u
|
||||
#define VS_PT_NODE 1u
|
||||
#define VS_OVF_NEXT 32u
|
||||
#define VS_OVF_LEN 40u
|
||||
#define VS_OVF_DATA 44u
|
||||
#define VS_NT_ID 1u
|
||||
#define VS_NT_EMB 24u
|
||||
#define VS_NT_EMB_DIM 25u
|
||||
|
||||
static uint16_t vg_u16(const uint8_t* p){ return (uint16_t)(p[0] | (p[1]<<8)); }
|
||||
static uint32_t vg_u32(const uint8_t* p){ uint32_t v=0; for(int i=0;i<4;i++) v|=(uint32_t)p[i]<<(8*i); return v; }
|
||||
static uint64_t vg_u64(const uint8_t* p){ uint64_t v=0; for(int i=0;i<8;i++) v|=(uint64_t)p[i]<<(8*i); return v; }
|
||||
|
||||
static int vs_pread(int fd, uint64_t page, uint8_t* buf){
|
||||
off_t off = (off_t)page * VS_PAGE_SIZE;
|
||||
ssize_t r = pread(fd, buf, VS_PAGE_SIZE, off);
|
||||
return (r == (ssize_t)VS_PAGE_SIZE) ? 0 : -1;
|
||||
}
|
||||
/* Read a (possibly overflowed) record body; caller frees *out. */
|
||||
static int vs_read_body(int fd, const uint8_t* page, uint16_t off, uint16_t len,
|
||||
uint8_t** out, size_t* outlen){
|
||||
if (len < VS_REC_HDR) return -1;
|
||||
uint8_t flags = page[off+3];
|
||||
if (flags & VS_REC_OVERFLOW){
|
||||
uint64_t head = vg_u64(page + off + VS_REC_HDR);
|
||||
uint64_t total = vg_u64(page + off + VS_REC_HDR + 8);
|
||||
uint8_t* body = (uint8_t*)malloc(total ? total : 1);
|
||||
if (!body) return -1;
|
||||
size_t got=0; uint64_t id=head;
|
||||
uint8_t ov[VS_PAGE_SIZE];
|
||||
while (id){
|
||||
if (vs_pread(fd, id, ov)){ free(body); return -1; }
|
||||
uint32_t chunk = vg_u32(ov + VS_OVF_LEN);
|
||||
if (got + chunk > total){ free(body); return -1; }
|
||||
memcpy(body+got, ov+VS_OVF_DATA, chunk); got += chunk;
|
||||
id = vg_u64(ov + VS_OVF_NEXT);
|
||||
}
|
||||
if (got != total){ free(body); return -1; }
|
||||
*out = body; *outlen = total;
|
||||
} else {
|
||||
uint16_t reclen = vg_u16(page + off);
|
||||
if (reclen < VS_REC_HDR) return -1;
|
||||
size_t blen = reclen - VS_REC_HDR;
|
||||
uint8_t* body = (uint8_t*)malloc(blen ? blen : 1);
|
||||
if (!body) return -1;
|
||||
memcpy(body, page + off + VS_REC_HDR, blen);
|
||||
*out = body; *outlen = blen;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
/* Extract id (strdup) and emb (malloc'd float[dim]) from a TLV node body. */
|
||||
static void vs_parse_node(const uint8_t* body, size_t len, char** id_out,
|
||||
float** emb_out, int* dim_out){
|
||||
*id_out=NULL; *emb_out=NULL; *dim_out=0;
|
||||
size_t i=0;
|
||||
while (i + 5 <= len){
|
||||
uint8_t tag = body[i];
|
||||
uint32_t flen = vg_u32(body + i + 1);
|
||||
if (i + 5 + (size_t)flen > len) break;
|
||||
const uint8_t* v = body + i + 5;
|
||||
if (tag == VS_NT_ID){
|
||||
char* s = (char*)malloc(flen+1);
|
||||
if (s){ memcpy(s,v,flen); s[flen]=0; free(*id_out); *id_out=s; }
|
||||
} else if (tag == VS_NT_EMB){
|
||||
int dim = (int)(flen/4);
|
||||
float* e = (float*)malloc((size_t)(dim?dim:1)*sizeof(float));
|
||||
if (e){ for (int k=0;k<dim;k++){ uint32_t u=vg_u32(v+k*4); memcpy(&e[k],&u,4);}
|
||||
free(*emb_out); *emb_out=e; if(*dim_out==0) *dim_out=dim; }
|
||||
} else if (tag == VS_NT_EMB_DIM){
|
||||
*dim_out = (int)vg_u32(v);
|
||||
}
|
||||
i += 5 + flen;
|
||||
}
|
||||
}
|
||||
|
||||
/* Tiny open-addressing string set to dedup ids across live records. */
|
||||
typedef struct { char** k; size_t cap, n; } StrSet;
|
||||
static uint64_t vs_fnv(const char* s){ uint64_t h=1469598103934665603ULL; for(;*s;++s){h^=(uint8_t)*s;h*=1099511628211ULL;} return h; }
|
||||
static int strset_add(StrSet* s, const char* key){ /* 1 added, 0 dup, -1 err */
|
||||
if (s->n*2 >= s->cap){
|
||||
size_t nc = s->cap ? s->cap*2 : 1024;
|
||||
char** nk = (char**)calloc(nc, sizeof(char*));
|
||||
if (!nk) return -1;
|
||||
for (size_t i=0;i<s->cap;i++) if (s->k[i]){ size_t j=vs_fnv(s->k[i])&(nc-1); while(nk[j]) j=(j+1)&(nc-1); nk[j]=s->k[i]; }
|
||||
free(s->k); s->k=nk; s->cap=nc;
|
||||
}
|
||||
size_t j = vs_fnv(key)&(s->cap-1);
|
||||
while (s->k[j]){ if (strcmp(s->k[j],key)==0) return 0; j=(j+1)&(s->cap-1); }
|
||||
char* d = strdup(key); if(!d) return -1;
|
||||
s->k[j]=d; s->n++;
|
||||
return 1;
|
||||
}
|
||||
static void strset_free(StrSet* s){ for(size_t i=0;i<s->cap;i++) free(s->k[i]); free(s->k); }
|
||||
|
||||
int vindex_build_from_store(VIndex* ix, const char* store_path,
|
||||
char*** ids_out, int* n_out){
|
||||
if (!ix || !store_path) return -1;
|
||||
int fd = open(store_path, O_RDONLY);
|
||||
if (fd < 0) return -1;
|
||||
struct stat st;
|
||||
if (fstat(fd, &st) != 0){ close(fd); return -1; }
|
||||
uint64_t npages = (uint64_t)st.st_size / VS_PAGE_SIZE;
|
||||
|
||||
char** ids = NULL; size_t ids_n = 0, ids_cap = 0;
|
||||
StrSet seen = {0,0,0};
|
||||
int inserted = 0;
|
||||
uint8_t page[VS_PAGE_SIZE];
|
||||
|
||||
for (uint64_t pg = 2; pg < npages; pg++){ /* pages 0,1 = superblocks */
|
||||
if (vs_pread(fd, pg, page)) continue;
|
||||
if (page[8] != VS_PT_NODE) continue;
|
||||
int slots = vg_u16(page + 10);
|
||||
for (int sidx=0; sidx<slots; sidx++){
|
||||
const uint8_t* sp = page + VS_HDR + (size_t)sidx*VS_SLOT_SIZE;
|
||||
uint16_t off = vg_u16(sp), len = vg_u16(sp+2), fl = vg_u16(sp+4);
|
||||
if (fl != VS_SLOT_LIVE) continue;
|
||||
if ((size_t)off + VS_REC_HDR > VS_PAGE_SIZE) continue;
|
||||
uint8_t* body=NULL; size_t blen=0;
|
||||
if (vs_read_body(fd, page, off, len, &body, &blen)) continue;
|
||||
char* id=NULL; float* emb=NULL; int dim=0;
|
||||
vs_parse_node(body, blen, &id, &emb, &dim);
|
||||
free(body);
|
||||
if (!id || !emb || dim != ix->dim){ free(id); free(emb); continue; }
|
||||
int add = strset_add(&seen, id);
|
||||
if (add <= 0){ free(id); free(emb); continue; } /* dup or err */
|
||||
if (vindex_insert(ix, (uint64_t)inserted, emb) != 0){ free(id); free(emb); break; }
|
||||
free(emb);
|
||||
if (ids_n == ids_cap){
|
||||
size_t nc = ids_cap ? ids_cap*2 : 256;
|
||||
char** ni = (char**)realloc(ids, nc*sizeof(char*));
|
||||
if (!ni){ free(id); break; }
|
||||
ids = ni; ids_cap = nc;
|
||||
}
|
||||
ids[ids_n++] = id; /* transfers ownership */
|
||||
inserted++;
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
strset_free(&seen);
|
||||
if (ids_out){ *ids_out = ids; if (n_out) *n_out = (int)ids_n; }
|
||||
else { for (size_t i=0;i<ids_n;i++) free(ids[i]); free(ids); if (n_out) *n_out=(int)ids_n; }
|
||||
return inserted;
|
||||
}
|
||||
|
||||
/* ── optional persistence (index is rebuildable; convenience only) ─────────── */
|
||||
#define VINDEX_SAVE_MAGIC "EGVIDX01"
|
||||
int vindex_save(const VIndex* ix, const char* path){
|
||||
if (!ix || !path) return -1;
|
||||
FILE* f = fopen(path, "wb");
|
||||
if (!f) return -1;
|
||||
int ok = 1;
|
||||
#define WR(p,n) do{ if(fwrite((p),1,(n),f)!=(size_t)(n)) ok=0; }while(0)
|
||||
WR(VINDEX_SAVE_MAGIC, 8);
|
||||
int32_t hdr[6] = { ix->dim, ix->M, ix->ef_construction, (int32_t)ix->n, ix->entry, ix->max_level };
|
||||
WR(hdr, sizeof(hdr));
|
||||
for (size_t i=0; ok && i<ix->n; i++){
|
||||
Elem* e = &ix->elems[i];
|
||||
WR(&e->node_id, sizeof(uint64_t));
|
||||
int32_t lvl = e->level; WR(&lvl, sizeof(int32_t));
|
||||
WR(e->vec, (size_t)ix->dim*sizeof(float));
|
||||
for (int l=0; ok && l<=e->level; l++){
|
||||
int32_t c = e->links[l].count; WR(&c, sizeof(int32_t));
|
||||
WR(e->links[l].ids, (size_t)c*sizeof(int));
|
||||
}
|
||||
}
|
||||
#undef WR
|
||||
fclose(f);
|
||||
return ok ? 0 : -1;
|
||||
}
|
||||
VIndex* vindex_load(const char* path){
|
||||
FILE* f = fopen(path, "rb");
|
||||
if (!f) return NULL;
|
||||
char magic[8];
|
||||
if (fread(magic,1,8,f)!=8 || memcmp(magic,VINDEX_SAVE_MAGIC,8)!=0){ fclose(f); return NULL; }
|
||||
int32_t hdr[6];
|
||||
if (fread(hdr,sizeof(hdr),1,f)!=1){ fclose(f); return NULL; }
|
||||
VIndex* ix = vindex_create(hdr[0], hdr[1], hdr[2]);
|
||||
if (!ix){ fclose(f); return NULL; }
|
||||
size_t N = (size_t)hdr[3];
|
||||
int ok = 1;
|
||||
for (size_t i=0; ok && i<N; i++){
|
||||
if (elems_reserve(ix)){ ok=0; break; }
|
||||
Elem* e = &ix->elems[ix->n];
|
||||
int32_t lvl;
|
||||
if (fread(&e->node_id,sizeof(uint64_t),1,f)!=1 || fread(&lvl,sizeof(int32_t),1,f)!=1){ ok=0; break; }
|
||||
e->level = lvl;
|
||||
e->vec = (float*)malloc((size_t)ix->dim*sizeof(float));
|
||||
e->links = (NeighList*)calloc((size_t)lvl+1, sizeof(NeighList));
|
||||
if (!e->vec || !e->links){ free(e->vec); free(e->links); ok=0; break; }
|
||||
if (fread(e->vec,sizeof(float),(size_t)ix->dim,f)!=(size_t)ix->dim){ ok=0; }
|
||||
for (int l=0; ok && l<=lvl; l++){
|
||||
int32_t c; if (fread(&c,sizeof(int32_t),1,f)!=1){ ok=0; break; }
|
||||
e->links[l].ids = (int*)malloc((size_t)(c?c:1)*sizeof(int));
|
||||
e->links[l].cap = c; e->links[l].count = c;
|
||||
if (c && fread(e->links[l].ids,sizeof(int),(size_t)c,f)!=(size_t)c){ ok=0; }
|
||||
}
|
||||
ix->n++;
|
||||
}
|
||||
ix->entry = hdr[4]; ix->max_level = hdr[5];
|
||||
fclose(f);
|
||||
if (!ok){ vindex_free(ix); return NULL; }
|
||||
return ix;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/* engram_vindex.h — M8 of the engram query engine: an approximate-nearest-
|
||||
* neighbour (ANN) vector index over the node embedding vectors, for fast
|
||||
* activation-seed selection.
|
||||
*
|
||||
* Replaces the O(n) cosine scan over emb vectors (design §9 M8; backlog #20)
|
||||
* with an HNSW (Hierarchical Navigable Small World) graph that returns
|
||||
* high-recall top-k seeds in ~O(log n).
|
||||
*
|
||||
* Standalone module: plain C11, stdlib + libm only. It does NOT modify the
|
||||
* store format or engram_store.{c,h}; vindex_build_from_store() decodes the
|
||||
* PERMANENT on-disk node format (design §2.4) read-only to harvest emb vectors.
|
||||
*
|
||||
* Similarity metric: cosine. Vectors are L2-normalised on insert/query, so
|
||||
* cosine similarity == dot product. Reported distance = 1 - cosine_similarity
|
||||
* (range [0,2]); smaller == closer. A query equal to an indexed vector scores
|
||||
* distance ~0 against it.
|
||||
*
|
||||
* The index is fully rebuildable from the store, so persistence is optional for
|
||||
* this milestone (see vindex_save/vindex_load below — provided as a convenience;
|
||||
* boot may simply rebuild via vindex_build_from_store()).
|
||||
*/
|
||||
#ifndef ENGRAM_VINDEX_H
|
||||
#define ENGRAM_VINDEX_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* Tuned defaults (rationale in engram_vindex.c). Pass 0 to vindex_create for
|
||||
* M / ef_construction to take these; pass ef_search<=0 to vindex_search for
|
||||
* VINDEX_DEFAULT_EF_SEARCH. */
|
||||
#define VINDEX_DEFAULT_M 24
|
||||
#define VINDEX_DEFAULT_EF_CONSTRUCTION 200
|
||||
#define VINDEX_DEFAULT_EF_SEARCH 128
|
||||
|
||||
typedef struct VIndex VIndex;
|
||||
|
||||
/* Create an index over `dim`-dimensional f32 vectors.
|
||||
* M — max neighbours per node on upper layers (2*M on layer 0).
|
||||
* ef_construction — candidate-list width during insert (recall/build cost).
|
||||
* Pass M<=0 or ef_construction<=0 to use the VINDEX_DEFAULT_* above.
|
||||
* Returns NULL on bad args / OOM. */
|
||||
VIndex* vindex_create(int dim, int M, int ef_construction);
|
||||
|
||||
/* Insert one vector under an opaque caller-defined node_id (need not be unique,
|
||||
* but the caller is responsible for meaning). `vec` has `dim` floats; it is
|
||||
* copied and L2-normalised internally. A zero vector is accepted (it simply has
|
||||
* distance ~1 to everything; never produces NaN). Returns 0 on success, <0 on
|
||||
* error (bad args / OOM). */
|
||||
int vindex_insert(VIndex* idx, uint64_t node_id, const float* vec);
|
||||
|
||||
/* Top-k search by cosine similarity. Writes up to k results (fewer if the index
|
||||
* holds fewer than k elements) into node_id_out[] / dist_out[], ordered nearest
|
||||
* first (ascending distance). Either out array may be NULL to skip it.
|
||||
* ef_search — search-time candidate width; larger == higher recall, slower.
|
||||
* Pass <=0 for VINDEX_DEFAULT_EF_SEARCH. Internally clamped to >=k.
|
||||
* Returns the number of results written, or <0 on error. */
|
||||
int vindex_search(VIndex* idx, const float* query, int k, int ef_search,
|
||||
uint64_t* node_id_out, float* dist_out);
|
||||
|
||||
/* Number of vectors currently indexed. */
|
||||
size_t vindex_size(const VIndex* idx);
|
||||
|
||||
void vindex_free(VIndex* idx);
|
||||
|
||||
/* Build an index by scanning every live node record in the paged store at
|
||||
* `store_path` (the on-disk format is decoded read-only; the store need not be
|
||||
* open). Nodes without an emb vector, or whose emb_dim != idx->dim, are skipped.
|
||||
* Each inserted node is assigned node_id = its 0-based insertion ordinal; if
|
||||
* `ids_out`/`n_out` are non-NULL, *ids_out is set to a malloc'd array of that
|
||||
* many strdup'd string ids (ids_out[node_id] == the store id) and *n_out to the
|
||||
* count — the caller frees each string and the array. Returns the number of
|
||||
* vectors inserted, or <0 on error. */
|
||||
int vindex_build_from_store(VIndex* idx, const char* store_path,
|
||||
char*** ids_out, int* n_out);
|
||||
|
||||
/* Optional persistence (index is rebuildable from the store; provided for
|
||||
* convenience). vindex_save writes a self-describing snapshot; vindex_load
|
||||
* reconstructs an index from one. Return 0 / non-NULL on success. */
|
||||
int vindex_save(const VIndex* idx, const char* path);
|
||||
VIndex* vindex_load(const char* path);
|
||||
|
||||
#endif /* ENGRAM_VINDEX_H */
|
||||
@@ -1,4 +1,27 @@
|
||||
# Decorator-as-seam — what's REAL vs STAGED (with the exact diff)
|
||||
# Decorator-as-seam — IMPLEMENTED + PROVEN ON CLONE (2026-08-14)
|
||||
|
||||
> **UPDATE — no longer staged. The boundary auto-emit is BUILT and PROVEN on the
|
||||
> clone.** Will waived the diff review. Implemented: `engram_boundary_beat()` in
|
||||
> `lang/runtime/el_runtime.c` (afferent counter++, `engram_chrono_tick`,
|
||||
> `engram_strengthen(self-anchor)`, `dharma_emit`) + two act-stats counters
|
||||
> (`aff_boundary_ops`, `dharma_emits`); `cg_fn` in `lang/el-compiler/src/codegen.el`
|
||||
> injects ONE `engram_boundary_beat(op)` at the entry of every `@manager`/`@accessor`
|
||||
> fn (via `fn_has_decorator`, so it also fires under `@route @manager` stacking).
|
||||
> Rebuilt `elc` self-host + the **cognition engram** in the worktree; ran it as the
|
||||
> clone daemon on `:8900`.
|
||||
>
|
||||
> **Proof** — `/api/boundary-proof` (`@manager`, body = one `return`, ZERO
|
||||
> instrumentation) called 5×:
|
||||
> - afferent `aff_boundary_ops` 0→5 · dharma `dharma_emits` 0→5
|
||||
> - strengthen: self `activation_count` 1510→1513, salience 0.9→1.0
|
||||
> - chronoception: `chrono_last_tick` 1786760357885→1786760381676
|
||||
>
|
||||
> All four auto-fired from the decoration alone; daemon stayed alive; live `:8742`
|
||||
> untouched. The original staged design is retained below for the record.
|
||||
|
||||
---
|
||||
|
||||
# Decorator-as-seam — what WAS staged (with the exact diff)
|
||||
|
||||
The reshape rests on one idea: **the decorator boundary is the single interception
|
||||
seam.** Decorate a function with its `@route` + VBD role and the fabric gives, for
|
||||
|
||||
Reference in New Issue
Block a user