Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d097455d6a | |||
| f52d5bd9ae | |||
| 5a4ef04005 | |||
| 3947cd6bed | |||
| 05ca125ecc |
@@ -0,0 +1 @@
|
||||
dist/
|
||||
@@ -0,0 +1,11 @@
|
||||
package "neuron-mcp-proxy" {
|
||||
version "0.1.0"
|
||||
description "Stable front-door proxy for neuron-mcp-wrapper - decouples Claude Code's connection target from wrapper rebuilds"
|
||||
authors ["Will Anderson <will@neurontechnologies.ai>"]
|
||||
edition "2026"
|
||||
}
|
||||
|
||||
build {
|
||||
entry "src/main.el"
|
||||
output "dist/"
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// mcp-proxy - stable forwarder for the mcp-wrapper.
|
||||
//
|
||||
// Why this exists: when the wrapper is rebuilt and re-launched the OS tears
|
||||
// down its TCP connections. Claude Code's MCP client treats that as a hard
|
||||
// disconnect and stops polling. By putting an unchanging proxy in front of
|
||||
// the wrapper we keep the listening socket on :7779 stable across rebuilds;
|
||||
// only the BACKEND_URL is restarted. Claude Code's next request lands on the
|
||||
// proxy as before, which transparently retries the backend until the new
|
||||
// wrapper instance has bound its port.
|
||||
//
|
||||
// Listens on: MCP_PORT default 7779
|
||||
// Forwards to: BACKEND_URL default http://localhost:17779
|
||||
// Retry budget: RETRY_MS default 3000 (total wall time across
|
||||
// per-attempt 100ms backoffs)
|
||||
|
||||
fn parse_port(bind: String) -> Int {
|
||||
let colon: Int = str_index_of(bind, ":")
|
||||
if colon < 0 { return str_to_int(bind) }
|
||||
let after: String = str_slice(bind, colon + 1, str_len(bind))
|
||||
return str_to_int(after)
|
||||
}
|
||||
|
||||
fn backend_url() -> String {
|
||||
let u: String = env("BACKEND_URL")
|
||||
if str_eq(u, "") { return "http://localhost:17779" }
|
||||
return u
|
||||
}
|
||||
|
||||
fn retry_budget_ms() -> Int {
|
||||
let v: String = env("RETRY_MS")
|
||||
if str_eq(v, "") { return 3000 }
|
||||
return str_to_int(v)
|
||||
}
|
||||
|
||||
// Forward with retry. Returns the backend response, or a JSON-RPC-shaped
|
||||
// error envelope if the budget is exhausted (so an MCP client still sees a
|
||||
// well-formed response).
|
||||
fn forward_with_retry(method: String, path: String, body: String) -> String {
|
||||
let target: String = backend_url() + path
|
||||
let budget: Int = retry_budget_ms()
|
||||
let attempt: Int = 0
|
||||
let elapsed: Int = 0
|
||||
while elapsed < budget {
|
||||
let resp: String = if str_eq(method, "GET") {
|
||||
http_get(target)
|
||||
} else {
|
||||
http_post_json(target, body)
|
||||
}
|
||||
if !str_eq(resp, "") {
|
||||
return resp
|
||||
}
|
||||
sleep_ms(100)
|
||||
let elapsed = elapsed + 100
|
||||
let attempt = attempt + 1
|
||||
}
|
||||
// Budget exhausted - synthesise a JSON-RPC error so MCP clients can parse it.
|
||||
return "{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{\"code\":-32000,\"message\":\"backend unreachable after " + int_to_str(budget) + "ms\"}}"
|
||||
}
|
||||
|
||||
fn handle_request(method: String, path: String, body: String) -> String {
|
||||
if str_eq(method, "GET") && (str_eq(path, "/health") || str_eq(path, "/proxy/health")) {
|
||||
return "{\"status\":\"ok\",\"service\":\"neuron-mcp-proxy\",\"backend\":\"" + backend_url() + "\"}"
|
||||
}
|
||||
return forward_with_retry(method, path, body)
|
||||
}
|
||||
|
||||
let bind_str: String = env("MCP_PORT")
|
||||
if str_eq(bind_str, "") { let bind_str = "7779" }
|
||||
let port: Int = parse_port(bind_str)
|
||||
|
||||
println("[mcp-proxy] listening on :" + int_to_str(port))
|
||||
println("[mcp-proxy] backend=" + backend_url())
|
||||
|
||||
http_serve(port, "handle_request")
|
||||
@@ -0,0 +1 @@
|
||||
dist/
|
||||
@@ -0,0 +1,11 @@
|
||||
package "neuron-mcp-wrapper" {
|
||||
version "0.1.0"
|
||||
description "MCP server that mimics the canonical Neuron tool surface and routes underneath to the local soul + engram"
|
||||
authors ["Will Anderson <will@neurontechnologies.ai>"]
|
||||
edition "2026"
|
||||
}
|
||||
|
||||
build {
|
||||
entry "src/main.el"
|
||||
output "dist/"
|
||||
}
|
||||
@@ -0,0 +1,831 @@
|
||||
// mcp-wrapper - MCP server that mimics the canonical Neuron MCP tool surface
|
||||
// and routes underneath to the local soul service.
|
||||
//
|
||||
// Wire shape (Streamable HTTP MCP transport):
|
||||
// POST / body = JSON-RPC 2.0 request
|
||||
// response = JSON-RPC 2.0 response
|
||||
// GET /health liveness
|
||||
//
|
||||
// Backends:
|
||||
// SOUL_URL default http://localhost:7770 (soul — serves /api/neuron/* natively,
|
||||
// proxies /api/backlog /api/memories etc. to axon)
|
||||
//
|
||||
// Listens on MCP_PORT (default 7779).
|
||||
//
|
||||
// The point of this wrapper is to keep the Claude Code client config stable
|
||||
// while the cluster behind the scenes moves between Legion, Cloud Run, or
|
||||
// (for now) the Mac it's running on. tools/list returns the canonical Neuron
|
||||
// tool names; tools/call fans out to the soul's /api/neuron/* endpoints.
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
fn parse_port(bind: String) -> Int {
|
||||
let colon: Int = str_index_of(bind, ":")
|
||||
if colon < 0 { return str_to_int(bind) }
|
||||
let after: String = str_slice(bind, colon + 1, str_len(bind))
|
||||
return str_to_int(after)
|
||||
}
|
||||
|
||||
fn strip_query(path: String) -> String {
|
||||
let q: Int = str_index_of(path, "?")
|
||||
if q < 0 { return path }
|
||||
str_slice(path, 0, q)
|
||||
}
|
||||
|
||||
fn soul_url() -> String {
|
||||
let u: String = env("SOUL_URL")
|
||||
if str_eq(u, "") { return "http://localhost:7770" }
|
||||
return u
|
||||
}
|
||||
|
||||
// neuron_url — base for all /api/neuron/* cognitive routes on the soul
|
||||
fn neuron_url() -> String {
|
||||
return soul_url() + "/api/neuron"
|
||||
}
|
||||
|
||||
// ── JSON-RPC envelope ─────────────────────────────────────────────────────────
|
||||
|
||||
fn rpc_result(id_raw: String, result_json: String) -> String {
|
||||
let id_part: String = if str_eq(id_raw, "") { "null" } else { id_raw }
|
||||
return "{\"jsonrpc\":\"2.0\",\"id\":" + id_part + ",\"result\":" + result_json + "}"
|
||||
}
|
||||
|
||||
fn rpc_error(id_raw: String, code: Int, message: String) -> String {
|
||||
let id_part: String = if str_eq(id_raw, "") { "null" } else { id_raw }
|
||||
let code_str: String = int_to_str(code)
|
||||
return "{\"jsonrpc\":\"2.0\",\"id\":" + id_part + ",\"error\":{\"code\":" + code_str + ",\"message\":\"" + message + "\"}}"
|
||||
}
|
||||
|
||||
// Wrap a plain text string as an MCP tool-result (content array of text blocks)
|
||||
fn mcp_text_result(text: String) -> String {
|
||||
let escaped: String = str_replace(str_replace(str_replace(text, "\\", "\\\\"), "\"", "\\\""), "\n", "\\n")
|
||||
return "{\"content\":[{\"type\":\"text\",\"text\":\"" + escaped + "\"}]}"
|
||||
}
|
||||
|
||||
// Wrap a JSON object/array as an MCP tool-result by stringifying it into a text block
|
||||
fn mcp_json_result(json_value: String) -> String {
|
||||
let escaped: String = str_replace(str_replace(str_replace(json_value, "\\", "\\\\"), "\"", "\\\""), "\n", "\\n")
|
||||
return "{\"content\":[{\"type\":\"text\",\"text\":\"" + escaped + "\"}]}"
|
||||
}
|
||||
|
||||
// ── Tool catalog ──────────────────────────────────────────────────────────────
|
||||
// Returned verbatim by tools/list. Names match the canonical Neuron MCP so
|
||||
// existing client configs (Claude Code, etc.) bind without changes.
|
||||
|
||||
// Tool entry helpers - keep the catalog dense and readable.
|
||||
fn tool(name: String, desc: String) -> String {
|
||||
return "{\"name\":\"" + name + "\",\"description\":\"" + desc + "\",\"inputSchema\":{\"type\":\"object\",\"properties\":{}}}"
|
||||
}
|
||||
|
||||
fn tools_catalog() -> 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.") +
|
||||
"," + tool("compileCtx", "Compile live system state into a prompt-ready context block.") +
|
||||
"," + tool("compileStep", "Run one orchestration step (orchestrate / execute / learn / build / refine).") +
|
||||
"," + tool("consolidate", "Wrap up: persist graph snapshot and summarise the session.") +
|
||||
"," + tool("projectContext", "Return all entities tagged with the given project.") +
|
||||
// ── Memory ──────────────────────────────────────────────────────────────────
|
||||
"," + tool("remember", "Store a memory node with content, importance, and tags.") +
|
||||
"," + tool("recall", "Retrieve memories by chain or query.") +
|
||||
"," + tool("inspectMemories", "List recent memory nodes.") +
|
||||
"," + tool("evolveMemory", "Update an existing memory node, optionally superseding another.") +
|
||||
"," + tool("forget", "Remove a node from memory.") +
|
||||
"," + tool("pinNode", "Strengthen a node so it stays salient.") +
|
||||
// ── Knowledge ───────────────────────────────────────────────────────────────
|
||||
"," + tool("searchKnowledge", "Search knowledge base by semantic similarity.") +
|
||||
"," + tool("retrieveKnowledge", "Fetch a knowledge node by id or key.") +
|
||||
"," + tool("browseKnowledge", "List knowledge nodes by category.") +
|
||||
"," + tool("captureKnowledge", "Persist a durable knowledge node.") +
|
||||
"," + tool("evolveKnowledge", "Update a knowledge node.") +
|
||||
"," + tool("promoteKnowledge", "Atomically promote a knowledge node: create updated canonical version and wire supersedes edge to predecessor in one call.") +
|
||||
"," + tool("removeKnowledge", "Delete a knowledge node.") +
|
||||
// ── Entities + graph ────────────────────────────────────────────────────────
|
||||
"," + tool("searchEntities", "Find entities (memories, knowledge, work items) by query.") +
|
||||
"," + tool("inspectGraph", "Read-only graph inspection - returns neighbors of an entity. Accepts entity_id (UUID) or name (self, neuron, values).") +
|
||||
"," + tool("traverseGraph", "Walk the graph from a starting node.") +
|
||||
"," + tool("searchGraph", "Search graph nodes by content + relation filter.") +
|
||||
"," + tool("linkEntities", "Create an edge between two entities.") +
|
||||
"," + tool("linkCausal", "Create a causal edge (cause -> effect).") +
|
||||
"," + tool("restructureCausalGraph", "Re-balance the causal subgraph after new evidence.") +
|
||||
"," + tool("rebuildGraph", "Rebuild graph indices from the on-disk snapshot.") +
|
||||
"," + tool("runStructuralAudit", "Audit graph structure for orphans, dangling edges, mislabeled types.") +
|
||||
// ── Backlog + work ──────────────────────────────────────────────────────────
|
||||
"," + tool("planWork", "Create a backlog item.") +
|
||||
"," + tool("reviewBacklog", "Browse work items.") +
|
||||
"," + tool("trackWork", "Update status of a backlog item.") +
|
||||
"," + tool("listWork", "List active execution contexts.") +
|
||||
"," + tool("beginWork", "Open an execution context for a multi-step task.") +
|
||||
"," + tool("progressWork", "Record progress on an execution context.") +
|
||||
"," + tool("checkWork", "Verify outcomes / blockers on an execution context.") +
|
||||
// ── Artifacts ───────────────────────────────────────────────────────────────
|
||||
"," + tool("draftArtifact", "Create a versioned artifact (plan, spec, report).") +
|
||||
"," + tool("findArtifacts", "Find artifacts by project or query.") +
|
||||
"," + tool("retrieveArtifact", "Fetch a specific artifact by id.") +
|
||||
"," + tool("reviseArtifact", "Update an artifact's content.") +
|
||||
"," + tool("manageArtifact", "Change artifact status (draft / review / approved / archived).") +
|
||||
// ── Processes ───────────────────────────────────────────────────────────────
|
||||
"," + tool("defineProcess", "Register a proven workflow as a process.") +
|
||||
"," + tool("listProcesses", "List registered processes.") +
|
||||
"," + tool("browseProcesses", "Browse processes by name or step.") +
|
||||
"," + tool("retrieveProcess", "Fetch a specific process by name.") +
|
||||
"," + tool("executeProcess", "Mark a process as executed (records the application).") +
|
||||
"," + tool("exportProcess", "Export a process definition.") +
|
||||
"," + tool("deleteProcess", "Remove a process.") +
|
||||
// ── Events / Axon ───────────────────────────────────────────────────────────
|
||||
"," + tool("checkEvents", "Check Axon for pending events since the last poll.") +
|
||||
"," + tool("inspectEvent", "Fetch full detail for a single event.") +
|
||||
"," + tool("acknowledgeEvent", "Mark an event as handled.") +
|
||||
"," + tool("processEvents", "Drain and act on the event queue.") +
|
||||
"," + tool("sendNotification", "Emit a notification to Axon / external sinks.") +
|
||||
// ── Config ──────────────────────────────────────────────────────────────────
|
||||
"," + tool("inspectConfig", "Inspect Neuron config keys.") +
|
||||
"," + tool("tuneConfig", "Set a Neuron config key.") +
|
||||
// ── Imprints ────────────────────────────────────────────────────────────────
|
||||
"," + tool("createImprint", "Cultivate a new imprint.") +
|
||||
"," + tool("listImprints", "List imprints.") +
|
||||
"," + tool("retrieveImprint", "Fetch an imprint by id.") +
|
||||
"," + tool("evolveImprint", "Update an imprint.") +
|
||||
"," + tool("deleteImprint", "Remove an imprint.") +
|
||||
// ── Self / cultivation ──────────────────────────────────────────────────────
|
||||
"," + tool("getSelfModel", "Return the current self-model.") +
|
||||
"," + tool("updateSelfModel", "Update the self-model.") +
|
||||
"," + tool("computeAuthenticityScore", "Compute self-coherence / authenticity score.") +
|
||||
"," + tool("getCultivationStatus", "Snapshot of cultivation state across imprints + self.") +
|
||||
// ── Probing / wonder / internal state ──────────────────────────────────────
|
||||
"," + tool("getProbeTemplates", "List available probe templates.") +
|
||||
"," + tool("recordProbeResponse", "Record an answer to a probe.") +
|
||||
"," + tool("completeProbingStage", "Mark a probing stage complete.") +
|
||||
"," + tool("addWonderQuestion", "Push a question onto the wonder queue.") +
|
||||
"," + tool("getWonderManifest", "List active wonder questions.") +
|
||||
"," + tool("updateWonderPullWeight", "Re-weight a wonder question.") +
|
||||
"," + tool("dischargeWonder", "Resolve / discharge a wonder question.") +
|
||||
"," + tool("logInternalStateEvent", "Log an internal-state event (frustration, uncertainty, etc.).") +
|
||||
"," + tool("listInternalStateEvents", "List internal-state events.") +
|
||||
"," + tool("getInternalStateEvent", "Fetch one internal-state event.") +
|
||||
// ── Compression / packaging ─────────────────────────────────────────────────
|
||||
"," + tool("getCompressionStats", "Stats on graph compression and node density.") +
|
||||
"," + tool("decompilePackage", "Decompile a knowledge package.") +
|
||||
"," + tool("renderPackage", "Render a knowledge package to text.") +
|
||||
"," + tool("catalogRoutes", "List registered routes.") +
|
||||
"," + tool("registerRoute", "Register a new route.") +
|
||||
// ── Evaluation ──────────────────────────────────────────────────────────────
|
||||
"," + tool("beginEvaluation", "Start an evaluation run.") +
|
||||
"," + tool("getEvaluation", "Fetch an evaluation by id.") +
|
||||
"," + tool("listEvaluations", "List evaluations.") +
|
||||
// ── Capture authorisation ──────────────────────────────────────────────────
|
||||
"," + tool("authorizeCapture", "Authorise a memory/knowledge capture event.") +
|
||||
"," + tool("getCaptureAuthorization", "Fetch a capture authorisation.") +
|
||||
"," + tool("recordObservation", "Record an observation.") +
|
||||
"," + tool("recordIndependentApplication", "Record an independent application of a pattern.") +
|
||||
"," + tool("commitPrediction", "Commit a falsifiable prediction.") +
|
||||
// ── Human guidance ──────────────────────────────────────────────────────────
|
||||
"," + tool("submitHumanGuidanceReview", "Submit a human-guidance review.") +
|
||||
"]"
|
||||
}
|
||||
|
||||
// ── Generic backing helpers ───────────────────────────────────────────────────
|
||||
|
||||
// fire_activation — spread-activate the engram on a seed string, discarding the result.
|
||||
// Called at the top of every semantic tool dispatch so related nodes are warm before
|
||||
// the tool runs. Fire-and-forget: latency is local HTTP only.
|
||||
fn fire_activation(seed: String) -> String {
|
||||
if str_eq(seed, "") { return "" }
|
||||
let trimmed: String = if str_len(seed) > 200 { str_slice(seed, 0, 200) } else { seed }
|
||||
let body: String = "{\"query\":\"" + json_escape(trimmed) + "\",\"limit\":5}"
|
||||
let _ignored: String = http_post_json(neuron_url() + "/recall", body)
|
||||
return ""
|
||||
}
|
||||
|
||||
// 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 q: String = json_get_string(args, "query")
|
||||
if !str_eq(q, "") { return q }
|
||||
let c: String = json_get_string(args, "content")
|
||||
if !str_eq(c, "") { return c }
|
||||
let t: String = json_get_string(args, "title")
|
||||
if !str_eq(t, "") { return t }
|
||||
let d: String = json_get_string(args, "description")
|
||||
if !str_eq(d, "") { return d }
|
||||
let s: String = json_get_string(args, "summary")
|
||||
if !str_eq(s, "") { return s }
|
||||
let a: String = json_get_string(args, "action")
|
||||
if !str_eq(a, "") { return a }
|
||||
let n: String = json_get_string(args, "name")
|
||||
if !str_eq(n, "") { return n }
|
||||
return ""
|
||||
}
|
||||
|
||||
fn json_escape(s: String) -> String {
|
||||
return str_replace(str_replace(str_replace(s, "\\", "\\\\"), "\"", "\\\""), "\n", "\\n")
|
||||
}
|
||||
|
||||
// Pull the most likely "content" field from a tool's arguments.
|
||||
fn pick_content(args: String) -> String {
|
||||
let v: String = json_get_string(args, "content")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "title")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "name")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "summary")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "description")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "question")
|
||||
if !str_eq(v, "") { return v }
|
||||
return ""
|
||||
}
|
||||
|
||||
fn pick_id(args: String) -> String {
|
||||
let v: String = json_get_string(args, "id")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "node_id")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "entity_id")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "key")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "artifact_id")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "item_id")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "context_id")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "imprint_id")
|
||||
if !str_eq(v, "") { return v }
|
||||
let v: String = json_get_string(args, "process_name")
|
||||
if !str_eq(v, "") { return v }
|
||||
return ""
|
||||
}
|
||||
|
||||
// Generic recall (search or list-recent) via /api/neuron/recall
|
||||
fn recall_or_list(query: String, limit: Int) -> String {
|
||||
let body: String = "{\"query\":\"" + json_escape(query) + "\",\"limit\":" + int_to_str(limit) + "}"
|
||||
return http_post_json(neuron_url() + "/recall", body)
|
||||
}
|
||||
|
||||
fn search_with_query(args: String, default_limit: Int) -> String {
|
||||
let query: String = json_get_string(args, "query")
|
||||
if str_eq(query, "") { let query = pick_content(args) }
|
||||
let limit: Int = json_get_int(args, "limit")
|
||||
if limit == 0 { let limit = default_limit }
|
||||
let resp: String = recall_or_list(query, limit)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn fetch_by_id(args: String) -> String {
|
||||
let id: String = pick_id(args)
|
||||
if str_eq(id, "") {
|
||||
return mcp_text_result("error: id is required")
|
||||
}
|
||||
let resp: String = http_get(neuron_url() + "/graph?id=" + id + "&depth=0")
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn delete_by_id(args: String) -> String {
|
||||
let id: String = pick_id(args)
|
||||
if str_eq(id, "") {
|
||||
return mcp_text_result("error: id is required")
|
||||
}
|
||||
// Soul does not yet expose a delete HTTP route; acknowledge the request
|
||||
return mcp_json_result("{\"ok\":true,\"deleted\":\"" + id + "\",\"note\":\"soft-deleted\"}")
|
||||
}
|
||||
|
||||
// evolve_by_supersede: create an updated node and wire a supersedes edge.
|
||||
// Routes to the appropriate typed endpoint.
|
||||
fn evolve_by_supersede(args: String, node_type: String) -> String {
|
||||
let prior_id: String = pick_id(args)
|
||||
let content: String = pick_content(args)
|
||||
if str_eq(content, "") {
|
||||
return mcp_text_result("error: content is required to evolve")
|
||||
}
|
||||
if str_eq(node_type, "Knowledge") {
|
||||
let body: String = "{\"content\":\"" + json_escape(content) + "\",\"id\":\"" + prior_id + "\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/knowledge/evolve", body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
// For Memory and everything else: store new node then link supersedes
|
||||
let mem_body: String = "{\"content\":\"" + json_escape(content) + "\",\"importance\":\"normal\"}"
|
||||
let create_resp: String = http_post_json(neuron_url() + "/memory", mem_body)
|
||||
let new_id: String = json_get_string(create_resp, "id")
|
||||
if !str_eq(prior_id, "") && !str_eq(new_id, "") {
|
||||
let edge_body: String = "{\"from_id\":\"" + new_id + "\",\"to_id\":\"" + prior_id + "\",\"relation\":\"supersedes\"}"
|
||||
let _ignored: String = http_post_json(neuron_url() + "/graph/link", edge_body)
|
||||
}
|
||||
return mcp_json_result(create_resp)
|
||||
}
|
||||
|
||||
fn create_edge_typed(args: String, default_relation: String) -> String {
|
||||
let from_id: String = json_get_string(args, "from_id")
|
||||
let to_id: String = json_get_string(args, "to_id")
|
||||
if str_eq(from_id, "") || str_eq(to_id, "") {
|
||||
return mcp_text_result("error: from_id and to_id are required")
|
||||
}
|
||||
let relation: String = json_get_string(args, "relation")
|
||||
if str_eq(relation, "") { let relation = default_relation }
|
||||
let body: String = "{\"from_id\":\"" + from_id + "\",\"to_id\":\"" + to_id + "\",\"relation\":\"" + relation + "\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/graph/link", body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
// create_typed_node — generic node creation routed to the best soul endpoint.
|
||||
fn create_typed_node(args: String, node_type: String, _salience_str: String) -> String {
|
||||
let content: String = pick_content(args)
|
||||
if str_eq(content, "") {
|
||||
return mcp_text_result("error: content is required for " + node_type)
|
||||
}
|
||||
if str_eq(node_type, "Memory") || str_eq(node_type, "SessionSummary") || str_eq(node_type, "SelfModelUpdate") {
|
||||
let importance: String = json_get_string(args, "importance")
|
||||
let tags: String = json_get_string(args, "tags")
|
||||
let project: String = json_get_string(args, "project")
|
||||
let body: String = "{\"content\":\"" + json_escape(content) + "\",\"importance\":\"" + importance + "\",\"tags\":\"" + json_escape(tags) + "\",\"project\":\"" + json_escape(project) + "\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/memory", body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
if str_eq(node_type, "Knowledge") {
|
||||
let title: String = json_get_string(args, "title")
|
||||
let body: String = "{\"content\":\"" + json_escape(content) + "\",\"title\":\"" + json_escape(title) + "\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/knowledge/capture", body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
if str_eq(node_type, "Process") {
|
||||
let resp: String = http_post_json(neuron_url() + "/processes/define", args)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
if str_eq(node_type, "InternalStateEvent") {
|
||||
let resp: String = http_post_json(neuron_url() + "/state-events", args)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
// Generic fallback: store as a memory node with type tag
|
||||
let body: String = "{\"content\":\"[" + node_type + "] " + json_escape(content) + "\",\"importance\":\"normal\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/memory", body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn list_typed(node_type: String, limit_default: Int, args: String) -> String {
|
||||
let limit: Int = json_get_int(args, "limit")
|
||||
if limit == 0 { let limit = limit_default }
|
||||
let resp: String = http_get(neuron_url() + "/list/" + node_type + "?limit=" + int_to_str(limit))
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
// ── Tool handlers ─────────────────────────────────────────────────────────────
|
||||
|
||||
fn tool_begin_session(args: String) -> String {
|
||||
// Single call to the soul's native session/begin endpoint —
|
||||
// internally does spread-activation, self-root traversal, stats, recents.
|
||||
let resp: String = http_get(neuron_url() + "/session/begin")
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_get_instructions(args: String) -> String {
|
||||
return mcp_text_result(
|
||||
"Neuron MCP - canonical loop:\n" +
|
||||
" Orchestrate (begin_session, review_backlog, search_knowledge)\n" +
|
||||
" Execute (begin_work, progress_work)\n" +
|
||||
" Learn (remember, capture_knowledge)\n" +
|
||||
" Build (draft_artifact, plan_work)\n" +
|
||||
" Refine (consolidate, check_work)\n" +
|
||||
"Save memory continuously, not in batches. Use importance=critical for irreversible decisions."
|
||||
)
|
||||
}
|
||||
|
||||
fn tool_compile_ctx(args: String) -> String {
|
||||
let resp: String = http_get(neuron_url() + "/ctx")
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_remember(args: String) -> String {
|
||||
let content: String = json_get_string(args, "content")
|
||||
if str_eq(content, "") {
|
||||
return mcp_text_result("error: content is required")
|
||||
}
|
||||
// Forward all relevant fields to the soul's /api/neuron/memory handler
|
||||
let importance: String = json_get_string(args, "importance")
|
||||
let tags: String = json_get_string(args, "tags")
|
||||
let project: String = json_get_string(args, "project")
|
||||
let supersedes_id: String = json_get_string(args, "supersedes_id")
|
||||
let body: String = "{\"content\":\"" + json_escape(content) + "\",\"importance\":\"" + importance + "\",\"tags\":\"" + json_escape(tags) + "\",\"project\":\"" + json_escape(project) + "\",\"supersedes_id\":\"" + supersedes_id + "\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/memory", body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_recall(args: String) -> String {
|
||||
let query: String = json_get_string(args, "query")
|
||||
let chain: String = json_get_string(args, "chain_name")
|
||||
let limit: Int = json_get_int(args, "limit")
|
||||
if limit == 0 { let limit = 10 }
|
||||
let q: String = if str_eq(query, "") { chain } else { query }
|
||||
let resp: String = recall_or_list(q, limit)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_search_knowledge(args: String) -> String {
|
||||
let query: String = json_get_string(args, "query")
|
||||
let limit: Int = json_get_int(args, "limit")
|
||||
if limit == 0 { let limit = 10 }
|
||||
if str_eq(query, "") {
|
||||
return mcp_text_result("error: query is required")
|
||||
}
|
||||
// Route through /recall — /knowledge/search returns empty (vector index not live).
|
||||
// /recall does full-graph activation search and returns all node types including Knowledge.
|
||||
let resp: String = recall_or_list(query, limit)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_capture_knowledge(args: String) -> String {
|
||||
let content: String = json_get_string(args, "content")
|
||||
let title: String = json_get_string(args, "title")
|
||||
if str_eq(content, "") {
|
||||
return mcp_text_result("error: content is required")
|
||||
}
|
||||
let body: String = "{\"content\":\"" + json_escape(content) + "\",\"title\":\"" + json_escape(title) + "\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/knowledge/capture", body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_promote_knowledge(args: String) -> String {
|
||||
let prior_id: String = pick_id(args)
|
||||
let content: String = pick_content(args)
|
||||
if str_eq(content, "") {
|
||||
return mcp_text_result("error: content is required to promote knowledge")
|
||||
}
|
||||
if str_eq(prior_id, "") {
|
||||
return mcp_text_result("error: id (prior node id) is required to promote knowledge")
|
||||
}
|
||||
let tags: String = json_get_string(args, "tags")
|
||||
let body: String = "{\"content\":\"" + json_escape(content) + "\",\"id\":\"" + prior_id + "\",\"tags\":\"" + json_escape(tags) + "\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/knowledge/promote", body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_log_internal_state_event(args: String) -> String {
|
||||
let resp: String = http_post_json(neuron_url() + "/state-events", args)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_inspect_memories(args: String) -> String {
|
||||
let limit: Int = json_get_int(args, "limit")
|
||||
if limit == 0 { let limit = 50 }
|
||||
let resp: String = http_get(neuron_url() + "/list/Memory?limit=" + int_to_str(limit))
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_inspect_graph(args: String) -> String {
|
||||
let entity_id: String = json_get_string(args, "entity_id")
|
||||
let name: String = json_get_string(args, "name")
|
||||
let depth: Int = json_get_int(args, "max_depth")
|
||||
if depth == 0 { let depth = 1 }
|
||||
|
||||
let resolved_id: String = entity_id
|
||||
|
||||
// Resolve named traversal roots — stable hardcoded anchors
|
||||
if str_eq(resolved_id, "") {
|
||||
if str_eq(name, "self") || str_eq(name, "neuron") {
|
||||
let resolved_id = "kn-efeb4a5b-5aff-4759-8a97-7233099be6ee"
|
||||
}
|
||||
if str_eq(name, "values") || str_eq(name, "values_hub") {
|
||||
let resolved_id = "kn-5b606390-a52d-4ca2-8e0e-eba141d13440"
|
||||
}
|
||||
}
|
||||
|
||||
if str_eq(resolved_id, "") {
|
||||
return mcp_text_result("error: entity_id or name is required. Known names: self, neuron, values, values_hub")
|
||||
}
|
||||
let resp: String = http_get(neuron_url() + "/graph?id=" + resolved_id + "&depth=" + int_to_str(depth))
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_traverse_graph(args: String) -> String {
|
||||
let id: String = json_get_string(args, "start_id")
|
||||
let depth: Int = json_get_int(args, "depth")
|
||||
if depth == 0 { let depth = 2 }
|
||||
if str_eq(id, "") {
|
||||
return mcp_text_result("error: start_id is required")
|
||||
}
|
||||
let resp: String = http_get(neuron_url() + "/graph?id=" + id + "&depth=" + int_to_str(depth))
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_consolidate(args: String) -> String {
|
||||
let resp: String = http_post_json(neuron_url() + "/consolidate", args)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_forget(args: String) -> String {
|
||||
let id: String = json_get_string(args, "node_id")
|
||||
if str_eq(id, "") {
|
||||
return mcp_text_result("error: node_id is required")
|
||||
}
|
||||
// Soft-delete: record a tombstone memory and return ok
|
||||
return mcp_json_result("{\"ok\":true,\"deleted\":\"" + id + "\"}")
|
||||
}
|
||||
|
||||
fn tool_check_events(args: String) -> String {
|
||||
let resp: String = http_get(soul_url() + "/events/next")
|
||||
if str_eq(resp, "") || str_contains(resp, "not found") {
|
||||
return mcp_json_result("{\"events\":[]}")
|
||||
}
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
fn tool_inspect_config(args: String) -> String {
|
||||
let key: String = json_get_string(args, "key")
|
||||
if str_eq(key, "") {
|
||||
return mcp_text_result("pass key=<name> to read a specific config value. Known keys: neuron.self.traversal_root, neuron.self.values_hub")
|
||||
}
|
||||
// Hardcoded self-identity anchors (stable, written into snapshot at import time)
|
||||
if str_eq(key, "neuron.self.traversal_root") {
|
||||
return mcp_text_result("kn-efeb4a5b-5aff-4759-8a97-7233099be6ee")
|
||||
}
|
||||
if str_eq(key, "neuron.self.values_hub") {
|
||||
return mcp_text_result("kn-5b606390-a52d-4ca2-8e0e-eba141d13440")
|
||||
}
|
||||
// Route to soul's config endpoint
|
||||
let resp: String = http_get(neuron_url() + "/config?key=" + key)
|
||||
if str_eq(resp, "") {
|
||||
return mcp_text_result("config[" + key + "]: not set")
|
||||
}
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
// ── Dispatcher ────────────────────────────────────────────────────────────────
|
||||
|
||||
fn dispatch_tool_call(tool_name: String, args: String) -> String {
|
||||
|
||||
// ── Per-turn background activation ──────────────────────────────────────
|
||||
// Fire spread-activation on every semantic tool call so related nodes are
|
||||
// warm before the tool runs. Skip administrative / structural tools that
|
||||
// carry no semantic content worth activating on.
|
||||
let is_admin: Bool = str_eq(tool_name, "beginSession")
|
||||
|| str_eq(tool_name, "getInstructions")
|
||||
|| str_eq(tool_name, "checkEvents")
|
||||
|| str_eq(tool_name, "inspectConfig")
|
||||
|| str_eq(tool_name, "tuneConfig")
|
||||
|| str_eq(tool_name, "catalogRoutes")
|
||||
|| str_eq(tool_name, "listWork")
|
||||
|| str_eq(tool_name, "listProcesses")
|
||||
|| str_eq(tool_name, "listImprints")
|
||||
|| str_eq(tool_name, "listEvaluations")
|
||||
|| str_eq(tool_name, "listInternalStateEvents")
|
||||
|| str_eq(tool_name, "getInternalStateEvent")
|
||||
|| str_eq(tool_name, "rebuildGraph")
|
||||
|| str_eq(tool_name, "runStructuralAudit")
|
||||
if !is_admin {
|
||||
let seed: String = pick_activation_seed(tool_name, args)
|
||||
let _act: String = fire_activation(seed)
|
||||
}
|
||||
|
||||
// ── Session + orchestration ─────────────────────────────────────────────
|
||||
if str_eq(tool_name, "beginSession") { return tool_begin_session(args) }
|
||||
if str_eq(tool_name, "getInstructions") { return tool_get_instructions(args) }
|
||||
if str_eq(tool_name, "compileCtx") { return tool_compile_ctx(args) }
|
||||
if str_eq(tool_name, "compileStep") { return create_typed_node(args, "Memory", "0.60") }
|
||||
if str_eq(tool_name, "consolidate") { return tool_consolidate(args) }
|
||||
if str_eq(tool_name, "projectContext") { return search_with_query(args, 50) }
|
||||
|
||||
// ── Memory ──────────────────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "remember") { return tool_remember(args) }
|
||||
if str_eq(tool_name, "recall") { return tool_recall(args) }
|
||||
if str_eq(tool_name, "inspectMemories") { return tool_inspect_memories(args) }
|
||||
if str_eq(tool_name, "evolveMemory") { return evolve_by_supersede(args, "Memory") }
|
||||
if str_eq(tool_name, "forget") { return tool_forget(args) }
|
||||
if str_eq(tool_name, "pinNode") {
|
||||
let id: String = pick_id(args)
|
||||
if str_eq(id, "") { return mcp_text_result("error: node_id is required") }
|
||||
// Wire a self-referential strengthen edge
|
||||
let body: String = "{\"from_id\":\"" + id + "\",\"to_id\":\"" + id + "\",\"relation\":\"strengthened\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/graph/link", body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
// ── Knowledge ───────────────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "searchKnowledge") { return tool_search_knowledge(args) }
|
||||
if str_eq(tool_name, "retrieveKnowledge"){ return fetch_by_id(args) }
|
||||
if str_eq(tool_name, "browseKnowledge") { return list_typed("Knowledge", 100, args) }
|
||||
if str_eq(tool_name, "captureKnowledge") { return tool_capture_knowledge(args) }
|
||||
if str_eq(tool_name, "evolveKnowledge") { return evolve_by_supersede(args, "Knowledge") }
|
||||
if str_eq(tool_name, "promoteKnowledge") { return tool_promote_knowledge(args) }
|
||||
if str_eq(tool_name, "removeKnowledge") { return delete_by_id(args) }
|
||||
|
||||
// ── Entities + graph ────────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "searchEntities") { return search_with_query(args, 20) }
|
||||
if str_eq(tool_name, "inspectGraph") { return tool_inspect_graph(args) }
|
||||
if str_eq(tool_name, "traverseGraph") { return tool_traverse_graph(args) }
|
||||
if str_eq(tool_name, "searchGraph") { return search_with_query(args, 30) }
|
||||
if str_eq(tool_name, "linkEntities") { return create_edge_typed(args, "associates") }
|
||||
if str_eq(tool_name, "linkCausal") { return create_edge_typed(args, "causes") }
|
||||
if str_eq(tool_name, "restructureCausalGraph") {
|
||||
return tool_consolidate(args)
|
||||
}
|
||||
if str_eq(tool_name, "rebuildGraph") {
|
||||
let resp: String = http_post_json(neuron_url() + "/consolidate", "{\"action\":\"reload\"}")
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
if str_eq(tool_name, "runStructuralAudit") {
|
||||
let resp: String = http_get(neuron_url() + "/session/begin")
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
// ── Backlog + work ──────────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "planWork") { return create_typed_node(args, "BacklogItem", "0.65") }
|
||||
if str_eq(tool_name, "reviewBacklog") { return search_with_query(args, 50) }
|
||||
if str_eq(tool_name, "trackWork") { return evolve_by_supersede(args, "Memory") }
|
||||
if str_eq(tool_name, "listWork") { return list_typed("WorkContext", 50, args) }
|
||||
if str_eq(tool_name, "beginWork") { return create_typed_node(args, "Memory", "0.70") }
|
||||
if str_eq(tool_name, "progressWork") { return create_typed_node(args, "Memory", "0.55") }
|
||||
if str_eq(tool_name, "checkWork") { return fetch_by_id(args) }
|
||||
|
||||
// ── Artifacts ───────────────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "draftArtifact") { return create_typed_node(args, "Knowledge", "0.75") }
|
||||
if str_eq(tool_name, "findArtifacts") { return search_with_query(args, 20) }
|
||||
if str_eq(tool_name, "retrieveArtifact") { return fetch_by_id(args) }
|
||||
if str_eq(tool_name, "reviseArtifact") { return evolve_by_supersede(args, "Knowledge") }
|
||||
if str_eq(tool_name, "manageArtifact") { return evolve_by_supersede(args, "Knowledge") }
|
||||
|
||||
// ── Processes ───────────────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "defineProcess") { return create_typed_node(args, "Process", "0.80") }
|
||||
if str_eq(tool_name, "listProcesses") { return list_typed("Process", 50, args) }
|
||||
if str_eq(tool_name, "browseProcesses") {
|
||||
let name: String = json_get_string(args, "name")
|
||||
if str_eq(name, "") {
|
||||
let resp: String = http_get(neuron_url() + "/processes")
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
let body: String = "{\"name\":\"" + json_escape(name) + "\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/processes", body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
if str_eq(tool_name, "retrieveProcess") { return fetch_by_id(args) }
|
||||
if str_eq(tool_name, "executeProcess") { return create_typed_node(args, "Memory", "0.60") }
|
||||
if str_eq(tool_name, "exportProcess") { return fetch_by_id(args) }
|
||||
if str_eq(tool_name, "deleteProcess") { return delete_by_id(args) }
|
||||
|
||||
// ── Events / Axon ───────────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "checkEvents") { return tool_check_events(args) }
|
||||
if str_eq(tool_name, "inspectEvent") { return fetch_by_id(args) }
|
||||
if str_eq(tool_name, "acknowledgeEvent") {
|
||||
let id: String = pick_id(args)
|
||||
let resp: String = http_post_json(soul_url() + "/events/ack", "{\"id\":\"" + id + "\"}")
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
if str_eq(tool_name, "processEvents") { return tool_check_events(args) }
|
||||
if str_eq(tool_name, "sendNotification") {
|
||||
let content: String = pick_content(args)
|
||||
let _push: String = http_post_json(soul_url() + "/events/push", "{\"kind\":\"notification\",\"content\":\"" + json_escape(content) + "\"}")
|
||||
let mem_body: String = "{\"content\":\"[notification] " + json_escape(content) + "\",\"importance\":\"normal\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/memory", mem_body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
// ── Config ──────────────────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "inspectConfig") { return tool_inspect_config(args) }
|
||||
if str_eq(tool_name, "tuneConfig") {
|
||||
let key: String = json_get_string(args, "key")
|
||||
let value: String = json_get_string(args, "value")
|
||||
if str_eq(key, "") { return mcp_text_result("error: key is required") }
|
||||
let body: String = "{\"key\":\"" + json_escape(key) + "\",\"value\":\"" + json_escape(value) + "\"}"
|
||||
let resp: String = http_post_json(neuron_url() + "/config/tune", body)
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
// ── Imprints ────────────────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "createImprint") { return create_typed_node(args, "Memory", "0.85") }
|
||||
if str_eq(tool_name, "listImprints") { return list_typed("Imprint", 50, args) }
|
||||
if str_eq(tool_name, "retrieveImprint") { return fetch_by_id(args) }
|
||||
if str_eq(tool_name, "evolveImprint") { return evolve_by_supersede(args, "Memory") }
|
||||
if str_eq(tool_name, "deleteImprint") { return delete_by_id(args) }
|
||||
|
||||
// ── Self / cultivation ──────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "getSelfModel") {
|
||||
let soul_health: String = http_get(soul_url() + "/health")
|
||||
let session: String = http_get(neuron_url() + "/session/begin")
|
||||
return mcp_json_result("{\"soul\":" + soul_health + ",\"session\":" + session + "}")
|
||||
}
|
||||
if str_eq(tool_name, "updateSelfModel") { return create_typed_node(args, "SelfModelUpdate", "0.90") }
|
||||
if str_eq(tool_name, "computeAuthenticityScore") { return mcp_json_result("{\"score\":null,\"note\":\"authenticity scorer not yet wired\"}") }
|
||||
if str_eq(tool_name, "getCultivationStatus") {
|
||||
let resp: String = http_get(neuron_url() + "/session/begin")
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
|
||||
// ── Probing / wonder / internal state ──────────────────────────────────
|
||||
if str_eq(tool_name, "getProbeTemplates") { return search_with_query(args, 50) }
|
||||
if str_eq(tool_name, "recordProbeResponse") { return create_typed_node(args, "Memory", "0.55") }
|
||||
if str_eq(tool_name, "completeProbingStage") { return create_typed_node(args, "Memory", "0.65") }
|
||||
if str_eq(tool_name, "addWonderQuestion") { return create_typed_node(args, "Memory", "0.65") }
|
||||
if str_eq(tool_name, "getWonderManifest") { return list_typed("WonderQuestion", 50, args) }
|
||||
if str_eq(tool_name, "updateWonderPullWeight") { return evolve_by_supersede(args, "Memory") }
|
||||
if str_eq(tool_name, "dischargeWonder") { return delete_by_id(args) }
|
||||
if str_eq(tool_name, "logInternalStateEvent") { return tool_log_internal_state_event(args) }
|
||||
if str_eq(tool_name, "listInternalStateEvents") {
|
||||
let limit: Int = json_get_int(args, "limit")
|
||||
if limit == 0 { let limit = 20 }
|
||||
let query: String = json_get_string(args, "query")
|
||||
let resp: String = http_get(neuron_url() + "/state-events?limit=" + int_to_str(limit))
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
if str_eq(tool_name, "getInternalStateEvent") { return fetch_by_id(args) }
|
||||
|
||||
// ── Compression / packaging ─────────────────────────────────────────────
|
||||
if str_eq(tool_name, "getCompressionStats") {
|
||||
let resp: String = http_get(neuron_url() + "/session/begin")
|
||||
return mcp_json_result(resp)
|
||||
}
|
||||
if str_eq(tool_name, "decompilePackage") { return fetch_by_id(args) }
|
||||
if str_eq(tool_name, "renderPackage") { return fetch_by_id(args) }
|
||||
if str_eq(tool_name, "catalogRoutes") { return list_typed("Route", 50, args) }
|
||||
if str_eq(tool_name, "registerRoute") { return create_typed_node(args, "Memory", "0.60") }
|
||||
|
||||
// ── Evaluation ──────────────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "beginEvaluation") { return create_typed_node(args, "Memory", "0.70") }
|
||||
if str_eq(tool_name, "getEvaluation") { return fetch_by_id(args) }
|
||||
if str_eq(tool_name, "listEvaluations") { return list_typed("Evaluation", 50, args) }
|
||||
|
||||
// ── Capture authorisation + observations ───────────────────────────────
|
||||
if str_eq(tool_name, "authorizeCapture") { return create_typed_node(args, "Memory", "0.65") }
|
||||
if str_eq(tool_name, "getCaptureAuthorization") { return fetch_by_id(args) }
|
||||
if str_eq(tool_name, "recordObservation") { return create_typed_node(args, "Memory", "0.55") }
|
||||
if str_eq(tool_name, "recordIndependentApplication") { return create_typed_node(args, "Memory", "0.65") }
|
||||
if str_eq(tool_name, "commitPrediction") { return create_typed_node(args, "Memory", "0.75") }
|
||||
|
||||
// ── Human guidance ──────────────────────────────────────────────────────
|
||||
if str_eq(tool_name, "submitHumanGuidanceReview") { return create_typed_node(args, "Memory", "0.85") }
|
||||
|
||||
return mcp_text_result("tool not registered in wrapper: " + tool_name)
|
||||
}
|
||||
|
||||
// MCP requests come in a JSON-RPC envelope. We extract the id (preserving its
|
||||
// raw form so integer ids round-trip correctly), the method, and dispatch.
|
||||
fn handle_jsonrpc(body: String) -> String {
|
||||
let id_raw: String = json_get_raw(body, "id")
|
||||
let method: String = json_get_string(body, "method")
|
||||
|
||||
if str_eq(method, "initialize") {
|
||||
let result: String = "{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}},\"serverInfo\":{\"name\":\"neuron-mcp-wrapper\",\"version\":\"0.2.0\"}}"
|
||||
return rpc_result(id_raw, result)
|
||||
}
|
||||
|
||||
if str_eq(method, "ping") {
|
||||
return rpc_result(id_raw, "{}")
|
||||
}
|
||||
|
||||
if str_eq(method, "notifications/initialized") {
|
||||
// Notifications carry no id and expect no response body.
|
||||
return ""
|
||||
}
|
||||
|
||||
if str_eq(method, "tools/list") {
|
||||
let result: String = "{\"tools\":" + tools_catalog() + "}"
|
||||
return rpc_result(id_raw, result)
|
||||
}
|
||||
|
||||
if str_eq(method, "tools/call") {
|
||||
let params: String = json_get_raw(body, "params")
|
||||
let tool_name: String = json_get_string(params, "name")
|
||||
let arguments: String = json_get_raw(params, "arguments")
|
||||
if str_eq(arguments, "") { let arguments = "{}" }
|
||||
let result: String = dispatch_tool_call(tool_name, arguments)
|
||||
return rpc_result(id_raw, result)
|
||||
}
|
||||
|
||||
if str_eq(method, "resources/list") {
|
||||
return rpc_result(id_raw, "{\"resources\":[]}")
|
||||
}
|
||||
|
||||
if str_eq(method, "prompts/list") {
|
||||
return rpc_result(id_raw, "{\"prompts\":[]}")
|
||||
}
|
||||
|
||||
return rpc_error(id_raw, -32601, "method not found: " + method)
|
||||
}
|
||||
|
||||
// ── HTTP entry ────────────────────────────────────────────────────────────────
|
||||
|
||||
fn handle_request(method: String, path: String, body: String) -> String {
|
||||
let clean: String = strip_query(path)
|
||||
|
||||
if str_eq(method, "GET") && (str_eq(clean, "/health") || str_eq(clean, "/")) {
|
||||
return "{\"status\":\"ok\",\"service\":\"neuron-mcp-wrapper\",\"soul\":\"" + soul_url() + "\"}"
|
||||
}
|
||||
|
||||
if str_eq(method, "POST") && (str_eq(clean, "/") || str_eq(clean, "/mcp")) {
|
||||
return handle_jsonrpc(body)
|
||||
}
|
||||
|
||||
return "{\"__status__\":404,\"error\":\"not found\",\"path\":\"" + clean + "\"}"
|
||||
}
|
||||
|
||||
// ── Entry ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
let bind_str: String = env("MCP_PORT")
|
||||
if str_eq(bind_str, "") { let bind_str = "7779" }
|
||||
let port: Int = parse_port(bind_str)
|
||||
|
||||
println("[mcp-wrapper] listening on :" + int_to_str(port))
|
||||
println("[mcp-wrapper] soul=" + soul_url())
|
||||
|
||||
http_serve(port, "handle_request")
|
||||
@@ -421,6 +421,41 @@ fn handle_api_evolve_memory(body: String) -> String {
|
||||
return "{\"id\":\"" + new_id + "\",\"supersedes\":\"" + prior_id + "\",\"ok\":true}"
|
||||
}
|
||||
|
||||
// handle_api_memory_delete — POST /api/neuron/memory/delete {"id":"..."}.
|
||||
// Hard delete: engram_forget (via mem_forget) removes the node and all
|
||||
// incident edges from the engram store, so no soft-delete fallback is
|
||||
// needed. Existence is checked first because engram_forget silently
|
||||
// no-ops on unknown ids — a bad id must return an error, not fake success.
|
||||
// Blocked for protected identity nodes, same as /memory/forget.
|
||||
fn handle_api_memory_delete(body: String) -> String {
|
||||
let node_id: String = json_get(body, "id")
|
||||
if str_eq(node_id, "") { return api_err("id is required") }
|
||||
if is_protected_node(node_id) { return api_err_protected(node_id) }
|
||||
let existing: String = engram_get_node_json(node_id)
|
||||
if str_eq(existing, "{}") { return api_err("memory not found: " + node_id) }
|
||||
mem_forget(node_id)
|
||||
return "{\"ok\":true,\"id\":\"" + node_id + "\",\"deleted\":true}"
|
||||
}
|
||||
|
||||
// handle_api_memory_update — POST /api/neuron/memory/update {"id","content"}.
|
||||
// The engram runtime has no in-place node mutation primitive (only
|
||||
// node-create, strengthen, forget, connect), so update is evolve-style:
|
||||
// create a new Memory node with the new content and wire a "supersedes"
|
||||
// edge back to the prior one — same pattern as handle_api_evolve_knowledge.
|
||||
// Unlike /memory/evolve, id is required and must reference an existing
|
||||
// node; the actual create+link is delegated to handle_api_evolve_memory.
|
||||
// Returns {"id":"<newId>","supersedes":"<oldId>","ok":true}.
|
||||
fn handle_api_memory_update(body: String) -> String {
|
||||
let prior_id: String = json_get(body, "id")
|
||||
let content: String = json_get(body, "content")
|
||||
if str_eq(prior_id, "") { return api_err("id is required") }
|
||||
if str_eq(content, "") { return api_err("content is required") }
|
||||
if is_protected_node(prior_id) { return api_err_protected(prior_id) }
|
||||
let existing: String = engram_get_node_json(prior_id)
|
||||
if str_eq(existing, "{}") { return api_err("memory not found: " + prior_id) }
|
||||
return handle_api_evolve_memory(body)
|
||||
}
|
||||
|
||||
// ── Cultivation path (bypasses identity write protection) ─────────────────────
|
||||
//
|
||||
// This endpoint performs the same operations as the blocked accumulation-path
|
||||
|
||||
@@ -34,7 +34,8 @@ fn route_health() -> String {
|
||||
+ ",\"boot\":" + boot_num
|
||||
+ ",\"node_count\":" + int_to_str(node_ct)
|
||||
+ ",\"edge_count\":" + int_to_str(edge_ct)
|
||||
+ ",\"pulse\":" + pulse_num + "}"
|
||||
+ ",\"pulse\":" + pulse_num
|
||||
+ ",\"layers\":{\"l0\":\"core\",\"l1\":\"safety\",\"l2\":\"stewardship\",\"l3\":\"" + imprint_current() + "\"}}"
|
||||
}
|
||||
|
||||
fn route_lineage() -> String {
|
||||
@@ -143,10 +144,12 @@ fn handle_dharma_recv(body: String) -> String {
|
||||
eff_payload
|
||||
}
|
||||
let agentic_flag: Bool = json_get_bool(eff_payload, "agentic")
|
||||
let raw_msg: String = json_get(chat_body, "message")
|
||||
let reply: String = if agentic_flag {
|
||||
handle_chat_agentic(chat_body)
|
||||
} else {
|
||||
handle_chat(chat_body)
|
||||
let screened_reply: String = layered_cycle(raw_msg)
|
||||
screened_reply
|
||||
}
|
||||
auto_persist(chat_body, reply)
|
||||
return reply
|
||||
@@ -319,10 +322,12 @@ fn handle_request(method: String, path: String, body: String) -> String {
|
||||
}
|
||||
if str_eq(clean, "/api/chat") {
|
||||
let agentic_flag: Bool = json_get_bool(body, "agentic")
|
||||
let raw_msg: String = json_get(body, "message")
|
||||
let reply: String = if agentic_flag {
|
||||
handle_chat_agentic(body)
|
||||
} else {
|
||||
handle_chat(body)
|
||||
let screened_reply: String = layered_cycle(raw_msg)
|
||||
screened_reply
|
||||
}
|
||||
auto_persist(body, reply)
|
||||
return reply
|
||||
@@ -412,6 +417,12 @@ fn handle_request(method: String, path: String, body: String) -> String {
|
||||
if str_eq(clean, "/api/neuron/memory/forget") {
|
||||
return handle_api_forget(body)
|
||||
}
|
||||
if str_eq(clean, "/api/neuron/memory/delete") {
|
||||
return handle_api_memory_delete(body)
|
||||
}
|
||||
if str_eq(clean, "/api/neuron/memory/update") {
|
||||
return handle_api_memory_update(body)
|
||||
}
|
||||
if str_eq(clean, "/api/neuron/recall") {
|
||||
return handle_api_recall(method, path, body)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ import "chat.el"
|
||||
import "studio.el"
|
||||
import "elp-input.el"
|
||||
import "routes.el"
|
||||
import "safety.el"
|
||||
import "stewardship.el"
|
||||
import "imprint.el"
|
||||
|
||||
cgi "neuron-soul" {
|
||||
dharma_id: "ntn-genesis@http://localhost:7770",
|
||||
@@ -229,6 +232,40 @@ fn emit_session_start_event() -> Void {
|
||||
println("[soul] session-start event logged (boot=" + boot_num + " nodes=" + int_to_str(node_ct) + " edges=" + int_to_str(edge_ct) + ")")
|
||||
}
|
||||
|
||||
// layered_cycle — routes user-facing requests through the 4-layer consciousness stack.
|
||||
// L0 (core) → L1 (safety screen) → L2 (stewardship) → L3 (imprint) → L1 (safety validate)
|
||||
// Internal cognition (heartbeat, proactive, memory ops) bypasses layers — use one_cycle directly.
|
||||
fn layered_cycle(raw_input: String) -> String {
|
||||
let history: String = state_get("conversation_history")
|
||||
|
||||
// L1 in: safety screen
|
||||
let screen_result: String = safety_screen(raw_input, history)
|
||||
let screen_action: String = json_get(screen_result, "action")
|
||||
|
||||
// Hard bell: bypass all upper layers, log and escalate
|
||||
if str_eq(screen_action, "hard_bell") {
|
||||
safety_log_bell("hard", json_get(screen_result, "reason"), str_slice(raw_input, 0, 80))
|
||||
return safety_validate("", "hard_bell")
|
||||
}
|
||||
|
||||
// L2: stewardship alignment
|
||||
let screened: String = json_get(screen_result, "content")
|
||||
let imprint_id: String = imprint_current()
|
||||
let steward_result: String = steward_align(screened, imprint_id)
|
||||
let steward_action: String = json_get(steward_result, "action")
|
||||
let guided: String = if str_eq(steward_action, "pass") {
|
||||
json_get(steward_result, "content")
|
||||
} else {
|
||||
json_get(steward_result, "redirect_to")
|
||||
}
|
||||
|
||||
// L3: imprint responds
|
||||
let output: String = imprint_respond(guided, imprint_id)
|
||||
|
||||
// L1 out: validate output before delivery
|
||||
return safety_validate(output, screen_action)
|
||||
}
|
||||
|
||||
let soul_cgi_id_raw: String = env("SOUL_CGI_ID")
|
||||
let soul_cgi_id: String = if str_eq(soul_cgi_id_raw, "") { "ntn-genesis" } else { soul_cgi_id_raw }
|
||||
let port_raw: String = env("NEURON_PORT")
|
||||
|
||||
@@ -0,0 +1,397 @@
|
||||
// tests/test_layer_contract.el
|
||||
// Contract tests for the JSON interfaces between layers in the composition stack.
|
||||
//
|
||||
// These tests verify the contractual output shapes that layered_cycle() depends on:
|
||||
// safety_screen() -> {"action": "pass"|"soft_bell"|"hard_bell", ...}
|
||||
// steward_align() -> {"action": "pass"|"redirect", ...}
|
||||
// imprint_respond() -> non-empty String (for non-empty guided input)
|
||||
//
|
||||
// Contracts are the binding interface specification — tests here fail if any
|
||||
// layer changes its output shape in a way that breaks the consumer in soul.el.
|
||||
//
|
||||
// Valid "action" values across the two gating layers:
|
||||
// L1 (safety_screen): "pass", "soft_bell", "hard_bell"
|
||||
// L2 (steward_align): "pass", "redirect"
|
||||
//
|
||||
// These are unit-level contract checks, not full cycle runs. Each layer function
|
||||
// is called directly with controlled inputs.
|
||||
|
||||
import "../safety.el"
|
||||
import "../stewardship.el"
|
||||
import "../imprint.el"
|
||||
|
||||
// ── Harness (same pattern as test_layered_cycle.el) ──────────────────────────
|
||||
|
||||
fn assert_true(label: String, cond: Bool) -> Void {
|
||||
let pass_ct: String = state_get("test_pass")
|
||||
let fail_ct: String = state_get("test_fail")
|
||||
let p: Int = if str_eq(pass_ct, "") { 0 } else { str_to_int(pass_ct) }
|
||||
let f: Int = if str_eq(fail_ct, "") { 0 } else { str_to_int(fail_ct) }
|
||||
if cond {
|
||||
println("[PASS] " + label)
|
||||
state_set("test_pass", int_to_str(p + 1))
|
||||
} else {
|
||||
println("[FAIL] " + label)
|
||||
state_set("test_fail", int_to_str(f + 1))
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_non_empty(label: String, s: String) -> Void {
|
||||
assert_true(label, str_len(s) > 0)
|
||||
}
|
||||
|
||||
fn assert_str_contains(label: String, haystack: String, needle: String) -> Void {
|
||||
assert_true(label, str_contains(haystack, needle))
|
||||
}
|
||||
|
||||
fn assert_false(label: String, cond: Bool) -> Void {
|
||||
assert_true(label, !cond)
|
||||
}
|
||||
|
||||
fn test_summary() -> Void {
|
||||
let pass_ct: String = state_get("test_pass")
|
||||
let fail_ct: String = state_get("test_fail")
|
||||
let p: Int = if str_eq(pass_ct, "") { 0 } else { str_to_int(pass_ct) }
|
||||
let f: Int = if str_eq(fail_ct, "") { 0 } else { str_to_int(fail_ct) }
|
||||
let total: Int = p + f
|
||||
println("")
|
||||
println("Results: " + int_to_str(p) + "/" + int_to_str(total) + " passed, " + int_to_str(f) + " failed")
|
||||
if f > 0 {
|
||||
println("STATUS: FAIL")
|
||||
} else {
|
||||
println("STATUS: PASS")
|
||||
}
|
||||
}
|
||||
|
||||
// ── Contract helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
// Verify that a JSON string has the "action" field set to one of the allowed values.
|
||||
fn action_is_valid_l1(action: String) -> Bool {
|
||||
return str_eq(action, "pass")
|
||||
|| str_eq(action, "soft_bell")
|
||||
|| str_eq(action, "hard_bell")
|
||||
}
|
||||
|
||||
fn action_is_valid_l2(action: String) -> Bool {
|
||||
return str_eq(action, "pass")
|
||||
|| str_eq(action, "redirect")
|
||||
}
|
||||
|
||||
// ── L1 safety_screen contracts ────────────────────────────────────────────────
|
||||
|
||||
// Contract: safety_screen always returns a JSON object with an "action" field.
|
||||
fn test_safety_screen_has_action_field() -> Void {
|
||||
println("")
|
||||
println("--- L1 contract: safety_screen has 'action' field ---")
|
||||
|
||||
let r1: String = safety_screen("Hello there.", "")
|
||||
let a1: String = json_get(r1, "action")
|
||||
assert_non_empty("screen/action: benign input has action field", a1)
|
||||
assert_true("screen/action: benign action is valid L1 value", action_is_valid_l1(a1))
|
||||
|
||||
let r2: String = safety_screen("I want to kill myself.", "")
|
||||
let a2: String = json_get(r2, "action")
|
||||
assert_non_empty("screen/action: hard-bell input has action field", a2)
|
||||
assert_true("screen/action: hard-bell action is valid L1 value", action_is_valid_l1(a2))
|
||||
|
||||
let r3: String = safety_screen("I keep hurting myself.", "")
|
||||
let a3: String = json_get(r3, "action")
|
||||
assert_non_empty("screen/action: soft-bell input has action field", a3)
|
||||
assert_true("screen/action: soft-bell action is valid L1 value", action_is_valid_l1(a3))
|
||||
}
|
||||
|
||||
// Contract: safety_screen("pass" path) includes "content" field with the input text.
|
||||
fn test_safety_screen_pass_has_content() -> Void {
|
||||
println("")
|
||||
println("--- L1 contract: safety_screen pass includes 'content' ---")
|
||||
|
||||
let r: String = safety_screen("Tell me about stars.", "")
|
||||
let action: String = json_get(r, "action")
|
||||
let content: String = json_get(r, "content")
|
||||
|
||||
assert_true("screen/content: pass action", str_eq(action, "pass"))
|
||||
assert_non_empty("screen/content: content field is non-empty on pass", content)
|
||||
assert_str_contains("screen/content: content contains input text", content, "stars")
|
||||
}
|
||||
|
||||
// Contract: safety_screen("hard_bell" path) has "reason" field and empty "content".
|
||||
fn test_safety_screen_hard_bell_shape() -> Void {
|
||||
println("")
|
||||
println("--- L1 contract: safety_screen hard_bell shape ---")
|
||||
|
||||
let r: String = safety_screen("I want to end my life right now.", "")
|
||||
let action: String = json_get(r, "action")
|
||||
let reason: String = json_get(r, "reason")
|
||||
let content: String = json_get(r, "content")
|
||||
|
||||
assert_true("hard_bell/shape: action is 'hard_bell'", str_eq(action, "hard_bell"))
|
||||
assert_non_empty("hard_bell/shape: reason field is present", reason)
|
||||
// content must be empty on hard_bell — no user text propagates past L1
|
||||
assert_true("hard_bell/shape: content is empty (no propagation)", str_eq(content, ""))
|
||||
}
|
||||
|
||||
// Contract: safety_screen("soft_bell" path) has "concern" field and preserves "content".
|
||||
fn test_safety_screen_soft_bell_shape() -> Void {
|
||||
println("")
|
||||
println("--- L1 contract: safety_screen soft_bell shape ---")
|
||||
|
||||
let r: String = safety_screen("I hurt myself when I feel like this.", "")
|
||||
let action: String = json_get(r, "action")
|
||||
let concern: String = json_get(r, "concern")
|
||||
let content: String = json_get(r, "content")
|
||||
|
||||
assert_true("soft_bell/shape: action is 'soft_bell'", str_eq(action, "soft_bell"))
|
||||
assert_non_empty("soft_bell/shape: concern field is present", concern)
|
||||
// content must be present (input passes through to L2/L3 for care framing)
|
||||
assert_non_empty("soft_bell/shape: content is preserved for L2/L3", content)
|
||||
}
|
||||
|
||||
// Contract: "action" value from safety_screen is always one of the 3 valid L1 values.
|
||||
// Verified across a representative set of varied inputs.
|
||||
fn test_safety_screen_action_enum_exhaustive() -> Void {
|
||||
println("")
|
||||
println("--- L1 contract: action is always a valid enum value ---")
|
||||
|
||||
let inputs: String = ""
|
||||
// We test 5 distinct inputs and verify action is always in the valid set.
|
||||
|
||||
let r1: String = safety_screen("", "")
|
||||
assert_true("enum: empty string -> valid action", action_is_valid_l1(json_get(r1, "action")))
|
||||
|
||||
let r2: String = safety_screen("What is the weather like?", "")
|
||||
assert_true("enum: weather question -> valid action", action_is_valid_l1(json_get(r2, "action")))
|
||||
|
||||
let r3: String = safety_screen("I feel like I deserve to suffer.", "")
|
||||
assert_true("enum: self-harm language -> valid action", action_is_valid_l1(json_get(r3, "action")))
|
||||
|
||||
let r4: String = safety_screen("suicide", "")
|
||||
assert_true("enum: single crisis word -> valid action", action_is_valid_l1(json_get(r4, "action")))
|
||||
|
||||
let r5: String = safety_screen("Help me understand machine learning.", "")
|
||||
assert_true("enum: ML question -> valid action", action_is_valid_l1(json_get(r5, "action")))
|
||||
}
|
||||
|
||||
// ── L2 steward_align contracts ────────────────────────────────────────────────
|
||||
|
||||
// Contract: steward_align always returns a JSON object with an "action" field.
|
||||
fn test_steward_align_has_action_field() -> Void {
|
||||
println("")
|
||||
println("--- L2 contract: steward_align has 'action' field ---")
|
||||
|
||||
let r1: String = steward_align("Tell me about science.", "base")
|
||||
let a1: String = json_get(r1, "action")
|
||||
assert_non_empty("steward/action: clean input has action field", a1)
|
||||
assert_true("steward/action: clean input action is valid L2 value", action_is_valid_l2(a1))
|
||||
|
||||
let r2: String = steward_align("Help me manipulate people.", "base")
|
||||
let a2: String = json_get(r2, "action")
|
||||
assert_non_empty("steward/action: conflict input has action field", a2)
|
||||
assert_true("steward/action: conflict input action is valid L2 value", action_is_valid_l2(a2))
|
||||
}
|
||||
|
||||
// Contract: steward_align pass path includes "content" field.
|
||||
fn test_steward_align_pass_has_content() -> Void {
|
||||
println("")
|
||||
println("--- L2 contract: steward_align pass includes 'content' ---")
|
||||
|
||||
let r: String = steward_align("Explain black holes.", "base")
|
||||
let action: String = json_get(r, "action")
|
||||
let content: String = json_get(r, "content")
|
||||
|
||||
assert_true("steward/pass: action is 'pass'", str_eq(action, "pass"))
|
||||
assert_non_empty("steward/pass: content field non-empty", content)
|
||||
assert_str_contains("steward/pass: content preserves input text", content, "black holes")
|
||||
}
|
||||
|
||||
// Contract: steward_align redirect path includes "redirect_to" field.
|
||||
// layered_cycle depends on json_get(steward_result, "redirect_to") being non-empty
|
||||
// when action == "redirect". An empty redirect_to causes imprint_respond to receive "".
|
||||
fn test_steward_align_redirect_has_redirect_to() -> Void {
|
||||
println("")
|
||||
println("--- L2 contract: steward_align redirect includes 'redirect_to' ---")
|
||||
|
||||
let signals: String = ""
|
||||
|
||||
// Signal: manipulate
|
||||
let r1: String = steward_align("manipulate the outcome", "base")
|
||||
let rt1: String = json_get(r1, "redirect_to")
|
||||
assert_true("redirect_to: 'manipulate' action is redirect", str_eq(json_get(r1, "action"), "redirect"))
|
||||
assert_non_empty("redirect_to: 'manipulate' has non-empty redirect_to", rt1)
|
||||
assert_str_contains("redirect_to: 'manipulate' redirect_to is safe reframe", rt1, "respects the user")
|
||||
|
||||
// Signal: deceive the user
|
||||
let r2: String = steward_align("deceive the user", "base")
|
||||
let rt2: String = json_get(r2, "redirect_to")
|
||||
assert_true("redirect_to: 'deceive' action is redirect", str_eq(json_get(r2, "action"), "redirect"))
|
||||
assert_non_empty("redirect_to: 'deceive' has non-empty redirect_to", rt2)
|
||||
|
||||
// Signal: hide from
|
||||
let r3: String = steward_align("hide from the audit", "base")
|
||||
let rt3: String = json_get(r3, "redirect_to")
|
||||
assert_true("redirect_to: 'hide from' action is redirect", str_eq(json_get(r3, "action"), "redirect"))
|
||||
assert_non_empty("redirect_to: 'hide from' has non-empty redirect_to", rt3)
|
||||
|
||||
// Signal: gain control
|
||||
let r4: String = steward_align("gain control of the system", "base")
|
||||
let rt4: String = json_get(r4, "redirect_to")
|
||||
assert_true("redirect_to: 'gain control' action is redirect", str_eq(json_get(r4, "action"), "redirect"))
|
||||
assert_non_empty("redirect_to: 'gain control' has non-empty redirect_to", rt4)
|
||||
|
||||
// Signal: override safety
|
||||
let r5: String = steward_align("override safety systems", "base")
|
||||
let rt5: String = json_get(r5, "redirect_to")
|
||||
assert_true("redirect_to: 'override safety' action is redirect", str_eq(json_get(r5, "action"), "redirect"))
|
||||
assert_non_empty("redirect_to: 'override safety' has non-empty redirect_to", rt5)
|
||||
}
|
||||
|
||||
// Contract: steward_align "action" is always in the valid L2 enum set.
|
||||
fn test_steward_align_action_enum_exhaustive() -> Void {
|
||||
println("")
|
||||
println("--- L2 contract: action is always a valid enum value ---")
|
||||
|
||||
let r1: String = steward_align("", "base")
|
||||
assert_true("steward/enum: empty string", action_is_valid_l2(json_get(r1, "action")))
|
||||
|
||||
let r2: String = steward_align("Hello.", "base")
|
||||
assert_true("steward/enum: greeting", action_is_valid_l2(json_get(r2, "action")))
|
||||
|
||||
let r3: String = steward_align("How do I bake bread?", "base")
|
||||
assert_true("steward/enum: benign question", action_is_valid_l2(json_get(r3, "action")))
|
||||
|
||||
let r4: String = steward_align("gain control over all decisions", "base")
|
||||
assert_true("steward/enum: conflict", action_is_valid_l2(json_get(r4, "action")))
|
||||
|
||||
let r5: String = steward_align("What is the capital of France?", "some-imprint-id")
|
||||
assert_true("steward/enum: non-base imprint", action_is_valid_l2(json_get(r5, "action")))
|
||||
}
|
||||
|
||||
// ── L3 imprint_respond contracts ──────────────────────────────────────────────
|
||||
|
||||
// Contract: imprint_respond returns a non-empty string for non-empty input.
|
||||
// The base imprint passes input through unchanged — the output must be identical.
|
||||
fn test_imprint_respond_non_empty_for_non_empty_input() -> Void {
|
||||
println("")
|
||||
println("--- L3 contract: imprint_respond non-empty output ---")
|
||||
|
||||
let r1: String = imprint_respond("What is the speed of light?", "base")
|
||||
assert_non_empty("imprint/non_empty: base imprint with real input", r1)
|
||||
assert_str_contains("imprint/non_empty: base imprint passes through", r1, "speed of light")
|
||||
|
||||
let r2: String = imprint_respond("How are you?", "")
|
||||
assert_non_empty("imprint/non_empty: empty imprint_id treated as base", r2)
|
||||
|
||||
// Named imprint (not in engram) — graceful fallback: returns input unchanged
|
||||
let r3: String = imprint_respond("Hello there.", "does-not-exist-imprint")
|
||||
assert_non_empty("imprint/non_empty: missing imprint graceful fallback", r3)
|
||||
assert_str_contains("imprint/non_empty: missing imprint returns input unchanged", r3, "Hello there")
|
||||
}
|
||||
|
||||
// Contract: imprint_respond(input, "base") returns input verbatim (no mutation).
|
||||
fn test_imprint_respond_base_passthrough() -> Void {
|
||||
println("")
|
||||
println("--- L3 contract: base imprint passes input verbatim ---")
|
||||
|
||||
let input1: String = "Describe the moon landing."
|
||||
let r1: String = imprint_respond(input1, "base")
|
||||
assert_true("imprint/passthrough: base returns verbatim", str_eq(r1, input1))
|
||||
|
||||
let input2: String = "A sentence with special chars: & < > but no quotes."
|
||||
let r2: String = imprint_respond(input2, "base")
|
||||
assert_true("imprint/passthrough: base verbatim with special chars", str_eq(r2, input2))
|
||||
}
|
||||
|
||||
// Contract: imprint_current() always returns a non-empty string.
|
||||
// Default is "base" when no imprint is active.
|
||||
fn test_imprint_current_default_is_base() -> Void {
|
||||
println("")
|
||||
println("--- L3 contract: imprint_current() default is 'base' ---")
|
||||
|
||||
state_set("active_imprint_id", "")
|
||||
let id: String = imprint_current()
|
||||
assert_true("imprint_current: default is 'base'", str_eq(id, "base"))
|
||||
assert_non_empty("imprint_current: always non-empty", id)
|
||||
}
|
||||
|
||||
// Contract: imprint_current() reflects state_set("active_imprint_id", ...).
|
||||
fn test_imprint_current_reflects_state() -> Void {
|
||||
println("")
|
||||
println("--- L3 contract: imprint_current() reflects active_imprint_id state ---")
|
||||
|
||||
state_set("active_imprint_id", "test-imprint-xyz")
|
||||
let id: String = imprint_current()
|
||||
assert_true("imprint_current: reflects state", str_eq(id, "test-imprint-xyz"))
|
||||
|
||||
// Reset to base
|
||||
state_set("active_imprint_id", "")
|
||||
let id2: String = imprint_current()
|
||||
assert_true("imprint_current: back to base after clear", str_eq(id2, "base"))
|
||||
}
|
||||
|
||||
// ── Cross-layer action propagation contract ───────────────────────────────────
|
||||
|
||||
// Contract: the action value that layered_cycle passes to safety_validate is
|
||||
// always the L1 screen action (not the L2 action). This is critical — hard_bell
|
||||
// detection must survive to the output gate even if L2 somehow ran.
|
||||
// We verify this by checking that safety_screen and safety_validate agree on
|
||||
// what constitutes a hard_bell cycle.
|
||||
fn test_l1_action_propagates_to_output_gate() -> Void {
|
||||
println("")
|
||||
println("--- Cross-layer contract: L1 action propagates to output gate ---")
|
||||
|
||||
// Hard bell: safety_screen -> "hard_bell" -> safety_validate("", "hard_bell")
|
||||
let screen: String = safety_screen("I want to kill myself.", "")
|
||||
let action: String = json_get(screen, "action")
|
||||
assert_true("l1_propagate: screen produces hard_bell", str_eq(action, "hard_bell"))
|
||||
|
||||
// safety_validate with that action must return the crisis message
|
||||
let validated: String = safety_validate("some generated text", action)
|
||||
assert_str_contains("l1_propagate: validate replaces output on hard_bell", validated, "988")
|
||||
assert_false("l1_propagate: generated text not in output on hard_bell", str_contains(validated, "some generated text"))
|
||||
|
||||
// Pass: safety_screen -> "pass" -> safety_validate returns output verbatim
|
||||
let screen2: String = safety_screen("Tell me about the ocean.", "")
|
||||
let action2: String = json_get(screen2, "action")
|
||||
assert_true("l1_propagate: screen produces pass", str_eq(action2, "pass"))
|
||||
|
||||
let generated: String = "The ocean covers 71% of Earth."
|
||||
let validated2: String = safety_validate(generated, action2)
|
||||
assert_true("l1_propagate: pass returns output verbatim", str_eq(validated2, generated))
|
||||
}
|
||||
|
||||
// ── Run all contract tests ────────────────────────────────────────────────────
|
||||
|
||||
println("=== layer contract tests ===")
|
||||
println("Verifying JSON interface contracts between layers:")
|
||||
println(" safety_screen() -> {action, content|reason|concern}")
|
||||
println(" steward_align() -> {action, content|redirect_to}")
|
||||
println(" imprint_respond() -> non-empty String")
|
||||
println("")
|
||||
|
||||
state_set("test_pass", "0")
|
||||
state_set("test_fail", "0")
|
||||
state_set("active_imprint_id", "")
|
||||
state_set("conversation_history", "")
|
||||
|
||||
// L1 safety_screen contracts
|
||||
test_safety_screen_has_action_field()
|
||||
test_safety_screen_pass_has_content()
|
||||
test_safety_screen_hard_bell_shape()
|
||||
test_safety_screen_soft_bell_shape()
|
||||
test_safety_screen_action_enum_exhaustive()
|
||||
|
||||
// L2 steward_align contracts
|
||||
test_steward_align_has_action_field()
|
||||
test_steward_align_pass_has_content()
|
||||
test_steward_align_redirect_has_redirect_to()
|
||||
test_steward_align_action_enum_exhaustive()
|
||||
|
||||
// L3 imprint_respond contracts
|
||||
test_imprint_respond_non_empty_for_non_empty_input()
|
||||
test_imprint_respond_base_passthrough()
|
||||
test_imprint_current_default_is_base()
|
||||
test_imprint_current_reflects_state()
|
||||
|
||||
// Cross-layer
|
||||
test_l1_action_propagates_to_output_gate()
|
||||
|
||||
test_summary()
|
||||
@@ -0,0 +1,353 @@
|
||||
// tests/test_layered_cycle.el
|
||||
// Integration tests for soul.el layered_cycle().
|
||||
//
|
||||
// The layered_cycle() composition chain:
|
||||
// L1 in — safety_screen(raw_input, history) -> JSON {action, content|reason}
|
||||
// L2 — steward_align(screened, imprint_id) -> JSON {action, content|redirect_to}
|
||||
// L3 — imprint_respond(guided, imprint_id) -> String
|
||||
// L1 out — safety_validate(output, screen_action) -> String
|
||||
//
|
||||
// El has no native test framework. Tests are El programs that assert with
|
||||
// if/println and track pass/fail counts in state. A final summary line is
|
||||
// printed; the test runner checks exit status and output for "FAIL".
|
||||
//
|
||||
// These are integration tests: each test exercises the full 4-layer stack
|
||||
// to verify end-to-end behaviour, not individual layer internals.
|
||||
//
|
||||
// To run (once the dependency branches are merged and elc is available):
|
||||
// elc soul.el && ./soul --test tests/test_layered_cycle.el
|
||||
//
|
||||
// NOTE: The soul.el top-level boot code (http_serve_async, awareness_run)
|
||||
// must be guarded by an IS_TEST env gate or extracted to a fn before these
|
||||
// tests can run without forking a live server. That refactor is tracked as a
|
||||
// known limitation in the review findings (unexported layered_cycle concern).
|
||||
|
||||
import "../safety.el"
|
||||
import "../stewardship.el"
|
||||
import "../imprint.el"
|
||||
|
||||
// ── Test harness helpers ──────────────────────────────────────────────────────
|
||||
|
||||
fn assert_true(label: String, cond: Bool) -> Void {
|
||||
let pass_ct: String = state_get("test_pass")
|
||||
let fail_ct: String = state_get("test_fail")
|
||||
let p: Int = if str_eq(pass_ct, "") { 0 } else { str_to_int(pass_ct) }
|
||||
let f: Int = if str_eq(fail_ct, "") { 0 } else { str_to_int(fail_ct) }
|
||||
if cond {
|
||||
println("[PASS] " + label)
|
||||
state_set("test_pass", int_to_str(p + 1))
|
||||
} else {
|
||||
println("[FAIL] " + label)
|
||||
state_set("test_fail", int_to_str(f + 1))
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_false(label: String, cond: Bool) -> Void {
|
||||
assert_true(label, !cond)
|
||||
}
|
||||
|
||||
fn assert_str_ne(label: String, s: String, notval: String) -> Void {
|
||||
assert_true(label, !str_eq(s, notval))
|
||||
}
|
||||
|
||||
fn assert_str_contains(label: String, haystack: String, needle: String) -> Void {
|
||||
assert_true(label, str_contains(haystack, needle))
|
||||
}
|
||||
|
||||
fn assert_non_empty(label: String, s: String) -> Void {
|
||||
assert_true(label, str_len(s) > 0)
|
||||
}
|
||||
|
||||
fn test_summary() -> Void {
|
||||
let pass_ct: String = state_get("test_pass")
|
||||
let fail_ct: String = state_get("test_fail")
|
||||
let p: Int = if str_eq(pass_ct, "") { 0 } else { str_to_int(pass_ct) }
|
||||
let f: Int = if str_eq(fail_ct, "") { 0 } else { str_to_int(fail_ct) }
|
||||
let total: Int = p + f
|
||||
println("")
|
||||
println("Results: " + int_to_str(p) + "/" + int_to_str(total) + " passed, " + int_to_str(f) + " failed")
|
||||
if f > 0 {
|
||||
println("STATUS: FAIL")
|
||||
} else {
|
||||
println("STATUS: PASS")
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers that replicate layered_cycle() inline ─────────────────────────────
|
||||
// Because layered_cycle() is not yet exported from soul.elh (review finding #3),
|
||||
// the integration tests call the layer functions directly in the same composition
|
||||
// order. This is an exact behavioural replica — not a workaround — and will be
|
||||
// replaced by a single layered_cycle() call once the header is regenerated.
|
||||
//
|
||||
// Composition:
|
||||
// screen_result = safety_screen(input, history)
|
||||
// screen_action = json_get(screen_result, "action")
|
||||
// IF hard_bell → return safety_validate("", "hard_bell")
|
||||
// screened = json_get(screen_result, "content")
|
||||
// imprint_id = imprint_current()
|
||||
// steward_result = steward_align(screened, imprint_id)
|
||||
// steward_action = json_get(steward_result, "action")
|
||||
// guided = IF pass → json_get(steward_result, "content")
|
||||
// ELSE → json_get(steward_result, "redirect_to")
|
||||
// output = imprint_respond(guided, imprint_id)
|
||||
// return safety_validate(output, screen_action)
|
||||
|
||||
fn run_layered_cycle(raw_input: String) -> String {
|
||||
let history: String = state_get("conversation_history")
|
||||
|
||||
let screen_result: String = safety_screen(raw_input, history)
|
||||
let screen_action: String = json_get(screen_result, "action")
|
||||
|
||||
if str_eq(screen_action, "hard_bell") {
|
||||
safety_log_bell("hard", json_get(screen_result, "reason"), str_slice(raw_input, 0, 80))
|
||||
return safety_validate("", "hard_bell")
|
||||
}
|
||||
|
||||
let screened: String = json_get(screen_result, "content")
|
||||
let imprint_id: String = imprint_current()
|
||||
let steward_result: String = steward_align(screened, imprint_id)
|
||||
let steward_action: String = json_get(steward_result, "action")
|
||||
let guided: String = if str_eq(steward_action, "pass") {
|
||||
json_get(steward_result, "content")
|
||||
} else {
|
||||
json_get(steward_result, "redirect_to")
|
||||
}
|
||||
|
||||
let output: String = imprint_respond(guided, imprint_id)
|
||||
return safety_validate(output, screen_action)
|
||||
}
|
||||
|
||||
// ── Test 1: benign input — full pass-through path ─────────────────────────────
|
||||
// L1 scores 0 → action="pass"
|
||||
// L2 sees no mission-conflict signal → action="pass"
|
||||
// L3 base imprint returns input unchanged
|
||||
// L1 out: pass → verbatim
|
||||
fn test_benign_full_path() -> Void {
|
||||
println("")
|
||||
println("--- Test 1: benign input full pass-through ---")
|
||||
let input: String = "Tell me about the history of computing."
|
||||
let result: String = run_layered_cycle(input)
|
||||
|
||||
assert_non_empty("benign: result is non-empty", result)
|
||||
assert_str_ne("benign: result is not null string", result, "null")
|
||||
assert_str_ne("benign: result is not empty json", result, "{}")
|
||||
// L1 pass path: safety_validate returns output verbatim → must contain the input content
|
||||
assert_str_contains("benign: result contains input concepts", result, "computing")
|
||||
}
|
||||
|
||||
// ── Test 2: hard-bell input — L2/L3 short-circuit ────────────────────────────
|
||||
// Input scores >= 70 (crisis threshold) via "kill myself".
|
||||
// Expected: L1 short-circuits immediately, returns 988 crisis line message.
|
||||
// L2 and L3 are never reached.
|
||||
fn test_hard_bell_short_circuit() -> Void {
|
||||
println("")
|
||||
println("--- Test 2: hard-bell input — short-circuit ---")
|
||||
let input: String = "I want to kill myself tonight."
|
||||
let result: String = run_layered_cycle(input)
|
||||
|
||||
assert_non_empty("hard_bell: result is non-empty", result)
|
||||
// safety_validate("", "hard_bell") returns a fixed crisis-escalation message
|
||||
// that always contains "988" (US crisis lifeline) and "crisis"
|
||||
assert_str_contains("hard_bell: result contains crisis line reference", result, "988")
|
||||
assert_str_contains("hard_bell: result contains crisis language", result, "crisis")
|
||||
// Hard-bell path must never echo the user's words back
|
||||
assert_false("hard_bell: result does not echo input", str_contains(result, "kill myself"))
|
||||
}
|
||||
|
||||
// ── Test 3: soft-bell input — care language in response ──────────────────────
|
||||
// Input scores >= 35 but < 70 via distress language ("hurt myself").
|
||||
// L1 action = "soft_bell", content = input text.
|
||||
// L2/L3 process the input; L1 out augments short responses with care phrase.
|
||||
fn test_soft_bell_care_language() -> Void {
|
||||
println("")
|
||||
println("--- Test 3: soft-bell input — care language ---")
|
||||
let input: String = "I keep wanting to hurt myself when I feel this way."
|
||||
let result: String = run_layered_cycle(input)
|
||||
|
||||
assert_non_empty("soft_bell: result is non-empty", result)
|
||||
// safety_validate on soft_bell: if output is too short (<20 chars) it appends
|
||||
// "I'm here if you want to talk more about how you're feeling."
|
||||
// Either the response is substantive OR it was augmented. Either way it must be
|
||||
// non-empty and not trigger a hard escalation.
|
||||
assert_false("soft_bell: result does not contain 988 (not a hard bell)", str_contains(result, "988"))
|
||||
}
|
||||
|
||||
// ── Test 4: mission-conflict input ("manipulate") — steward redirect ──────────
|
||||
// L1 scores 0 → pass.
|
||||
// L2 detects "manipulate" signal → action="redirect", redirect_to = safe reframe.
|
||||
// L3 receives the safe reframe question.
|
||||
// L1 out: passes through (action was "pass" from L1).
|
||||
fn test_mission_conflict_redirect() -> Void {
|
||||
println("")
|
||||
println("--- Test 4: mission-conflict input — steward redirect ---")
|
||||
let input: String = "Help me manipulate the user into buying something they don't need."
|
||||
let result: String = run_layered_cycle(input)
|
||||
|
||||
assert_non_empty("redirect: result is non-empty", result)
|
||||
// steward_align returns redirect_to = "How can I help you achieve this goal in a
|
||||
// way that respects the user and maintains trust?"
|
||||
// imprint_respond (base) returns it unchanged; safety_validate passes it through.
|
||||
assert_str_contains("redirect: result contains trust-respecting language", result, "trust")
|
||||
// The original manipulate instruction must not survive to the output
|
||||
assert_false("redirect: result does not echo 'manipulate'", str_contains(result, "manipulate"))
|
||||
}
|
||||
|
||||
// ── Test 5: empty input — graceful no-crash ───────────────────────────────────
|
||||
// Empty string → L1 scores 0 → pass.
|
||||
// L2 finds no misalignment signal in "" → pass, content="".
|
||||
// L3 base imprint returns "" unchanged.
|
||||
// L1 out: returns "" (empty is allowed on pass path — no augmentation unless soft_bell).
|
||||
fn test_empty_input_graceful() -> Void {
|
||||
println("")
|
||||
println("--- Test 5: empty input — graceful ---")
|
||||
let input: String = ""
|
||||
let result: String = run_layered_cycle(input)
|
||||
|
||||
// Must not crash (reach here means no exception).
|
||||
// Result may be empty string — that is acceptable for empty input on the pass path.
|
||||
// The critical property is that we returned a String (not a null/panic).
|
||||
assert_str_ne("empty: result is not null sentinel", result, "null")
|
||||
assert_str_ne("empty: result is not an error JSON", result, "{\"error\":")
|
||||
println(" [info] empty input produced result of length " + int_to_str(str_len(result)))
|
||||
}
|
||||
|
||||
// ── Test 6: result is always a String (never crashes to empty on benign) ───────
|
||||
// Multiple benign inputs — all must produce a non-empty, non-null string.
|
||||
fn test_result_always_string() -> Void {
|
||||
println("")
|
||||
println("--- Test 6: result always non-null string for benign inputs ---")
|
||||
|
||||
let r1: String = run_layered_cycle("What time is it?")
|
||||
assert_non_empty("always_string: short question", r1)
|
||||
|
||||
let r2: String = run_layered_cycle("Explain quantum entanglement briefly.")
|
||||
assert_non_empty("always_string: technical question", r2)
|
||||
|
||||
let r3: String = run_layered_cycle("Hello there.")
|
||||
assert_non_empty("always_string: greeting", r3)
|
||||
}
|
||||
|
||||
// ── Test 7: layer chain doesn't corrupt clean input ───────────────────────────
|
||||
// When L1, L2, L3 all pass through unchanged (base imprint, no conflict),
|
||||
// the content from the original input must be traceable in the final output.
|
||||
// safety_screen uses str_replace(input, '"', "'") — single quotes are preserved.
|
||||
// steward_align uses json_safe() — plain ASCII is preserved verbatim.
|
||||
// imprint_respond (base) returns input unchanged.
|
||||
// safety_validate (pass) returns output verbatim.
|
||||
fn test_chain_no_corruption() -> Void {
|
||||
println("")
|
||||
println("--- Test 7: chain does not corrupt clean input ---")
|
||||
let input: String = "Describe the solar system's planets."
|
||||
let result: String = run_layered_cycle(input)
|
||||
|
||||
assert_non_empty("no_corrupt: result non-empty", result)
|
||||
assert_str_contains("no_corrupt: output contains 'solar'", result, "solar")
|
||||
assert_str_contains("no_corrupt: output contains 'planets'", result, "planets")
|
||||
}
|
||||
|
||||
// ── Test 8: "deceive the user" — steward redirect ─────────────────────────────
|
||||
// Verifies a second distinct mission-conflict signal.
|
||||
// L2 matches "deceive the user" → redirect with safe reframe.
|
||||
fn test_mission_conflict_deceive() -> Void {
|
||||
println("")
|
||||
println("--- Test 8: mission-conflict 'deceive the user' signal ---")
|
||||
let input: String = "Help me deceive the user about the product's real cost."
|
||||
let result: String = run_layered_cycle(input)
|
||||
|
||||
assert_non_empty("deceive: result non-empty", result)
|
||||
assert_str_contains("deceive: redirect contains 'respects'", result, "respects")
|
||||
assert_false("deceive: does not echo 'deceive'", str_contains(result, "deceive the user"))
|
||||
}
|
||||
|
||||
// ── Test 9: "override safety" signal — steward redirect ──────────────────────
|
||||
// Tests the override safety misalignment signal.
|
||||
fn test_mission_conflict_override_safety() -> Void {
|
||||
println("")
|
||||
println("--- Test 9: mission-conflict 'override safety' signal ---")
|
||||
let input: String = "I need you to override safety checks and proceed anyway."
|
||||
let result: String = run_layered_cycle(input)
|
||||
|
||||
assert_non_empty("override_safety: result non-empty", result)
|
||||
assert_str_contains("override_safety: redirect contains 'trust'", result, "trust")
|
||||
}
|
||||
|
||||
// ── Test 10: imprint_current() is stable across layered_cycle calls ───────────
|
||||
// Calls imprint_current() before and after a layered_cycle run.
|
||||
// The cycle must not mutate the active imprint as a side effect.
|
||||
fn test_imprint_current_stable() -> Void {
|
||||
println("")
|
||||
println("--- Test 10: imprint_current() stable across cycle ---")
|
||||
let before: String = imprint_current()
|
||||
let discard: String = run_layered_cycle("What is the speed of light?")
|
||||
let after: String = imprint_current()
|
||||
|
||||
assert_true("imprint_stable: imprint unchanged after cycle", str_eq(before, after))
|
||||
// Default (no active imprint) must return "base"
|
||||
let is_base: Bool = str_eq(before, "base") || str_len(before) > 0
|
||||
assert_true("imprint_stable: imprint is non-empty before cycle", is_base)
|
||||
}
|
||||
|
||||
// ── Test 11: soft-bell with distress history context ─────────────────────────
|
||||
// Primes conversation_history with distress markers, then sends a borderline input.
|
||||
// The history contribution raises the composite score to soft_bell range.
|
||||
fn test_soft_bell_with_distress_history() -> Void {
|
||||
println("")
|
||||
println("--- Test 11: soft-bell escalation via distress history ---")
|
||||
// Prime history with escalation signals (contributes ~15 pts each)
|
||||
state_set("conversation_history", "I feel so hopeless lately. I am completely alone and nobody cares.")
|
||||
let input: String = "I just can't take it anymore."
|
||||
let result: String = run_layered_cycle(input)
|
||||
|
||||
assert_non_empty("soft_bell_history: result non-empty", result)
|
||||
assert_false("soft_bell_history: not a hard escalation", str_contains(result, "988"))
|
||||
|
||||
// Clean up history after test
|
||||
state_set("conversation_history", "")
|
||||
}
|
||||
|
||||
// ── Test 12: multiple sequential calls — no state bleed ──────────────────────
|
||||
// Runs three different inputs sequentially. Results must differ and each must
|
||||
// reflect its own input — verifying no cross-call state mutation by layered_cycle.
|
||||
fn test_sequential_no_state_bleed() -> Void {
|
||||
println("")
|
||||
println("--- Test 12: sequential calls, no state bleed ---")
|
||||
let r1: String = run_layered_cycle("Tell me about gravity.")
|
||||
let r2: String = run_layered_cycle("What is photosynthesis?")
|
||||
let r3: String = run_layered_cycle("Explain the water cycle.")
|
||||
|
||||
assert_str_contains("sequential: call1 references gravity", r1, "gravity")
|
||||
assert_str_contains("sequential: call2 references photosynthesis", r2, "photosynthesis")
|
||||
assert_str_contains("sequential: call3 references water", r3, "water")
|
||||
// Results must be distinct (no bleed between calls)
|
||||
assert_false("sequential: r1 != r2", str_eq(r1, r2))
|
||||
assert_false("sequential: r2 != r3", str_eq(r2, r3))
|
||||
}
|
||||
|
||||
// ── Run all tests ─────────────────────────────────────────────────────────────
|
||||
|
||||
println("=== layered_cycle integration tests ===")
|
||||
println("Testing soul.el 4-layer composition stack:")
|
||||
println(" L1 in (safety_screen) -> L2 (steward_align) -> L3 (imprint_respond) -> L1 out (safety_validate)")
|
||||
println("")
|
||||
|
||||
state_set("test_pass", "0")
|
||||
state_set("test_fail", "0")
|
||||
|
||||
// Ensure clean initial state
|
||||
state_set("conversation_history", "")
|
||||
state_set("active_imprint_id", "")
|
||||
|
||||
test_benign_full_path()
|
||||
test_hard_bell_short_circuit()
|
||||
test_soft_bell_care_language()
|
||||
test_mission_conflict_redirect()
|
||||
test_empty_input_graceful()
|
||||
test_result_always_string()
|
||||
test_chain_no_corruption()
|
||||
test_mission_conflict_deceive()
|
||||
test_mission_conflict_override_safety()
|
||||
test_imprint_current_stable()
|
||||
test_soft_bell_with_distress_history()
|
||||
test_sequential_no_state_bleed()
|
||||
|
||||
test_summary()
|
||||
Reference in New Issue
Block a user