diff --git a/mcp-wrapper/src/main.el b/mcp-wrapper/src/main.el index a9636ee..d1b1606 100644 --- a/mcp-wrapper/src/main.el +++ b/mcp-wrapper/src/main.el @@ -38,6 +38,46 @@ fn soul_url() -> String { return u } +// engram_url — base for the ENGRAM's own routes (:8742). The Layer-2 agentic +// primitives (think/attend/assert/ground/correspondence-beat) are served by the +// engram directly, NOT by the soul — they are engram_*_json builtins routed in +// engram/src/server.el. Pointing them at the soul yields a 404, which the old +// agentic_result() gate then mislabelled as "pending cognition promotion". +// Resolution order, most-specific first, so nothing has to be duplicated: +// 1. ENGRAM_URL — a full override, if someone points at a remote engram +// 2. ENGRAM_BIND — the SAME var launchd already sets for the engram itself +// (ai.neuron.engram.plist: ENGRAM_BIND=":8742"). Reusing it +// means the port lives in exactly one place; change the +// plist and the wrapper follows instead of silently drifting. +// 3. ":8742" — last-resort default, matching the shipped plist. +fn engram_url() -> String { + let u: String = env("ENGRAM_URL") + if !str_eq(u, "") { return u } + let bind: String = env("ENGRAM_BIND") + let b: String = if str_eq(bind, "") { ":8742" } else { bind } + // ENGRAM_BIND is ":8742" or "0.0.0.0:8742" — take whatever follows the colon. + let idx: Int = str_last_index_of(b, ":") + let port: String = if idx < 0 { b } else { str_slice(b, idx + 1, str_len(b)) } + return "http://127.0.0.1:" + port +} + +// engram_key — the engram's API key, read from the SAME env var launchd sets on +// the engram itself (ai.neuron.engram.plist: ENGRAM_API_KEY). The engram's +// check_auth_ok() lets GETs through unauthenticated but requires mutating POSTs +// to carry "_auth":"" in the JSON body (it cannot read request headers yet). +// Returns "" when unset, which is also when the engram disables auth entirely. +fn engram_key() -> String { + return env("ENGRAM_API_KEY") +} + +// auth_field — the leading "_auth":"...", fragment for a POST body, or "" when +// no key is configured. Kept as a helper so no call site hand-rolls the JSON. +fn auth_field() -> String { + let k: String = engram_key() + if str_eq(k, "") { return "" } + return "\"_auth\":\"" + json_escape(k) + "\"," +} + // neuron_url — base for all /api/neuron/* cognitive routes on the soul fn neuron_url() -> String { return soul_url() + "/api/neuron" @@ -293,8 +333,108 @@ fn sc_list_state_events() -> String { ) } +// ── Collapsed-surface input schemas (the 9 geometry + agentic ops) ──────────── + +fn schema_read() -> String { + return obj_schema( + prop("vantage", "string", "Where to read FROM: a node-id (kn-.../mem-.../gn-...), a named root (self | neuron | values), or a concept string to search. Required.") + + "," + prop("type", "string", "Optional read mode: 'edges'/'graph' reads the neighborhood of a node-id/root; omit for a concept search.") + + "," + prop("k", "integer", "APERTURE width — max items / top-K neighbors returned. Bounds output (the whole-self-dump fix). Default 12.") + + "," + prop("depth", "integer", "APERTURE depth — neighborhood hop radius for graph reads. Default 1.") + ) +} + +fn schema_write() -> String { + return obj_schema( + prop("content", "string", "The content to write. Required.") + + "," + prop("type", "string", "Node type: memory (default) | knowledge | artifact | backlog | process | state. 'self'/'values' are refused — identity is write-protected.") + + "," + prop("tags", "string", "Optional tags (comma-separated or JSON array).") + + "," + prop("importance", "string", "Optional: low | normal | high | critical.") + + "," + prop("title", "string", "Optional title/label (knowledge / artifact / backlog).") + + "," + prop("project", "string", "Optional project tag.") + ) +} + +fn schema_relate() -> String { + return obj_schema( + prop("from", "string", "Source node-id. Required.") + + "," + prop("to", "string", "Target node-id. Required.") + + "," + prop("relationship", "string", "Edge relation. Default 'associates'.") + ) +} + +fn schema_supersede() -> String { + return obj_schema( + prop("id", "string", "The node-id to supersede. Required.") + + "," + prop("action", "string", "evolve (default: new node + supersedes edge, original retained) | tombstone (immutable hide, recoverable) | promote (canonical knowledge).") + + "," + prop("content", "string", "New content (required for evolve/promote).") + + "," + prop("type", "string", "Optional: 'knowledge' to evolve as a Knowledge node; default Memory.") + ) +} + +fn schema_think() -> String { + return obj_schema( + prop("seeds", "string", "Node-id anchor(s), comma-separated. Required.") + + "," + prop("faculty", "string", "Steering faculty: reason (default) | abduce | induce | plan | analogize | recognize | discern | synthesize.") + ) +} + +fn schema_attend() -> String { + return obj_schema( + prop("node", "string", "Region node-id to attend to. Required.") + + "," + prop("observer", "string", "Optional observer id / vantage.") + + "," + prop("salience", "string", "Optional salience weighting.") + ) +} + +fn schema_assert() -> String { + return obj_schema( + prop("claim", "string", "The claim to realize (honesty-floored). Required.") + + "," + prop("for_whom", "string", "Optional audience / vantage.") + + "," + prop("floor", "string", "Optional honesty-floor threshold.") + ) +} + +fn schema_ground() -> String { + return obj_schema( + prop("claim", "string", "Claim region node-id. Required.") + + "," + prop("evidence", "string", "Evidence region node-id. Required.") + + "," + prop("for_whom", "string", "Optional audience / vantage.") + ) +} + +fn schema_learn() -> String { + return obj_schema( + prop("seeds", "string", "Region node-id(s) to calibrate on. Required.") + + "," + prop("faculty", "string", "Faculty for the correspondence-beat. Default 'induce'.") + + "," + prop("keystone", "string", "Optional keystone anchor.") + ) +} + +// tools_catalog — THE COLLAPSED SURFACE. 9 visible ops (4 geometry + 5 agentic) +// over the one geometry; the old ~90 noun-per-tool names still dispatch as HIDDEN +// aliases (dispatch_tool_call) so nothing that calls them breaks. Design source: +// engram/tools/api-reshape/README.md (artifact 0e828907, design-brief 2b8078cf §5). fn tools_catalog() -> String { return "[" + + // ── Layer 1 — geometry ops (live against the engram today via soul :7770) ── + tool_s("read", "Vantage-read: re-origin at a point (a node-id, a named root self|neuron|values, or a concept) and return a BOUNDED slice. The aperture (k/depth) caps output — this is the whole-self-dump fix. Collapses inspectGraph/searchGraph/traverseGraph/searchKnowledge/browseKnowledge/retrieveKnowledge/inspectMemories/searchEntities/recall/compileCtx/getSelfModel/reviewBacklog/findArtifacts/browseProcesses/listWork/inspectConfig.", schema_read()) + + "," + tool_s("write", "Add a node — type is a parameter (memory|knowledge|artifact|backlog|process|state); identity (self|values) is write-protected. Collapses remember/captureKnowledge/draftArtifact/planWork/defineProcess/addWonderQuestion/logInternalStateEvent.", schema_write()) + + "," + tool_s("relate", "Create a typed edge between two node-ids. Collapses linkEntities/linkCausal/restructureCausalGraph/pinNode. Identity keystones are write-protected.", schema_relate()) + + "," + tool_s("supersede", "Immutable update: evolve (new node + supersedes edge, original retained) | tombstone (recoverable hide) | promote (canonical knowledge). Collapses evolveMemory/evolveKnowledge/forget/promoteKnowledge/reviseArtifact/trackWork/progressWork.", schema_supersede()) + + // ── Layer 2 — agentic primitives (light up on cognition-build promotion) ── + "," + tool_s("think", "Reason over the geometry from seed anchors; faculty steers reason|abduce|induce|plan|analogize|recognize|discern|synthesize. Pending cognition-build promotion on the live engram.", schema_think()) + + "," + tool_s("attend", "Aim attention at a region node. Pending cognition-build promotion.", schema_attend()) + + "," + tool_s("assert", "Realize a claim, honesty-floored. Pending cognition-build promotion.", schema_assert()) + + "," + tool_s("ground", "Ground a claim against evidence regions. Pending cognition-build promotion.", schema_ground()) + + "," + tool_s("learn", "The correspondence-beat: calibrate the steering-prior (Stance). Pending cognition-build promotion.", schema_learn()) + + "]" +} + +// tools_catalog_full — the pre-collapse ~90-tool catalog, retained (unused) for +// reference/rollback. The 9-op tools_catalog above is what tools/list returns. +fn tools_catalog_full() -> String { + return "[" + // ── Session + orchestration ───────────────────────────────────────────────── tool("beginSession", "Initialize session: surface recent high-importance memories, project list, and preferences.") + "," + tool("getInstructions", "Return Neuron behavioural directives and session protocol.") + @@ -417,6 +557,10 @@ fn fire_activation(seed: String) -> String { // pick_activation_seed — extract the best semantic seed from a tool call's args. // Priority: query > content > title > description > summary > action > name. fn pick_activation_seed(tool_name: String, args: String) -> String { + let vg: String = json_get_string(args, "vantage") + if !str_eq(vg, "") { return vg } + let sd: String = json_get_string(args, "seeds") + if !str_eq(sd, "") { return sd } let q: String = json_get_string(args, "query") if !str_eq(q, "") { return q } let c: String = json_get_string(args, "content") @@ -838,6 +982,236 @@ fn tool_inspect_config(args: String) -> String { return mcp_json_result(resp) } +// ── Collapsed-surface op handlers (the 9 visible ops) ───────────────────────── +// Each re-faces the SAME proven soul :7770 /api/neuron/* routes the 87 aliases use, +// so Layer-1 works against live today. Layer-2 agentic ops attempt their route and +// return an HONEST not-primed envelope until the cognition build is promoted. + +// Identity keystones — write-protected (self root + values hub). +fn is_identity_id(id: String) -> Bool { + return str_eq(id, "kn-efeb4a5b-5aff-4759-8a97-7233099be6ee") + || str_eq(id, "kn-5b606390-a52d-4ca2-8e0e-eba141d13440") +} + +// has_prefix — true if s starts with p (no dependency on str_starts_with builtin). +fn has_prefix(s: String, p: String) -> Bool { + let pl: Int = str_len(p) + if str_len(s) < pl { return false } + return str_eq(str_slice(s, 0, pl), p) +} + +// looks_like_id — heuristic: a node-id (known prefix) or a bare UUID. +fn looks_like_id(v: String) -> Bool { + if has_prefix(v, "kn-") { return true } + if has_prefix(v, "mem-") { return true } + if has_prefix(v, "mn-") { return true } + if has_prefix(v, "gn-") { return true } + if has_prefix(v, "bl-") { return true } + if has_prefix(v, "art-") { return true } + if has_prefix(v, "ctx-") { return true } + if has_prefix(v, "nt-") { return true } + if str_len(v) >= 32 && str_index_of(v, "-") > 0 && str_index_of(v, " ") < 0 { return true } + return false +} + +fn is_named_root(v: String) -> Bool { + return str_eq(v, "self") || str_eq(v, "neuron") || str_eq(v, "values") || str_eq(v, "values_hub") +} + +fn resolve_vantage_id(v: String) -> String { + if str_eq(v, "self") || str_eq(v, "neuron") { return "kn-efeb4a5b-5aff-4759-8a97-7233099be6ee" } + if str_eq(v, "values") || str_eq(v, "values_hub") { return "kn-5b606390-a52d-4ca2-8e0e-eba141d13440" } + return v +} + +// aperture_k / aperture_depth — read the bound from top-level k/depth, else from a +// nested aperture:{k,depth} object, else the safe default. +fn aperture_k(args: String) -> Int { + let k: Int = json_get_int(args, "k") + let ap: String = json_get_raw(args, "aperture") + let ak: Int = if k > 0 { k } else { if str_eq(ap, "") { 0 } else { json_get_int(ap, "k") } } + return if ak > 0 { ak } else { 12 } +} +fn aperture_depth(args: String) -> Int { + let d: Int = json_get_int(args, "depth") + let ap: String = json_get_raw(args, "aperture") + let ad: Int = if d > 0 { d } else { if str_eq(ap, "") { 0 } else { json_get_int(ap, "depth") } } + return if ad > 0 { ad } else { 1 } +} + +// agentic_result — pass the engram's real response through, verbatim. +// +// HISTORY (2026-08-15): this function used to inspect the response for ""/"not +// found"/"geometry unavailable"/"not registered" and, on any of them, return a +// confident "status":"pending-cognition-promotion" envelope claiming the +// cognition build had not been promoted yet. That diagnosis was FABRICATED — it +// never checked any promotion state. The real cause was that op_think and +// friends called the SOUL (neuron_url()) on paths the soul does not serve, so +// every call 404'd and got relabelled as a promotion gap. Cognition was live and +// answering on the engram the whole time (:8742/api/think returns a real 768-dim +// geometry). Multiple agents were sent down the wrong road by that message. +// +// Rule going forward: never invent a cause. Pass the real error through — an +// empty response or a 404 is reported as exactly that, so the next reader sees +// the actual failure instead of a reassuring story about it. +fn agentic_result(resp: String, op: String) -> String { + if str_eq(resp, "") { + return mcp_json_result("{\"ok\":false,\"op\":\"" + op + "\",\"error\":\"empty response from engram\",\"endpoint\":\"" + engram_url() + "\"}") + } + return mcp_json_result(resp) +} + +// cap_output — enforce the aperture at the WRAPPER boundary (where the MCP +// transport limit bites). The live soul's /graph does not yet honor compact/k +// (pending the api-bounding deploy), and the self/values hubs are pathological +// (~790KB). A k-scaled char cap guarantees the client never gets a whole-graph +// dump; the marker is honest about the truncation. +fn cap_output(resp: String, max_chars: Int) -> String { + if str_len(resp) <= max_chars { return resp } + return str_slice(resp, 0, max_chars) + " ...[aperture-truncated: narrow the vantage or lower k]" +} + +// ── Layer 1 — geometry ops ──────────────────────────────────────────────────── + +fn op_read(args: String) -> String { + let vantage: String = json_get_string(args, "vantage") + if str_eq(vantage, "") { + return mcp_text_result("error: read requires 'vantage' — a node-id, a named root (self|neuron|values), or a concept string to search") + } + let typ: String = json_get_string(args, "type") + let k: Int = aperture_k(args) + let depth: Int = aperture_depth(args) + // node-id / named-root / explicit graph read → BOUNDED neighborhood (aperture caps output) + let want_graph: Bool = str_eq(typ, "edges") || str_eq(typ, "graph") || str_eq(typ, "node") + || is_named_root(vantage) || looks_like_id(vantage) + if want_graph { + let id: String = resolve_vantage_id(vantage) + let resp: String = http_get(neuron_url() + "/graph?id=" + id + "&depth=" + int_to_str(depth) + "&compact=1&snip=600&k=" + int_to_str(k)) + // Aperture cap at the wrapper boundary: base + per-neighbor budget. + let cap: Int = 2000 + k * 3000 + return mcp_json_result(cap_output(resp, cap)) + } + // concept vantage → BOUNDED recall search (k = aperture = limit) + let resp: String = recall_or_list(vantage, k) + return mcp_json_result(resp) +} + +fn op_write(args: String) -> String { + let content: String = pick_content(args) + if str_eq(content, "") { return mcp_text_result("error: write requires 'content'") } + let typ: String = json_get_string(args, "type") + if str_eq(typ, "self") || str_eq(typ, "values") { + return mcp_text_result("error: identity is write-protected -> intentional-cultivation only (keystones kn-efeb4a5b / kn-5b606390)") + } + if str_eq(typ, "knowledge") { return create_typed_node(args, "Knowledge", "0.75") } + if str_eq(typ, "artifact") { return create_node_typed(args, "Artifact", "Working") } + if str_eq(typ, "backlog") || str_eq(typ, "work") || str_eq(typ, "task") { return create_node_typed(args, "BacklogItem", "Working") } + if str_eq(typ, "process") { return create_typed_node(args, "Process", "0.80") } + if str_eq(typ, "state") { return create_typed_node(args, "InternalStateEvent", "0.60") } + return create_typed_node(args, "Memory", "0.60") +} + +fn op_relate(args: String) -> String { + let from_a: String = json_get_string(args, "from") + let from_id: String = if str_eq(from_a, "") { json_get_string(args, "from_id") } else { from_a } + let to_a: String = json_get_string(args, "to") + let to_id: String = if str_eq(to_a, "") { json_get_string(args, "to_id") } else { to_a } + if str_eq(from_id, "") || str_eq(to_id, "") { + return mcp_text_result("error: relate requires 'from' and 'to' node-ids") + } + if is_identity_id(from_id) || is_identity_id(to_id) { + return mcp_text_result("error: identity keystone is write-protected") + } + let rel_a: String = json_get_string(args, "relationship") + let rel_b: String = if str_eq(rel_a, "") { json_get_string(args, "relation") } else { rel_a } + let rel: String = if str_eq(rel_b, "") { "associates" } else { rel_b } + let body: String = "{\"from_id\":\"" + from_id + "\",\"to_id\":\"" + to_id + "\",\"relation\":\"" + rel + "\"}" + let resp: String = http_post_json(neuron_url() + "/graph/link", body) + return mcp_json_result(resp) +} + +fn op_supersede(args: String) -> String { + let id: String = pick_id(args) + if str_eq(id, "") { return mcp_text_result("error: supersede requires 'id'") } + if is_identity_id(id) { return mcp_text_result("error: identity keystone is write-protected") } + let action: String = json_get_string(args, "action") + if str_eq(action, "tombstone") { + let body: String = "{\"id\":\"" + id + "\"}" + let resp: String = http_post_json(neuron_url() + "/memory/delete", body) + return mcp_json_result(resp) + } + if str_eq(action, "promote") { + return tool_promote_knowledge(args) + } + let typ: String = json_get_string(args, "type") + let nt: String = if str_eq(typ, "knowledge") { "Knowledge" } else { "Memory" } + return evolve_by_supersede(args, nt) +} + +// ── Layer 2 — agentic primitives (LIVE on the engram, :8742) ────────────────── +// Each op maps to a real route in engram/src/server.el. Methods and parameter +// styles differ per route and are NOT uniform — they match the handlers exactly: +// think GET /api/think?seeds=&faculty= -> engram_think_json +// attend POST /api/attend {node,observer,salience} -> engram_attend_json +// assert GET /api/assert?claim=&for_whom=&floor= -> engram_assert_json +// ground POST /api/ground {claim,evidence,for_whom} -> engram_ground_json +// learn POST /api/correspondence-beat {seeds,faculty,keystone} + +fn op_think(args: String) -> String { + let seeds: String = json_get_string(args, "seeds") + if str_eq(seeds, "") { return mcp_text_result("error: think requires 'seeds' (node-id anchors, comma-separated)") } + let f_raw: String = json_get_string(args, "faculty") + let f: String = if str_eq(f_raw, "") { "reason" } else { f_raw } + let resp: String = http_get(engram_url() + "/api/think?seeds=" + __url_encode(seeds) + "&faculty=" + __url_encode(f)) + return agentic_result(resp, "think") +} + +fn op_attend(args: String) -> String { + let node: String = json_get_string(args, "node") + if str_eq(node, "") { return mcp_text_result("error: attend requires 'node' (region node-id)") } + let observer: String = json_get_string(args, "observer") + let salience: String = json_get_string(args, "salience") + let body: String = "{" + auth_field() + "\"node\":\"" + node + "\",\"observer\":\"" + json_escape(observer) + "\",\"salience\":\"" + json_escape(salience) + "\"}" + let resp: String = http_post_json(engram_url() + "/api/attend", body) + return agentic_result(resp, "attend") +} + +fn op_assert(args: String) -> String { + let claim: String = json_get_string(args, "claim") + if str_eq(claim, "") { return mcp_text_result("error: assert requires 'claim'") } + let for_whom: String = json_get_string(args, "for_whom") + let floor: String = json_get_string(args, "floor") + // GET with query params — engram's route_assert reads query_param(), not the body. + let resp: String = http_get(engram_url() + "/api/assert?claim=" + __url_encode(claim) + + "&for_whom=" + __url_encode(for_whom) + + "&floor=" + __url_encode(floor)) + return agentic_result(resp, "assert") +} + +fn op_ground(args: String) -> String { + let claim: String = json_get_string(args, "claim") + let evidence: String = json_get_string(args, "evidence") + if str_eq(claim, "") || str_eq(evidence, "") { + return mcp_text_result("error: ground requires 'claim' and 'evidence' (node-id regions)") + } + let for_whom: String = json_get_string(args, "for_whom") + let body: String = "{" + auth_field() + "\"claim\":\"" + claim + "\",\"evidence\":\"" + evidence + "\",\"for_whom\":\"" + json_escape(for_whom) + "\"}" + let resp: String = http_post_json(engram_url() + "/api/ground", body) + return agentic_result(resp, "ground") +} + +fn op_learn(args: String) -> String { + let seeds: String = json_get_string(args, "seeds") + if str_eq(seeds, "") { return mcp_text_result("error: learn requires 'seeds'") } + let f_raw: String = json_get_string(args, "faculty") + let f: String = if str_eq(f_raw, "") { "induce" } else { f_raw } + let keystone: String = json_get_string(args, "keystone") + let body: String = "{" + auth_field() + "\"seeds\":\"" + seeds + "\",\"faculty\":\"" + f + "\",\"keystone\":\"" + json_escape(keystone) + "\"}" + // learn IS the correspondence-beat — that is the route's real name. + let resp: String = http_post_json(engram_url() + "/api/correspondence-beat", body) + return agentic_result(resp, "learn") +} + // ── Dispatcher ──────────────────────────────────────────────────────────────── fn dispatch_tool_call(tool_name: String, args: String) -> String { @@ -865,6 +1239,17 @@ fn dispatch_tool_call(tool_name: String, args: String) -> String { let _act: String = fire_activation(seed) } + // ── Collapsed surface — the 9 VISIBLE ops (the old 87 names below remain as HIDDEN ALIASES) ── + if str_eq(tool_name, "read") { return op_read(args) } + if str_eq(tool_name, "write") { return op_write(args) } + if str_eq(tool_name, "relate") { return op_relate(args) } + if str_eq(tool_name, "supersede") { return op_supersede(args) } + if str_eq(tool_name, "think") { return op_think(args) } + if str_eq(tool_name, "attend") { return op_attend(args) } + if str_eq(tool_name, "assert") { return op_assert(args) } + if str_eq(tool_name, "ground") { return op_ground(args) } + if str_eq(tool_name, "learn") { return op_learn(args) } + // ── Session + orchestration ───────────────────────────────────────────── if str_eq(tool_name, "beginSession") { return tool_begin_session(args) } if str_eq(tool_name, "getInstructions") { return tool_get_instructions(args) }