fix(api): bound inspect_graph with relevance-ranked projection; regen soul.c
Neuron Soul CI / build (pull_request) Failing after 14m5s
Neuron Soul CI / deploy (pull_request) Has been skipped

High-fanout identity anchors (voice, writing-imprint, self-root) have ~670KB
neighborhoods. inspect_graph returned the full traversal, which overflowed the
MCP client's context and socket-closed the wrapper mid self-load -- the soul
could not traverse its own identity graph.

handle_api_inspect_graph gains an opt-in `compact` projection (compact=1|true):
the neighborhood is relevance-ranked, the top K (default 12) keep a UTF-8-safe
content snippet (default snip=600), and the remainder collapse to lightweight
{id,label,node_type,tier,edge,pointer:true} stubs. This bounds the voice node
from 669,799B -> 25,353B (HTTP 200, valid JSON) and the wrapper's soul-load no
longer socket-closes. New helpers: api_compact_neighbors, api_neigh_full,
api_neigh_pointer, api_neigh_rank, api_neigh_better, api_float_or.

The flag is gated: ABSENT it, the response is byte-identical to the old plain
traversal, so the studio app (which never sends it) is unaffected. The MCP
wrapper (mcp-wrapper/src/main.el) appends &compact=1 on its inspectGraph and
fetch-by-id paths.

dist/soul.c is REGENERATED so CI ships the fix: CI compiles the committed
single-TU dist/soul.c directly (running elb/elc on the Linux runner OOM-kills
it), so an .el-only change would build the OLD behavior. Regenerated and verified
on macOS -- compiles with the CI cc line (0 errors) and, on a throwaway soul over
a copy of the live snapshot, serves compact ~25KB / non-compact ~670KB. The regen
also syncs the amalgamation to this branch's .el sources, which had drifted
several self-review commits ahead of the previously-committed soul.c.

Docs: docs/architecture/00-05 added; 01/02/05 corrected so the relevance-ranked
inspect_graph projection reads as committed source, not an in-flight concern.
This commit is contained in:
2026-08-10 10:28:50 -05:00
parent 64cd5055c5
commit 4bff40fa4a
10 changed files with 2314 additions and 466 deletions
Generated Vendored
+946 -464
View File
File diff suppressed because one or more lines are too long
+145
View File
@@ -0,0 +1,145 @@
# Neuron — Architecture Overview
> Status: living document. Grounded in the committed source of the `neuron`
> repository as of 2026-08-10. Every structural claim cites a real file. Where a
> statement is inferred rather than read directly, it is labelled *(inference)*
> or *(unverified/TODO)*.
## What Neuron is
Neuron is a **persistent CGI (Cultivated General Intelligence) runtime**. It is
not a chatbot and not a stateless API in front of an LLM. It is a long-lived
process that *remembers* — it carries an identity, a graph of memory and
knowledge, and an autonomous idle-cognition loop across restarts. The LLM is one
resource it calls; the durable part is the **engram** (the graph) and the
**soul** (the program that reasons over it).
Three things run together to make that true:
- **The soul** — the compiled El program in this repo. It owns the HTTP surface,
the cognitive API, the request pipeline (`layered_cycle`), and the autonomous
awareness daemon. Entry point `soul.el`, served by `handle_request`
(`routes.el:358`).
- **The engram** — the graph store. Node/edge model, spreading activation, and
Hebbian co-activation physically live in the shared El runtime
(`el_runtime.c`); `engram/src/server.el` is a thin HTTP face on `:8742`. The
engram is a *sibling* repo (`foundation/el/engram`), compiled and co-located at
runtime, not part of this repo's source tree.
- **The El runtime** — `el_runtime.c` / `el_runtime.h`. Every compiled El binary
links it. It implements all builtins (`engram_*`, `http_*`, `json_*`, LLM,
crypto) and *is* the database — "no SQL, no db layer, no SQLite"
(`../foundation/el/engram/src/server.el:4-6`).
Neuron persists memory itself — this repo is the memory system. Do not confuse
it with the Neuron desktop/UI application, which is **out of scope** here and is
only ever a *client* of the MCP surface described in this set.
## System context
```
┌────────────────────────────────────────────────────────────┐
│ MCP clients (Claude Code, Soma chat UI, agents) │
│ — talk MCP JSON-RPC over stdio, or HTTP to the soul │
└───────────────┬────────────────────────────────────────────┘
│ MCP JSON-RPC (stdio)
┌──────────▼──────────┐
│ mcp-proxy :7779 │ byte-forwarder + retry + health
└──────────┬──────────┘
│ MCP JSON-RPC (stdio→HTTP)
┌──────────▼──────────┐
│ mcp-wrapper :17779 │ JSON-RPC ⇄ soul REST; ~90-tool catalog
└──────────┬──────────┘
│ HTTP (REST)
┌──────────▼──────────┐ ┌──────────────────────────┐
│ soul :7770 │──HTTP──▶│ engram :8742 │
│ handle_request │ │ graph store (snapshot) │
│ layered_cycle │◀──────▶│ el_runtime.c = the DB │
│ awareness daemon │ └──────────────────────────┘
└──────────┬──────────┘
│ HTTP
┌───────────────┼───────────────┬───────────────┐
▼ ▼ ▼ ▼
Axon backend neuron-connectd LLM API (self-callback
:backlog/ :7771 connectors Anthropic NEURON_API_URL)
artifacts/ (MCP bridges) format
projects
```
*Ports/topology verified*: proxy `:7779` and wrapper `:17779`
(`mcp-proxy/src/main.el`, `mcp-wrapper/src/main.el`); soul `:7770`
(`NEURON_PORT`, k8s `deployment-blue.yaml`); engram `:8742` (`entrypoint.sh`,
`server.el:711`). The Axon backend, `neuron-connectd` (`:7771`), and the LLM are
external dependencies the soul reaches over HTTP (`routes.el` `axon_get/post`,
`connectd_get/post`).
## The two external interfaces
Neuron exposes exactly two surfaces, and it is worth being precise about the
difference because they drive the whole component split:
1. **The MCP surface** — the *tool* interface. MCP clients call tools
(`begin_session`, `remember`, `search_knowledge`, `inspect_graph`,
`cultivate`, …). This is the interface Claude Code and agents use. It is
delivered by the **proxy → wrapper** chain, which translates MCP JSON-RPC
into the soul's HTTP REST calls. The wrapper carries a catalog of ~90 tools
(`mcp-wrapper/src/main.el`).
2. **The HTTP API** — the *cognitive* interface. The soul serves REST on
`:7770`. `routes.el` dispatches; `neuron-api.el` handles the cognitive
endpoints (`/api/neuron/*`). This same surface backs the chat product
(`/api/chat`, `/api/sessions`) and the studio UI (`/`).
In production the MCP client connects to the soul's HTTP directly — the
`neuron-mcp` ClusterIP Service targets `:7770` (`service.yaml`) and the
proxy/wrapper chain is primarily the **local developer adapter** that lets a
stdio MCP client speak to an HTTP soul. See `04-runtime-and-deployment.md`.
## Component map (summary)
The full VBD classification is in `01-vbd-decomposition.md`. In one glance:
| Layer | Module(s) | Role |
|---|---|---|
| HTTP dispatch | `routes.el` | Manager — hand-written method/path dispatch |
| Cognitive API | `neuron-api.el` | Managers + Engines — session/memory/knowledge/graph/cultivation handlers |
| Request pipeline | `soul.el` `layered_cycle` | Manager — L1 safety → L2 stewardship → L3 imprint |
| Boot + identity | `soul.el` | Manager — compose layers, seed identity graph, start server + daemon |
| Autonomous cognition | `awareness.el` | Manager (`awareness_run`) + Engines (curiosity, attend, threat) |
| Memory access | `memory.el` | Resource Accessor over the engram FFI/HTTP |
| Store | `engram/server.el` + `el_runtime.c` | Accessor (HTTP) over the real graph engine |
| Request-layer rules | `safety.el`, `stewardship.el`, `imprint.el` | Engines |
| Conversation sessions | `sessions.el` | Manager (chat product) |
| MCP transport | `mcp-proxy`, `mcp-wrapper` | Managers/Accessors — protocol boundary |
| Build | `manifest.el`, `dist/soul.c`, El toolchain | amalgamation → `soul.c` → binary |
## Reading guide
- **`01-vbd-decomposition.md`** — the volatility analysis. Start here for *why*
the boundaries fall where they do. Contains the full Manager/Engine/Accessor/
Utility table and the honest list of where the real code diverges from VBD.
- **`02-components.md`** — per-subsystem detail: routing, the cognitive API, the
memory & activation engine, the MCP transport chain. Read after 01.
- **`03-data-and-memory.md`** — the engram graph model: node/edge structs,
layers, the two tier systems, write-protection, tombstone/supersede
immutability, persistence.
- **`04-runtime-and-deployment.md`** — process/port topology, the end-to-end MCP
request path, local vs GKE blue/green, secrets/config.
- **`05-el-and-build.md`** — the El language, the `elc`/`elb` toolchain, the
amalgamation → `soul.c` → binary pipeline, and the compile-time capability
gates.
## A note on honesty
Two facts shape everything below and are stated once here so the rest reads
straight:
1. **The most volatile logic — the activation and Hebbian math — lives in the
most stable-looking layer**, the C runtime (`el_runtime.c`). The El files in
this repo are largely a *Manager + Accessor shell* around that core. This
inverts the usual VBD expectation and is called out wherever it matters.
2. **The immutability guarantee lives above the store, not in it.** The engram
HTTP server will hard-delete a node (`DELETE /api/nodes/:id`
`engram_forget`, `server.el:322`). Immutability holds only because the
neuron-api / MCP layer routes every user-facing delete through *tombstone*
instead (`memory.el:46`). The invariant is a policy, not a property of the
accessor.
+218
View File
@@ -0,0 +1,218 @@
# Neuron — VBD Decomposition
> This is the load-bearing document. It applies Volatility-Based Decomposition
> (VBD) to the *actual* neuron code, not an idealized version of it. VBD asks one
> question — **what changes, why, and how often** — and draws component
> boundaries around the answers so that a change lands inside one component
> instead of rippling across many.
>
> VBD's component taxonomy:
> - **Managers** — stable orchestrators. They sequence use-cases and delegate;
> they change only when the *shape* of a workflow changes.
> - **Engines** — volatile business rules. The "how" that churns.
> - **Resource Accessors** — isolate an external dependency (a store, an API) so
> its volatility can't leak inward.
> - **Utilities** — cross-cutting, low-volatility helpers.
>
> Communication ideal: Managers orchestrate Engines and Accessors; Managers
> prefer async/event coupling to each other; Engines are stateless-ish and never
> reach external I/O directly; Accessors hide all I/O. We note below where neuron
> honors this and where it doesn't.
## The axes of change
Before classifying modules, name the volatility. These are the axes along which
neuron actually changes, ranked by observed churn (dated self-review comments in
the source are the evidence — the code keeps a changelog in its own margins).
### 1. Context / payload shaping — *highest churn*
How much of the graph, and in what projected form, gets returned to a
bounded MCP response. The `begin_session` / `compile_ctx` handlers and the
`api_compact_*` helpers carry dense dated review comments (2026-07-30, -31)
documenting repeated rework after unbounded payloads closed the MCP client
socket (`neuron-api.el:90-317`). This changes because the *client's* context
budget and the *shape* of "what's relevant right now" keep moving. The newest
rework in this axis is the **relevance-ranked neighbor projection**
(`api_compact_neighbors` + `api_neigh_*`) behind `inspect_graph`'s `compact=1`
path — it is what keeps *self-load* (traversing the high-fanout identity anchors)
from closing the socket. It is committed source, compiled into `dist/soul.c`.
### 2. Autonomous-cognition policy
What the idle soul chooses to think about: seed-domain selection, curiosity
rotation, novelty gating, and the inbox verb-mapping in `attend()`. The
`proactive_curiosity` / `auto_term_try_slot` machinery
(`awareness.el:590-876`) has the deepest git-archaeology in the codebase
(comments spanning 2026-05 → 2026-08). This is where the *behavior* of the
agent is tuned.
### 3. Epistemic & memory semantics
Tiers, salience mapping, promotion/consolidation, the immutability policy
(tombstone/supersede), and knowledge disposition. These evolve as the memory
*philosophy* matures — e.g. `mem_forget` becoming a soft delete
(`memory.el:70`), the salience-evolution pass in `mem_consolidate`
(`memory.el:92-133`), the supersede-edge pattern (`neuron-api.el:394-428`).
### 4. Safety & stewardship rules
Crisis bell thresholds, agentic threat scoring, mission alignment, CGI
continuity fingerprinting. `safety.el`, `stewardship.el`, and the threat
scorer grafted onto `awareness.el:1286-1419` change on behavioral/regulatory
pressure, independently of everything else.
### 5. API / route surface growth
New cognitive endpoints and their dispatch. `routes.el` grows structurally as
tools are added; the `handle_request` if/else chain (`routes.el:358-753`) is
edited on every surface change.
*(A sixth axis — the activation/Hebbian numeric math — is real and volatile but
is externalized to `el_runtime.c`. See "Divergences," point 6.)*
## The component map
Modules classified against the taxonomy, with the volatility that justifies each
placement. Paths are repo-relative unless noted `foundation/…`.
### Managers (stable orchestration)
| Module / function | File | Why a Manager |
|---|---|---|
| `handle_request` | `routes.el:358-753` | Top-level HTTP dispatcher. Pure method/path routing; delegates every body of work. Changes only when the *route surface* (axis 5) changes, not when logic changes. |
| Boot sequence | `soul.el:508-627` | Sequences load → seed → identity → serve → daemon. Highest stability; changes only on architecture shifts. |
| `layered_cycle` | `soul.el:382-506` | Request use-case pipeline: L1 safety → L2 stewardship (continuity, mission, affect) → L3 imprint → L1 output validation. Orchestrates Engines; holds no rules itself. |
| `awareness_run` / `one_cycle` | `awareness.el:1097-1284`, `1041-1095` | Daemon lifecycle + the perceive→attend→respond→record sequencer. Manager of the autonomous loop. |
| Session CRUD | `sessions.el` | Orchestrates the immutable delete-then-recreate dance for conversation sessions (chat product). Manager-flavored, but leaks store detail (see Divergences). |
| MCP proxy | `mcp-proxy/src/main.el` | Orchestrates transport: accept stdio, forward, retry, health-gate, wrap errors. |
| MCP wrapper | `mcp-wrapper/src/main.el` | Orchestrates the JSON-RPC ⇄ REST translation, tool catalog, lifecycle (`initialize`/`tools/list`/`tools/call`). |
### Engines (volatile business rules)
| Module / function | File | Volatility it absorbs |
|---|---|---|
| `api_compact_*`, `begin_session`, `compile_ctx` | `neuron-api.el:90-317` | Axis 1 — context/payload shaping. The single most-reworked logic on the API side. |
| `attend()` | `awareness.el:926-973` | Axis 2 — inbox content → action-verb ruleset. |
| `proactive_curiosity`, `auto_term_try_slot` | `awareness.el:590-876` | Axis 2 — seed selection, stopword/IDF gates, tabu ring. Textbook Engine: highest churn. |
| threat scoring | `awareness.el:1286-1419` | Axis 4 — additive command/path/history threat rules. |
| `safety.el` (crisis/harm/bell) | `safety.el` | Axis 4 — crisis screening, bell thresholds, output validation. |
| `stewardship.el` | `stewardship.el` | Axis 4 — mission alignment, CGI check, continuity fingerprint. |
| `imprint.el` | `imprint.el` | Axis 2/3 — persona response + knowledge/memory surfacing per imprint. |
| `mem_consolidate` | `memory.el:92-133` | Axis 3 — which nodes to strengthen; salience-evolution rules. |
| salience/importance mapping | `neuron-api.el` (repeated in `remember`, `node_create`, `evolve_memory`, `cultivate`) | Axis 3 — importance-enum → salience float mapping. |
| chat mode selection | `chat.el` (via `routes.el:433-440`, `597-604`) | plan / agentic / `layered_cycle` routing. |
| **activation + Hebbian math** | `foundation/.../el_runtime.c` | Axis 6 — the true cognitive Engine, externalized to C. |
### Resource Accessors (isolate external I/O)
| Accessor | File | Dependency isolated |
|---|---|---|
| `mem_*` | `memory.el` | The engram FFI/HTTP. **The** memory Accessor — clean, single isolation point; every forget routes through `mem_tombstone` (`memory.el:46`). |
| `engram_*` builtins + `server.el` | `el_runtime.c`, `foundation/el/engram/src/server.el` | The graph store over HTTP `:8742`. |
| `axon_get` / `axon_post` | `routes.el` | The Axon backend (backlog, artifacts, projects, memories, non-neuron knowledge). |
| `connectd_get` / `connectd_post` | `routes.el:303-324` | `neuron-connectd` bridge (`:7771`). |
| `llm_call_system` / `llm_call_agentic` | runtime builtins (used in `routes.el:115`, chat) | The LLM. |
| `ise_post`, `hebb_consolidate` | `awareness.el:101-148`, `64-99` | Durable engram HTTP (`/api/neuron/state-events`, `/api/edges/batch`). |
| `render_studio` | `studio.el` | The UI surface. |
### Utilities (cross-cutting, stable)
`flag_true`, `strip_query`, `err_404/405` (`routes.el:14-91`);
`api_json_escape`, `api_query_param/int`, `api_ok/err`, `api_nonempty`,
`api_utf8_trunc`, `api_persisted` (`neuron-api.el:45-201`); `idle_*`/`pulse_*`
counters, `elapsed_ms/human`, `make_action`, `embed_ok` (`awareness.el`);
`session_make_content`, `aff_try_slot`, JSON builders (`sessions.el`, `soul.el`).
Beneath all of these, the El runtime builtins (`json_*`, `http_*`, crypto, time)
are the utility substrate every module shares.
## Communication topology (as built)
```
MCP client
│ JSON-RPC
proxy ──► wrapper ──► soul.handle_request ──► neuron-api.handle_api_*
│ │
│ layered_cycle │ engram_* builtins
▼ ▼
safety / steward / imprint memory.el (Accessor)
(Engines) │
el_runtime.c graph
engram HTTP :8742
awareness_run (daemon) ──perceive──► engram inbox (soul-inbox-pending tag)
──hebb_consolidate──► POST /api/edges/batch
```
Two things about coupling:
- **Manager → Engine/Accessor is in-process and synchronous** (direct El calls),
which matches VBD: rules and I/O sit behind the Managers.
- **Manager ↔ Manager is *not* the VBD async-event ideal.** It is synchronous
HTTP (soul → engram, soul → Axon) plus one genuine event-ish channel: the
**engram inbox**. The awareness daemon `perceive()`s by polling a
`soul-inbox-pending` tag and consumes trigger nodes
(`awareness.el:900-924`, `1090-1093`), and modules communicate asynchronously
by writing **InternalStateEvent** nodes. That is a partial actor/event
pattern, realized through the graph rather than a message bus.
## Where reality diverges from VBD (call it out)
Honest deviations, so no one reads this doc as a conformance certificate:
1. **No route table.** Dispatch is a hand-written if/else chain in
`handle_request` (`routes.el:358-753`); there is no `register-route`
registry. Path params are sliced by hand (`str_slice` + `str_index_of`,
`routes.el:508-513, 539-541`) — one site carries an inline offset bug-fix
comment. Acceptable for a single dispatcher, but it means the "route surface"
Manager is edited manually on every change.
2. **Store I/O leaks into Managers.** `routes.el` inlines engram export logic for
`/api/graph/edges` (`routes.el:394-422`, with a 2026-08-07 comment about a
read-route that corrupted the canonical snapshot). The `awareness_run` sync
block inlines `http_get /api/sync` + `engram_load_merge`
(`awareness.el:1219-1279`). `emit_heartbeat` (`awareness.el:201-549`, ~350
lines) mixes Utility (formatting), Accessor (HTTP/FFI reads), and Manager
(state-delta tracking) in one function. These are Accessor responsibilities
living inside orchestration — the clearest VBD smell in the codebase.
3. **No authentication.** The only access control on the HTTP surface is per-IP
rate limiting (`routes.el:38-75`) plus `is_protected_node` on 15 hardcoded
identity IDs (`neuron-api.el:20-37`). There is no bearer/token check in the
dispatch path. Security is a cross-cutting concern only partially realized;
the deployment relies on a **single-trusted-client, internal-only** boundary
assumption (the `neuron-mcp` Service is ClusterIP, no external LB — see doc 04).
4. **Immutability is enforced above the Accessor, not in it.** The engram store
itself hard-deletes (`DELETE /api/nodes/:id``engram_forget`,
`server.el:322`). The invariant "we never delete, we tombstone/supersede"
is a *routing policy* in `memory.el` / `neuron-api.el`, not a property of the
store. A caller that hits the raw engram HTTP bypasses it.
5. **Mutation via delete-then-recreate.** Because nodes are immutable,
`sessions.el` mutates a session by deleting and recreating the node — flagged
non-atomic in its own comments (`sessions.el:303-308`, `:456`).
6. **The volatile core is in the stable layer.** The activation, decay, and
Hebbian co-activation math — genuinely high-volatility numeric policy — lives
in `el_runtime.c`, the foundational runtime every binary links. The El files
here are a Manager+Accessor shell around it. This inverts VBD's usual
layering (volatile logic should sit *above* stable infrastructure) and is the
single most important thing to understand before changing memory behavior:
you often can't, from this repo, without touching `foundation/el`.
7. **Vocabulary mismatch across layers.** The MCP-facing memory vocabulary
(tiers `note → lesson → canonical`, disposition
`experimental → … → deprecated`, importance enum `low/normal/high/critical`)
is **not** the engine's model. The engine uses cognitive tiers
`Working / Episodic / Semantic / Canonical` (a `tier` string field) plus
continuous `salience`/`importance`/`confidence` floats, and stores epistemic
tier/disposition as **tags** (`tier:canonical`, `disposition:stable`), not as
enforced state (`neuron-api.el:533`, `server.el:519-522`). The mapping is a
convention, not a guarded state machine. See `03-data-and-memory.md`.
## Testing spiral (VBD heuristic, as observed)
VBD recommends testing Engines first (pure logic), then Accessors (mock I/O),
then Managers (integration). The repo has `tests/*.el` matching this instinct —
`test_safety.el`, `test_bell_safety.el` (Engines), `test_layer_contract.el`
(the Manager↔Engine JSON contract `layered_cycle` depends on), `test_soul_guard.el`
(the boot Manager's seed guard), `test_sessions.el`. **Flag:** CI compiles and
smoke-tests only (`dist/neuron --help`); it does **not** run these `.el` suites
(`ci.yaml`). Whether they gate merges elsewhere is unverified — see doc 05.
+278
View File
@@ -0,0 +1,278 @@
# Neuron — Component Detail
> Per-subsystem detail: routing/dispatch, the cognitive API, the memory &
> activation engine, and the MCP transport chain. For the *why* behind these
> boundaries read `01-vbd-decomposition.md` first; this doc is the *what* and
> *how*, grounded in file citations.
---
## 1. Routing / dispatch — `routes.el`
**Responsibility:** turn an inbound HTTP request into a handler call. One
function does it.
- **Entry point:** `handle_request(method, path, body) -> String`
(`routes.el:358-753`). Structure: branch by method (`GET` `:384`, `POST`
`:549`, `DELETE` `:726`, `PATCH` `:739`), then an ordered sequence of exact
(`str_eq`) and prefix (`str_starts_with`) tests against the cleaned path.
First match wins. There is **no route table and no `register-route`** — this is
a deliberate hand-written dispatcher.
- **Path params** are extracted manually with `str_slice`/`str_index_of`
(session id `:539-541`, typed-node type `:508-513`).
- **Query strings** stripped up front by `strip_query` (`:77-83`); the raw path
(with query) is still passed to handlers that read params.
- **Pre-dispatch middleware** (cross-cutting, inline): an activity timestamp
(`state_set("soul.last_activity_ts", …)` `:367`) and **rate limiting**
(`rate_limit_check(ip, path)` `:38-75`, `:372-378`) — a per-IP 60 req/min
sliding window, `/health` exempt, loopback skipped, returns a 429 body.
- **Auth:** none in the dispatch path. See doc 01, Divergence 3.
- **Fallbacks:** `err_404` / `err_405`.
**Collaborators:** delegates to `neuron-api.el` (`/api/neuron/*`), `sessions.el`
(`/api/sessions/*`), `chat.el` (`/api/chat`, `/dharma/recv`), the Axon Accessor
(`axon_get/post` for `/api/backlog|artifacts|projects|memories|knowledge`),
`connectd_*` (`/api/connectors*`), `studio.el` (`/`), and engram builtins for the
raw `/api/graph*` reads.
**Route surface** (grouped; full table with line numbers is in the survey notes):
| Group | Representative routes | Handler home |
|---|---|---|
| Session/context | `/api/neuron/session/begin`, `/api/neuron/ctx`, `/api/sessions*` | neuron-api, sessions.el |
| Memory | `/api/neuron/memory`, `/recall`, `/memory/{evolve,forget,delete,update}`, `/node/{create,update,delete}` | neuron-api |
| Knowledge | `/api/neuron/knowledge/{search,capture,evolve,promote}`, `/knowledge` | neuron-api |
| Graph/activation | `/api/neuron/graph`, `/graph/link`, `/api/graph*`, `/list/:type` | neuron-api + engram builtins |
| Cultivation/self | `/api/neuron/cultivate`, `/lineage`, `/imprint/*`, `/synthesize` | neuron-api, routes.el |
| Processes/config | `/api/neuron/processes{,/define}`, `/config{,/tune}` | neuron-api |
| State/consolidate | `/api/neuron/state-events`, `/consolidate` | neuron-api |
| Backlog/artifacts | `/api/backlog`, `/artifacts`, `/projects`, `/memories` | Axon (HTTP) |
| Chat/NLG | `/api/chat`, `/see`, `/elp/chat`, `/dharma*`, `/nlg*` | chat.el, elp-input.el |
| Health/UI | `/health`, `/lineage`, `/` | routes.el, studio.el |
---
## 2. The cognitive API — `neuron-api.el`
**Responsibility:** the `/api/neuron/*` handlers — the operations that read and
write the engram as *cognition* (session, memory, knowledge, graph, config,
processes, state, cultivation). The file header notes these were migrated **out
of the MCP wrapper's HTTP calls into in-process engram builtins**
(`neuron-api.el:3-9`) — so most handlers call the store directly, no HTTP
round-trip.
**Primary collaborators** are the engram builtins (`engram_node_full`,
`engram_search_json`, `engram_activate_json`, `engram_scan_nodes_json`,
`engram_scan_nodes_by_type_json`, `engram_neighbors_json`, `engram_connect`,
`engram_get_node_json`, `engram_stats_json`, `engram_save`) and `memory.el` for
tombstoning.
**Handler groups:**
- **Session / context** — `handle_api_begin_session` (`:273-301`),
`handle_api_compile_ctx` (`:305-317`). Pull `engram_stats_json`, run
spreading activation (`engram_activate_json`, depth-1 for begin, depth-2 for
ctx), scan recent `InternalStateEvent`s, then **project the result through the
compaction helpers** so the payload can't overflow the MCP client's context.
This is Engine work (axis 1) inside a Manager-shaped entry point.
- **Memory** — `handle_api_remember` (`:322-348`): maps `importance` → salience,
injects a `project:<name>` tag, writes a `Memory`/`Episodic` node, then
**read-back-verifies** persistence (`api_persisted`). Deletes are **tombstone,
never hard delete** — `node_delete` / `memory_delete` / `forget` all route
through `tombstone_node``mem_tombstone`. Updates/evolves are **immutable
supersede** — `node_update` (`:397-429`), `evolve_memory` (`:711-735`) create a
new node and wire `engram_connect(new, old, "supersedes")`.
- **Knowledge** — `search_knowledge` (`:458-478`, falls back to
`engram_activate_json(q,2)` when lexical search returns nothing),
`browse_knowledge`, `capture_knowledge` (`:492-504`), `evolve_knowledge`,
`promote_knowledge` (`:526-542`, writes a canonical-tier node + supersede
edge). Evolve/promote respect `is_protected_node`.
- **Graph** — `handle_api_inspect_graph` (`:778-813`): resolves a named anchor
(`self`/`neuron``kn-efeb4a5b…`, `values``kn-5b606390…`) or an explicit
id, then `engram_neighbors_json(resolved, depth, "both")`. By default this is a
plain neighbor traversal (byte-identical to the old behavior, so the studio app
is unaffected). **When called with `compact=1` (or `true`) it returns a
relevance-ranked projection** (`:804-810`): the neighborhood is ranked and the
top **`k`** neighbors (default 12) keep a UTF-8-safe content snippet (default
`snip=600`) via `api_neigh_full`, while the remainder collapse to lightweight
`{id,label,node_type,tier,edge,pointer:true}` stubs via `api_neigh_pointer`.
This bounds a high-fanout identity anchor (voice, writing-imprint, self-root)
from ~670 KB to ~25 KB so the MCP transport no longer socket-closes on
self-load. The MCP wrapper appends `&compact=1` on its inspectGraph/fetch-by-id
path; the studio app omits the flag and is unchanged.
`handle_api_link_entities` (`:818-…`) creates edges but blocks edges *into*
protected nodes.
- **Cultivation** — `handle_api_cultivate` (`:781-839`): dispatches on
`operation` (evolve_knowledge / evolve_memory / forget / link_entities) and
performs the same engram ops **but skips `is_protected_node`** — the sanctioned
identity-write path, gated by convention to Will's explicit cultivation
sessions.
- **Config / processes / state-events / consolidate** — config anchors + a
`ConfigEntry` node search (`:616-639`), `tune_config` (`:642-653`),
`browse_processes` / `define_process` (`:547-568`), state-event log/list
(`:575-610`), and `consolidate` (`:855-880`, an `engram_save` snapshot plus an
optional `SessionSummary` node).
**The projection/compaction layer** (a real, recurring concern) lives in
`api_compact_node` (`:132-148`), `api_compact_node_array` (`:152-165`),
`api_compact_activated` (`:170-189`), and `api_utf8_trunc` (`:116-127`). These
**cap array length and truncate each node to identity + a bounded UTF-8-safe
content snippet.** Their consumers are `begin_session` and `compile_ctx`.
The design principle is the important part: *the API returns a relevance-bounded
projection of the graph, not the graph.* That bounding started as
length-capping + activation-ordering; it now also includes a **relevance-ranked
neighbor projection** — `api_compact_neighbors` (`:288-317`), backed by
`api_neigh_better`/`api_neigh_rank` (relevance ordering), `api_neigh_full`
(top-K, snippet), `api_neigh_pointer` (the rest, stub), and `api_float_or`. This
is **committed fact, not an in-flight concern**: it is the `compact=1` path of
`handle_api_inspect_graph` above, and it is what makes self-load survive the MCP
transport. It is compiled into `dist/soul.c` (this PR regenerated the
amalgamation so CI ships it — see doc 05).
---
## 3. Memory & activation engine
This subsystem spans three files in this repo (`memory.el`, `awareness.el`,
`soul.el`) and one in `foundation` (`el_runtime.c`). The split matters: **the
math is in C; the El files orchestrate, persist, and instrument it.**
### 3a. Memory access — `memory.el` (the Accessor)
The single isolation point over the engram FFI. Key functions:
| Fn | Lines | Backing call | Notes |
|---|---|---|---|
| `mem_store` | `5-28` | `engram_node_full` + read-back | verified write |
| `mem_remember` | `30-32` | `mem_store` | label `soul-memory` |
| `mem_recall` | `34-36` | `engram_activate_json(query, depth)` | **spreading-activation recall** (mutates WM) |
| `mem_search` | `38-40` | `engram_search_json` | pure lexical scan (no WM side-effect) |
| `mem_strengthen` | `42-44` | `engram_strengthen` | salience bump |
| `mem_tombstone` | `52-62` | `engram_node_full` + `engram_connect` | the one canonical soft-delete |
| `mem_forget` | `70-72` | `mem_tombstone` | soft delete (no longer hard) |
| `mem_consolidate` | `92-133` | `engram_wm_top_json`, `engram_strengthen` | salience-evolution pass |
| `mem_save` / `mem_load` | `135-148` | `engram_save/load` | snapshot I/O |
Note the distinction between **recall and search**: `mem_recall` fires spreading
activation (and warms working memory as a side effect); `mem_search` is a passive
lexical lookup. Tiers here are `tier_working` / `tier_episodic` / `tier_canonical`
(`memory.el:1-3`) — see doc 03 for how these relate to the engine's tier field
and to the MCP surface vocabulary.
### 3b. Autonomous cognition — `awareness.el` (the daemon)
`awareness.el` is the **idle-cognition daemon plus observability**, not
emotional-state code. `awareness_run()` (`:1097-1284`) is the master loop,
launched last from `soul.el:627`. Each tick (`SOUL_TICK_MS`, ~200ms):
1. **`one_cycle()`** (`:1041-1095`) — the cognitive step:
`perceive()` (`:900-924`, gated on a `soul-inbox-pending` tag, then
`engram_activate_json`) → `attend()` (`:926-973`, parse trigger content into
an action verb: remember / search / activate / strengthen / forget /
consolidate / respond) → `respond()` (`:975-1029`, dispatch to the `mem_*`
fns) → `record()` (`:1031-1039`, emit an InternalStateEvent) → consume the
trigger.
2. **Heartbeat** (every 60s): `hebb_consolidate()` **then** `emit_heartbeat()`
then `mem_save` snapshot (`:1189-1197`).
3. **Curiosity scan** (every 30s when idle): `proactive_curiosity()`
(`:701-876`) rotates 4 seed-domain sets, activates a seed, strengthens the
top result **only if it changed** (novelty-gated), and derives an
autobiographical seed from the top-10 working-memory nodes with
stopword/IDF/tabu filtering.
4. **Engram sync** (every 10 min): `GET /api/sync``engram_load_merge`
telemetry prune.
Two functions carry most of the file's weight and volatility:
- **`hebb_consolidate()`** (`:64-99`) — the durable-learning write-back. It drains
newly-formed co-activation edges (`engram_hebb_drain_json(64)`) and POSTs them
as one batch to `/api/edges/batch` (`:94`). The comment block (`:33-63`)
records that before this path existed the soul threw away ~1,198 learned
edges per restart — the daemon is where **essentially all co-activation
happens**, and this is how it survives.
- **`emit_heartbeat()`** (`:201-549`, ~350 lines) — assembles ~50 gauges (WM
saturation/churn, Hebbian candidate/edge counts, embedding coverage, corpus
health) into one ISE. Pure observability; a fat, churny Accessor/Utility mix.
A **threat scorer** (`:1286-1419`) is grafted onto the end — command/path/history
additive scoring, ≥70 blocks a tool call. Cross-cutting agentic-safety policy,
unrelated to memory mechanism.
### 3c. Identity & the request pipeline — `soul.el`
`soul.el` is the top-level program (`cgi "neuron-soul"`, `:12-17`) and imports
every other module (`:1-10`). It owns:
- **The identity graph.** `init_soul_edges()` (`:19-92`) hard-wires a `self_root`
node linked by `identity` edges (weight 0.95) to family/origin/value nodes,
plus a dense `co-value` mesh (weight 0.7) among 8 value nodes.
`ensure_self_canonical_bridge()` (`:101-110`) links the public traversal-root
anchor (`kn-efeb4a5b`) to the curated self node via `canonical-self` edges.
`load_identity_context()` (`:153-240`) loads intellectual-DNA / values /
memory-philosophy content into a state key for prompt injection.
- **Boot orchestration** (`:508-627`): load snapshot → optional first-boot seed
(guarded) → identity context → persona-from-env → boot-count increment →
session-start event → genesis-only edge init → `http_serve_async(port,
"handle_request")``awareness_run()`.
- **The request pipeline.** `layered_cycle()` (`:382-506`) — a 4-layer stack for
user input: **L1** safety screen (`safety_screen`) → **L2a** continuity/
behavioral (`steward_session_check`) → **L2b** mission alignment
(`steward_align`) → **L2c** affective-context injection → **L3**
`imprint_respond`**L1** output validation (`safety_validate`). Hard-bell
inputs bypass the upper layers. The JSON contract between these layers is
pinned by `tests/test_layer_contract.el`.
### 3d. Where the activation math actually is
`el_runtime.c` implements the two-layer activation model
(`background_activation` via BFS fan-out, then `working_memory_weight` via an
executive filter), ACT-R base-level learning (per-node access-timestamp ring
buffer), 768-dim semantic embeddings, and Hebbian eligibility traces. Retrieval
is **spreading activation, not query**:
`strength = parent_strength × edge_weight × target_salience ×
cosine(query, target)`. The El files never compute this — they seed it
(`engram_activate_json`), harvest it (`engram_hebb_drain_json`), and persist it.
See `03-data-and-memory.md`.
---
## 4. The MCP transport chain — `mcp-proxy`, `mcp-wrapper`
The chain exists because two boundaries vary independently: the *client
transport* (stdio MCP JSON-RPC) and the *soul's protocol* (HTTP REST). Each hop
absorbs one.
- **`mcp-proxy/src/main.el`** (listens `:7779`) — a **byte-forwarder**. It
accepts the client connection, forwards to the wrapper, and adds resilience:
retry, health-gating, and a well-formed error envelope so a downstream hiccup
never surfaces to the client as a broken pipe. It holds no MCP semantics —
pure transport orchestration.
- **`mcp-wrapper/src/main.el`** (listens `:17779`) — the **protocol translator**.
It speaks MCP JSON-RPC to the client and REST to the soul (`:7770`), owns the
MCP lifecycle (`initialize`, `tools/list`, `tools/call`), and carries the
**tool catalog** (~90 tools) that clients enumerate. `dispatch_tool_call` maps
each tool to a soul REST endpoint. It also fires a **spread-activation side
effect** (`fire_activation`) — after relevant calls it issues a `/recall` to
warm related nodes, so tool use itself nudges working memory. The tool schemas
in the catalog are largely name-only stubs — flag as a place where richer
schemas could live.
- **Manifests** (`mcp-proxy/manifest.el`, `mcp-wrapper/manifest.el`) declare the
build entry and package metadata for each transport binary.
**End-to-end (one `tools/call`):** client → proxy (`:7779`, forward+retry) →
wrapper (`:17779`, JSON-RPC→REST, catalog dispatch) → soul (`:7770`,
`handle_request``handle_api_*`) → engram builtins → (HTTP `:8742` when in HTTP
mode). The response walks back up, and the wrapper may fire a `/recall` warm-up
on the way. The full sequence is drawn in `04-runtime-and-deployment.md`.
**VBD reading:** proxy and wrapper are Managers of transport; the wrapper is also
the Accessor that isolates the *MCP protocol* boundary from the soul (the soul
knows only HTTP). The multi-hop shape is justified: the client transport, the
protocol translation, and the cognition each change for different reasons and are
deployed/updated independently.
+233
View File
@@ -0,0 +1,233 @@
# Neuron — Data & Memory (the Engram Graph Model)
> The engram is neuron's durable substrate. This document describes the graph
> model: node/edge structure, the consciousness layers, the two distinct tier
> systems, write-protection, the tombstone/supersede immutability model, and
> persistence. Sources: the runtime `el_runtime.c` (where the graph engine
> physically lives — "the runtime IS the database",
> `foundation/el/engram/src/server.el:1-6`), the engram HTTP face
> `server.el`, and the neuron-layer semantics in `memory.el` / `neuron-api.el`.
>
> Runtime path analyzed:
> `foundation/el/lang/releases/v1.0.0-20260501/el_runtime.c`.
## Where the model lives
The engram is **not** a database library. The graph, the activation math, and
Hebbian learning are compiled C in `el_runtime.c`; `server.el` is a thin HTTP
server that exposes them on `:8742`; the storage format is a single JSON
snapshot. There is no SQL, no SQLite, no append log. Keep this in mind: the
"schema" below is C structs, not tables.
> **Design-doc caveat.** `engram/README.md` describes a Rust/`sled`/`bincode`
> `EngramDb` with a `NodeType::Concept` enum. That is **aspirational/legacy
> narrative** — it does not match the shipped C engine. Treat the README as
> design story, not as the implementation. *(unverified against runtime)*
## Nodes
`EngramNode``el_runtime.c:5958-6018+`. Every node carries:
| Field group | Fields | Notes |
|---|---|---|
| Identity/content | `id`, `content`, `node_type`, `label`, `tier`, `tags`, `metadata` | all `char*` (`:5959-5965`) |
| Epistemic weights | `salience`, `importance`, `confidence` (double), `temporal_decay_rate` | per-node decay λ override; 0 = use global (`:5966-5969`) |
| Access history | `activation_count`, `last_activated`, `created_at`, `updated_at` | `:5970-5973` |
| Two-layer activation | `background_activation` (Layer 1, BFS fan-out), `working_memory_weight` (Layer 2, executive filter), `suppression_count` | context compilation uses **only** `working_memory_weight` (`:5974-5991`) |
| Consciousness layer | `layer_id` | default 1 = CORE_IDENTITY (`:5996`) |
| ACT-R learning | `access_ts[K]` ring buffer, `access_head`, `access_filled`, `wm_anchor` | base-level learning (`:5997-6008`) |
| Semantics | `emb` (768-dim nomic-embed-text vector, lazily backfilled), `emb_dim` | `:6009-6016` |
| Hebbian | eligibility trace | `:6017+` |
### Node types are strings, not an enum
`node_type` is a free `char*`, defaulting to `"Memory"` when unset
(`el_runtime.c:7401`, `server.el:159`). There is **no closed node-type enum** in
the shipped engine. Two consequences:
- The runtime *special-cases* a handful of type strings for activation
thresholds (`engram_type_threshold`, `:5933-5955`): `DharmaSelf`/`Safety`
(0.05, fire easily), `Belief`/`Entity` (0.30), `Knowledge` (0.20), everything
else `Note`/`Memory`/`Working` (0.40). `InternalStateEvent` and `Tag` are
**excluded from working-memory promotion** (`:6674-6676`, `:7368-7370`).
- Type strings the neuron layer actually writes: `Memory` (default), `Knowledge`
(`server.el:549`), `InternalStateEvent` (`server.el:493`), `Tombstone`
(`memory.el:55`), `Conversation` (session nodes, `sessions.el`), `Persona`
(`soul.el:250-292`), plus identity/value `Knowledge` nodes.
The types the MCP surface names — `Self`, `BacklogItem`, `SessionSummary`,
`Artifact`, `Process`, `ConfigEntry` — are **`node_type` string conventions set
by higher neuron/Axon layers**, not runtime-known types. Where `BacklogItem` /
`Artifact` are set was not in the files read (they route to the Axon backend, doc
02) — **flag as unverified/TODO** for a human pass.
## Edges
`EngramEdge``el_runtime.c:6701-6730+`. Directed, typed, weighted:
| Field | Meaning |
|---|---|
| `id`, `from_id`, `to_id`, `relation` | typed relation string |
| `weight` (double) | **authored** strength — never mutated by activation |
| `hebb` (double) | **learned** co-activation potentiation — the fraction of recent activations in which both endpoints were in working memory together; strictly separate from `weight` |
| `inhibitory` (int flag) | if set, activating the source **suppresses** the target's WM weight instead of exciting it |
| `confidence`, `created_at`, `updated_at`, `last_fired`, `layer` | — |
The **`hebb` field is the co-activation weight** — the Hebbian/LTP channel — kept
deliberately separate from the static authored `weight`. Edges are created via
`engram_connect(from, to, weight, relation)` (`server.el:253`).
**Relation strings observed:** `associates` (default, `server.el:248`),
`identity`, `co-value`, `birthday-twin`, `canonical-self` (`soul.el:37-108`),
`supersedes`, `tombstones`, `contains`, `tagged` (`neuron-api.el`,
`el_runtime.c:6168`).
## Consciousness layers
Orthogonal to memory tiers, the engram has five canonical **layers**
(`el_runtime.c:5919-5924`):
| id | Name | activation_priority | Role |
|---|---|---|---|
| 0 | SAFETY | 0 (fires earliest) | deepest / limbic |
| 1 | CORE_IDENTITY | — | **default** for all nodes (`ENGRAM_LAYER_DEFAULT`, `:7423`) |
| 2 | DOMAIN | — | domain knowledge |
| 3 | IMPRINT | — | persona overlay |
| 4 | SUIT | — | outermost |
`EngramLayer` (`:6731-6738`) carries `activation_priority` (lower fires first),
`suppressible` (can higher layers suppress it?), `transparent` (invisible to
introspection?), and `injectable` (add/remove at runtime?). Layers are managed
via `engram_add_layer` / `engram_node_layered` / `engram_list_layers`. This is
the identity-vs-domain-knowledge stratification, independent of the tier system
below.
## Two tier systems — do not conflate them
This is the single most important clarification in the data model, and the source
of the vocabulary mismatch flagged throughout this set.
### A. Cognitive memory tiers — the `tier` field
`Working` / `Episodic` / `Semantic` / `Procedural` (and `Canonical` in use).
Runtime default `"Working"` (`el_runtime.c:7408`; `README.md:41-49`). Nodes
**migrate between these by salience decay/reinforcement**, driven by the runtime.
Salience decays as `importance × 1/(1 + days_since) × ln(count + 1)`
(`README.md:57-62`). `memory.el` exposes `tier_working`/`episodic`/`canonical`
helpers (`memory.el:1-3`); `soul.el` writes `Semantic`-tier persona nodes
(`:267`, `:282`). So the live tier set is **{Working, Episodic, Semantic,
Procedural, Canonical}** with continuous salience/importance/confidence floats.
### B. Epistemic tiers & disposition — tags, not runtime concepts
The MCP-facing vocabulary — tiers `note → lesson → canonical`, disposition
`experimental → provisional → stable → deprecated` — is **not enforced anywhere
in `el_runtime.c`.** It is stored as **tags**:
- Knowledge capture preserves the incoming epistemic tier as a `tier:<x>` tag
rather than mapping onto a cognitive tier — deliberately, to avoid a lossy
mapping (`server.el:519-522, 544`).
- `promote_knowledge` writes a canonical node tagged
`["Knowledge","tier:canonical","disposition:stable"]` (`neuron-api.el:533`).
There is **no state machine** validating `experimental → … → deprecated`.
Disposition and epistemic tier are convention-by-tag. *(Flag: not structurally
guarded. The exact MCP-enum → tag/float mapping is not fully traced in the files
read — unverified/TODO.)*
## Write-protection
`is_protected_node(id)` (`neuron-api.el:20-37`) is a **hard-coded allowlist of 15
identity/value node IDs** — the self root, the values hub, intellectual-dna,
memory-philosophy, voice, and the 8 value nodes. Handlers that could mutate the
graph (tombstone / supersede / evolve / connect) check it and return HTTP 403
`api_err_protected` (`:39-41`) for a protected target (checked at `:384, 511,
692, 705, 746, 768`). Edges *into* a protected node are also blocked
(`handle_api_link_entities`).
**The one sanctioned override** is `POST /api/neuron/cultivate`
(`neuron-api.el:781-816`) — it performs the same ops with the protection check
skipped, gated by convention to Will's explicit cultivation sessions. The self
layer is writable, but only through a deliberate door.
## Immutability — tombstone, never delete
Engram nodes are immutable (`memory.el:64-69`). The model is:
- **Tombstone** — `mem_tombstone(node_id)` (`memory.el:46-71`) **keeps the node
and all its edges**, creates a `Tombstone` marker node
(`content = target id`, `label = "tombstone:<id>"`) and wires a `tombstones`
edge (weight 1.0). It never calls `engram_forget`. This is *the* one canonical
delete — every user-facing forget path routes through it. Default bounded reads
hide tombstoned nodes (`memory_hide_tombstoned`, `neuron-api.el:239-249`);
`?include_deleted=1` recovers them.
- **Supersede** — updates/evolves (`neuron-api.el:394-428, 506-541, 715-734`)
create a **new** node with the new content, wire a `supersedes` edge new→old
(weight 0.9, or 0.95 for promote), and **keep the original**. The response
returns both ids so the caller re-points. This is the `supersedes_id`
pattern: new node linked, old preserved, full audit trail.
> **The hole to know about.** The raw runtime `engram_forget` **does** hard-delete
> (frees node + edges, `el_runtime.c:7647`), and the engram HTTP route
> `DELETE /api/nodes/:id` calls it directly (`server.el:322-328`). Immutability
> is therefore an invariant of the **neuron-api / MCP layer routing**, not of the
> store. A client that hits engram HTTP directly can bypass it. *(flag)*
`engram_forget` is also used *internally* for genuine GC: boot-counter pruning
(`memory.el:184`), session-summary/telemetry pruning (`soul.el:369`,
`sessions.el`). Those are bounded housekeeping, not user deletes.
## Persistence, snapshots, backups
- **Storage:** a single JSON snapshot `snapshot.json` under `ENGRAM_DATA_DIR`,
written by `engram_save` / read by `engram_load` (`el_runtime.c:9660+`; format
`{"nodes":[...],"edges":[...]}`). In prod that dir is the RWO PVC mount `/data`
(doc 04).
- **Write policy:** `persist_canonical()` writes the **full** snapshot after every
durable write (`server.el:133-141`). The batch-edge route snapshots **once per
batch** to avoid ~150 GB/day of writes from Hebbian edge churn
(`server.el:258-305`) — this is why `hebb_consolidate` batches (doc 02).
- **Boot safety:** on load, engram writes `snapshot.boot-backup.json` (good load)
or `snapshot.failed-load.json` (a non-empty file that parsed to 0 nodes)
(`server.el:718-734`). Read routes export to scratch paths
(`.scan-export.json`, `.sync-export.json`) and **never** touch the canonical
(`server.el:207-223, 418-437`) — a guard added after a read-route corrupted the
snapshot.
- **Off-cluster backup:** a Kubernetes CronJob (`engram-backup`) tars `/data`
every 15 minutes to `gs://neuron-db-backup/gke/neuron-prod/` and keeps the last
96 (24h) (`infrastructure/platform/k8s/neuron-mcp/backup-cronjob.yaml`).
- **Retention:** InternalStateEvent telemetry pruned at 48h
(`ENGRAM_ISE_RETENTION_MS`, `server.el:485-499`).
> **Data-dir mismatch to flag:** the `server.el` header comment says the default
> is `~/.neuron/engram` (`:16`) but the code defaults to `/tmp/engram`
> (`:135, 717`). Prod overrides both via `ENGRAM_DATA_DIR=/data`. *(unverified —
> which default is intended)*
## The engram HTTP surface (`:8742`)
Dispatcher `handle_request` (`server.el:592-707`). Auth: `ENGRAM_API_KEY`; GETs
always allowed, mutations require `"_auth":"<key>"` in the JSON body
(`server.el:578-588`).
| Endpoint | Purpose |
|---|---|
| `GET /health`, `GET /` | health + live node/edge counts |
| `POST /api/nodes`, `GET /api/nodes`, `GET /api/nodes/:id`, `DELETE /api/nodes/:id` | node CRUD (DELETE = hard `engram_forget`) |
| `GET /api/edges`, `POST /api/edges`, `POST /api/edges/batch`, `GET /api/neighbors/:id?depth` | edge ops + traversal |
| `POST\|GET /api/activate?q&depth`, `POST\|GET /api/search` | spreading activation vs lexical search |
| `POST /api/strengthen` | Hebbian potentiation |
| `POST /api/save`, `/api/load`, `/api/load-merge` | snapshot control |
| `GET /api/sync` | soul daemon periodic pull |
| `GET /api/embed-backfill`, `GET /api/similarity?a&b` | embeddings + cosine |
| `POST /api/neuron/state-events` (auth-exempt), `POST /api/neuron/knowledge/capture` | neuron-layer helpers |
| `GET /api/stats`, `/api/act-stats`, `/api/text-health` | telemetry |
## Retrieval model (summary)
Retrieval is **spreading activation, not query matching**:
`strength = parent_strength × edge_weight × target_salience ×
cosine(query, target)` — multiplicative, top-N, with the two-layer
background → working-memory promotion (`README.md:27-36`; `el_runtime.c:5892+,
6094+`). `mem_recall` / `/api/activate` fire this and mutate WM; `mem_search` /
`/api/search` are passive lexical scans. The cognitive API's `begin_session` and
`compile_ctx` return a **bounded projection** of the activated set, never the raw
graph (doc 02, §2).
@@ -0,0 +1,178 @@
# Neuron — Runtime & Deployment
> Process/port topology, the end-to-end MCP request path, local vs GKE
> blue/green production, and a high-level view of secrets/config. Grounded in
> `entrypoint.sh`, `scripts/blue-green-deploy.sh`, the k8s manifests under
> `infrastructure/platform/k8s/neuron-mcp/`, and `.gitea/workflows/`.
## Process & port topology
A running neuron is **two processes in one container**: the soul and the engram,
started by `entrypoint.sh`.
```
container (one pod)
┌──────────────────────────────────────────────────────────┐
│ entrypoint.sh │
│ 1. start engram (background) ── listens :8742 │
│ 2. wait /health up to 60s │
│ 3. exec soul (PID 1 foreground) ── listens :7770 │
│ │
│ soul :7770 ──HTTP──► engram :8742 │
│ (ENGRAM_URL=http://localhost:8742, HTTP mode) │
│ │
│ /data (PVC mount) ◄── engram snapshot.json │
└──────────────────────────────────────────────────────────┘
```
- `entrypoint.sh` starts engram with `ENGRAM_BIND=:8742` and
`ENGRAM_DATA_DIR=/data`, polls `http://localhost:8742/health` (up to 60s;
Autopilot cold starts are slow), then `exec`s the soul. `SOUL_ENGRAM_PATH` is
deliberately unset so `ENGRAM_URL` triggers **HTTP mode** (soul talks to engram
over localhost HTTP, not an in-process embed).
- EL HTTP runtime is tuned down for co-located calls: `EL_HTTP_TIMEOUT_MS=10000`,
`EL_HTTP_CONNECT_TIMEOUT_MS=3000` (`entrypoint.sh`).
### Full port map
| Port | Process | Role | Source |
|---|---|---|---|
| 7779 | mcp-proxy | MCP client entry; byte-forward + retry | `mcp-proxy/src/main.el` |
| 17779 | mcp-wrapper | MCP JSON-RPC ⇄ soul REST; tool catalog | `mcp-wrapper/src/main.el` |
| 7770 | soul | HTTP cognitive API + `handle_request` | `NEURON_PORT`, `deployment-blue.yaml` |
| 8742 | engram | graph store HTTP | `entrypoint.sh`, `server.el:711` |
| 7771 | neuron-connectd | MCP connector bridges | `routes.el` `connectd_*` |
**Local vs prod, an important distinction.** The proxy → wrapper chain is the
**local developer adapter**: a stdio MCP client (Claude Code) needs to reach an
HTTP soul, so the proxy/wrapper translate and add resilience. In **production**,
the `neuron-mcp` Kubernetes Service is a ClusterIP that targets the soul's
`:7770` directly (`service.yaml`) — external access is "to be wired via
Cloudflare Tunnel later" (annotation, same file). So in prod the MCP/HTTP
boundary is the soul's own HTTP surface; the proxy/wrapper are not (yet) in the
cluster path. *(inference from the ClusterIP-only Service + the local-only
proxy/wrapper binaries.)*
## The MCP request path (end to end)
A single `tools/call` from an MCP client, local topology:
```
client proxy :7779 wrapper :17779 soul :7770 engram :8742
│ JSON-RPC │ │ │ │
│ tools/call ─────────► │ forward+retry │ │ │
│ │ ─────────────────► │ map tool→REST │ │
│ │ │ ─── HTTP POST ────► │ handle_request │
│ │ │ /api/neuron/... │ → handle_api_* │
│ │ │ │ engram_* builtin │
│ │ │ │ ── (HTTP mode) ───► │ activate/search/
│ │ │ │ │ save
│ │ │ │ ◄─── nodes/edges ── │
│ │ │ ◄── JSON result ── │ │
│ │ │ fire_activation │ │
│ │ │ /recall warm-up ─► soul (side effect) │
│ ◄──── result ──────── │ ◄───────────────── │ │ │
```
Responsibilities per hop, and the volatility each isolates (VBD reading):
1. **proxy** — transport resilience. Isolates *client connection volatility*
(drops, retries, health) from everything above. No MCP semantics.
2. **wrapper** — protocol translation. Isolates the *MCP protocol* from the soul:
owns `initialize`/`tools/list`/`tools/call`, the ~90-tool catalog, and
`dispatch_tool_call`. Also fires the `fire_activation` `/recall` side effect so
tool use warms working memory.
3. **soul** — cognition. `handle_request` dispatch → `handle_api_*` → engram
builtins. In HTTP mode it reaches engram over localhost; otherwise embedded.
4. **engram** — the graph. Spreading activation, Hebbian edges, snapshot
persistence.
For the user-facing chat pipeline (not tool calls), `/api/chat` enters
`layered_cycle` (soul.el) — L1 safety → L2 stewardship → L3 imprint — described
in `02-components.md §3c`.
## Production: GKE blue/green
Neuron prod runs on GKE cluster **`neuron-platform`** (Autopilot, us-central1),
namespace **`neuron-prod`**. Two Deployments, `neuron-mcp-blue` and
`neuron-mcp-green`, share one Service selector that names the *active slot*.
- **Deployments** (`deployment-blue.yaml` / `deployment-green.yaml`): one
container `soul`, image pinned by **digest** (not `:latest`) so Argo CD can't
drift the active slot to an untested build (see the pin comment in
`deployment-blue.yaml`). `strategy: Recreate` — the PVC is RWO so only one pod
can hold it at a time. Probes hit `/health` on `:7770`.
- **Service** (`service.yaml`): ClusterIP `neuron-mcp`, port 7770 → 7770,
`selector: {app: neuron-mcp, slot: blue}`. The blue/green script patches
`slot`.
- **Storage** (`pvc.yaml`): `neuron-engram-data`, `standard-rwo` (pd-balanced),
10Gi, RWO. Engram data is the single `snapshot.json` (~8MB active).
- **The swap** (`scripts/blue-green-deploy.sh`): (1) set image on the target
slot; (2) scale target to 1, wait for rollout; (3) **patch the Service selector
to the new slot** (traffic flip); (4) scale the old slot to 0. Imperative
`kubectl` for the live swap, then git-update the Argo manifests so a sync
doesn't revert replica counts.
- **Backup** (`backup-cronjob.yaml`): every 15 min, tar `/data` → GCS, keep 96.
### Resource sizing (learned the hard way)
`deployment-blue.yaml` documents the memory history in comments: idle soul RSS
~860Mi; the `beginSession` call (loads memories + backlog + preferences) spikes
past 1Gi and OOM-killed the pod mid-request (client socket closed). Current
setting: `requests = limits = 2Gi`, cpu 250m/1000m. This is *why* the cognitive
API projects/compacts payloads so aggressively (doc 02 §2, doc 01 axis 1) — the
memory ceiling is real and close.
## CI/CD
Two Gitea Actions workflows (`.gitea/workflows/`), serialized on a single GCE
runner (`concurrency: neuron-runner`).
- **`ci.yaml`** (push/PR to `main`):
- **build:** free disk → checkout → install gcc/libcurl/gcloud → download
`el-runtime-c`/`el-runtime-h` from Artifact Registry `foundation-prod`
(`elc`/`elb` intentionally **not** downloaded) → compile the committed
`dist/soul.c` directly: `cc -O2 -DHAVE_CURL dist/soul.c el_runtime.c -lssl
-lcrypto -lcurl -lpthread -lm -o dist/neuron``strip -s` → smoke test
`dist/neuron --help` → publish `neuron-soul@<sha8>` to AR (push only).
- **deploy** (push-to-main only): auth GCP → `get-credentials neuron-platform`
**determine idle slot** (the deployment at 0 replicas) → prepare artifacts
(soul binary + `elc` + runtime for the Docker build) → **clone the engram
repo** into `./engram/` (Dockerfile builds engram from source) → `docker
build`+push `neuron-soul:<sha>``scripts/blue-green-deploy.sh --image
--slot` → git-push updated infra manifests → `kubectl rollout status`
verify `neuron-mcp` endpoints.
- **`deploy-gke.yaml`** (`workflow_dispatch` only, slot default `green`) — manual
rollback / forced-slot deploy without a rebuild; same auth → slot → docker →
blue-green → manifest-sync → verify steps.
The Docker image (`Dockerfile`) is a two-stage build: stage 1 compiles
`engram/src/server.el``engram.c``engram` binary via `elc` + `cc`; stage 2
is an Ubuntu 24.04 runtime (GLIBC 2.39 satisfies both binaries) with `soul` +
`engram` + `entrypoint.sh`.
## Config & secrets (high level)
Runtime configuration is injected as environment, sourced from a Kubernetes
Secret `neuron-soul-secrets` via ExternalSecret (ESO → GCP Secret Manager,
Workload Identity — no key files). From `deployment-blue.yaml`:
| Env | Meaning |
|---|---|
| `NEURON_PORT` | soul HTTP port (7770) |
| `NEURON_LLM_0_URL` / `_KEY` / `_FORMAT` | primary LLM endpoint (Anthropic format) |
| `SOUL_CGI_ID` / `SOUL_IDENTITY` | CGI id + identity seed (→ `seed_persona_from_env`, `soul.el:250`) |
| `NEURON_TOKEN` | auth token *(present in env; note the HTTP dispatch does not currently check it — doc 01 Divergence 3)* |
| `NEURON_API_URL` | self-callback URL (`http://neuron-mcp.neuron-prod.svc.cluster.local:7770`) |
| `ENGRAM_URL` / `ENGRAM_DATA_DIR` | `http://localhost:8742` / `/data` |
There is also an in-graph config surface: `ConfigEntry` nodes read/written by
`inspect_config` / `tune_config` (`neuron-api.el:616-653`) — runtime-tunable
persona/behavior keys stored *in* the engram rather than the environment.
> **Operational note to flag.** The `deployment-blue.yaml` image pin comment
> (dated Jul 2026) records that `:latest` resolved to an untested build lacking a
> `mem_save`/genesis-SIGSEGV fix, which is why the active slot is pinned to a
> digest. Any promotion must (a) rebuild a good soul and (b) update the digest in
> git so Argo CD and `blue-green-deploy.sh` agree. *(state as-of the manifests
> read; verify current slot before deploying.)*
+165
View File
@@ -0,0 +1,165 @@
# Neuron — El & the Build Pipeline
> The soul and the engram are written in **El**, a self-hosted language that
> compiles to C11. This document covers the language layer, the
> amalgamation → `soul.c` → binary pipeline, how the soul is composed from its
> layers, and the compile-time capability gates. Sources: `manifest.el`,
> `soul.el`, `dist/soul.c`, the El toolchain under `foundation/el/`
> (`elc.c`, `elb.el`, `BOOTSTRAP.md`), and `.gitea/workflows/`.
## The El language layer
El is a compiled, Lisp-family language transpiled to C11. Every El program links
a shared runtime, `el_runtime.c` / `el_runtime.h`, which implements **all
builtins**: the engram graph engine (`engram_*`), HTTP (`http_*`), JSON
(`json_*`), crypto, time, LLM calls, and DHARMA primitives (`el_runtime.h`,
`BOOTSTRAP.md:599-644`). The runtime also provides an arena allocator (server
mode) and ARC refcounting. Practically: **the runtime is both the standard
library and the database** — the graph physically lives in `el_runtime.c`, and El
source files are the orchestration/logic on top.
A recurring texture in the source is workaround comments for codegen quirks
(e.g. broken `%`/`*` operators). These are El-compiler maturity issues, not
architecture — but they explain some of the hand-rolled arithmetic in
`awareness.el`/`memory.el`.
## The toolchain: `elc`, `elb`, `el_runtime`
| Tool | What it is | Role |
|---|---|---|
| `elc` | the El compiler, **self-hosted** (written in El) | compiles one El translation unit → C11. Import resolution is textual, depth-first, dedup'd — it inlines all imports into one string and emits forward decls for every fn (`BOOTSTRAP.md:927-936`). |
| `elb` | the build coordinator (`elb.el`, ~367 lines) | reads `manifest.el`, walks the import graph, does **incremental** separate compilation using `.elh` header files (`extern fn` decls), links the final binary (".NET-style incremental build", `BOOTSTRAP.md:886, 916-925`). |
| `el_runtime.c/.h` | the C runtime | linked by every compiled El binary; implements all builtins and the graph engine. |
The `.elh` files present in this repo (`soul.elh`, `memory.elh`,
`neuron-api.elh`, `routes.elh`, …) are **auto-generated headers** (`elc
--emit-header`) — the `extern fn` interface each module exports. They are the
contract surface `elb` uses for incremental builds, and they double as a concise
map of each module's public functions.
### Self-hosting fixed point
`elc` is bootstrapped from a seed binary (`dist/platform/elc`, Mach-O arm64) and
verified by a **fixed-point self-recompile**: the compiler must compile its own
source to a byte-identical binary (`BOOTSTRAP.md:7-58, 801-816`). Pipeline:
`elc-cli.el → compiler.el → lexer/parser/codegen.el`.
## Building the soul: `.el → elc → .c → cc → binary`
The concrete pipeline (mirrored in the engram build, `engram/src/server.el:8-11`):
```
soul.el (+ imports)
│ elc (self-hosted El→C11, inlines imports)
dist/soul.c (~31,300 lines — single amalgamated translation unit)
│ cc -std=c11 -O2 soul.c el_runtime.c
dist/neuron (native binary)
```
### Why `dist/soul.c` is committed
`dist/soul.c` is the authoritative combined translation unit, **regenerated on
macOS by running `elb`**. It is checked into the repo on purpose: CI compiles it
**directly** and skips `elb` entirely (`ci.yaml`). The reason is operational, not
aesthetic —
- `elb` succeeds on arm64/macOS `ld`, but **fails on Linux** (duplicate strong
symbols), and
- `elc` uses 24GB+ virtual memory, which **OOM-kills the 16GB CI runner**.
So the pattern is: **compile on the Mac, commit the amalgamation, and let Linux
CI do only the cheap `cc` step.** `dist/` also holds the per-module `.c` outputs
(`memory.c`, `awareness.c`, `chat.c`, the NLG morphology tables, …) —
intermediate artifacts of the same process.
> **Mechanism note (observed during the self-load regen).** The single-TU
> `dist/soul.c` is produced by running `elc` over the **flattened import set** —
> every module source in `soul.el`'s transitive import graph, concatenated with
> `import` lines stripped, compiled in one pass (`elc` hoists forward decls for
> all functions, so concat order doesn't affect correctness). `elb` on its own
> emits **per-module `.c` + a linked binary**, not the combined `soul.c`; it is
> the separate-compilation coordinator, and `elc soul.el` alone yields only the
> soul module. Because the amalgamation is regenerated only on demand, it can lag
> the `.el` sources: this PR regenerated it after it had fallen behind several
> source commits, and folded in the `inspect_graph` relevance-ranked projection
> (the `compact=1` self-load fix, doc 02) so CI ships it.
## How the soul is composed (layer stack)
`manifest.el` declares the build:
```
package "neuron" { version "0.1.0" edition "2026" }
build { entry "soul.el" }
```
The comment in `manifest.el:8-16` documents the intended **layer composition
order**: a base layer `../foundation/nlg` (the NLG engine — 31-language
morphology, grammar, realizer, semantics) with the **soul layer** (`soul.el`)
injected on top. New layers are added by importing them in `soul.el` before the
soul's own code. *(The `../foundation/nlg` path is the manifest's stated NLG base;
the NLG sources compile into the `dist/*.c` morphology/grammar tables seen in the
tree.)*
`soul.el` itself imports, in order (`soul.el:1-10`): `elp.el`, `memory.el`,
`safety.el`, `stewardship.el`, `imprint.el`, `awareness.el`, `chat.el`,
`studio.el`, `elp-input.el`, `routes.el` — then declares the `cgi "neuron-soul"`
identity block (`:12-17`): `dharma_id`, `principal`, `network`, and
`engram: http://localhost:8742`. Because `elc` inlines imports depth-first, this
import list *is* the amalgamation order that produces `dist/soul.c`.
The `cgi` block is not just metadata — it sets the program's **capability tier**
(next section).
## Compile-time capability gates
El's codegen classifies each program by its top-level declaration and **enforces
capabilities at compile time** (`BOOTSTRAP.md:958-965`):
| Declaration | Tier | Allowed |
|---|---|---|
| `cgi { … }` | full | everything — `llm_call_agentic`, `llm_register_tool`, `dharma_emit`, `dharma_field`, LLM, DHARMA |
| `service { … }` | restricted | no `llm_call_agentic` / `llm_register_tool` / `dharma_emit` / `dharma_field` |
| neither | utility | no DHARMA, no LLM |
A program that calls a capability its tier forbids **fails to compile**: codegen
emits a C `#error` naming the forbidding call, so the downstream `cc` aborts.
This is the **primary hard gate** in the build — capability escalation is caught
by the compiler, not at runtime. The soul is a `cgi`, so it gets the full tier;
`engram` is declared without `cgi`/`service` semantics that would grant LLM
access (it is a store).
## Verification gates
| Gate | Where | What it checks |
|---|---|---|
| Capability tier | El codegen (`BOOTSTRAP.md:958`) | no capability escalation; hard `#error` at compile |
| Self-hosting fixed point | `elc` bootstrap (`BOOTSTRAP.md:801`) | compiler reproduces itself byte-identically |
| `test_soul_guard.el` | `tests/` | the genesis `safe_to_seed` boot guard — a sparse/oversized snapshot must not clobber the graph |
| `test_layer_contract.el` | `tests/` | JSON interface shapes between composition-stack layers that `layered_cycle` depends on (e.g. `safety_screen` always returns an `action` field) |
| other `tests/*.el` | `tests/` | `test_sessions.el`, `test_safety.el`, `test_bell_safety.el`, `test_layered_cycle.el`, `test_imprint.el`, `test_stewardship.el`, `test_api_define_process.el`, … |
| CI smoke test | `ci.yaml` | `dist/neuron --help` runs |
> **Flag (unverified/TODO).** CI (`ci.yaml`) runs only the `cc` compile + the
> `dist/neuron --help` smoke test — it does **not** invoke the `tests/*.el`
> soul-guard / layer-contract suites, and `.githooks/` is empty. Whether these
> tests are gated anywhere (a pre-merge hook, a separate workflow, or manual
> discipline on the Mac before regenerating `soul.c`) is **not evident in the
> files read**. This is the most important build-integrity gap to confirm with a
> human: the contract tests exist but their enforcement point is unproven.
## Practical consequences for a contributor
- **You cannot rebuild the whole soul on Linux/CI.** Regenerate `dist/soul.c` on
a Mac (`elb`), commit it, then CI compiles it. Changing an `.el` file without
regenerating `soul.c` ships nothing.
- **The `.elh` files are your API map.** To see what a module exposes, read its
`.elh` — it's the generated `extern fn` list.
- **Memory/activation behavior often can't be changed from this repo.** The
volatile numeric core is in `foundation/el` `el_runtime.c`. Doc 01, Divergence
6 explains why this is the sharpest edge in the architecture.
- **The engram is a separate repo.** It is cloned and compiled by CI
(`Dockerfile`, `.gitea/workflows/`), not vendored here. Its source of truth is
`foundation/el/engram`.
+9 -2
View File
@@ -302,7 +302,11 @@ fn fetch_by_id(args: String) -> String {
if str_eq(id, "") {
return mcp_text_result("error: id is required")
}
let resp: String = http_get(neuron_url() + "/graph?id=" + id + "&depth=0")
// NB: the soul's engram_neighbors_json coerces depth<=0 to depth=1, so this
// "single node fetch" actually pulls the full 1-hop neighborhood. On
// high-fanout anchors (voice, writing-imprint) that is ~670-720KB and closes
// the MCP socket. compact=1 bounds it identically to inspectGraph.
let resp: String = http_get(neuron_url() + "/graph?id=" + id + "&depth=0&compact=1")
return mcp_json_result(resp)
}
@@ -516,7 +520,10 @@ fn tool_inspect_graph(args: String) -> String {
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))
// compact=1: soul returns a bounded, relevance-ranked neighborhood (top-K
// with content, the rest as pointers) so high-fanout nodes (voice,
// writing-imprint) no longer overflow the MCP transport and close the socket.
let resp: String = http_get(neuron_url() + "/graph?id=" + resolved_id + "&depth=" + int_to_str(depth) + "&compact=1")
return mcp_json_result(resp)
}
+131
View File
@@ -188,6 +188,125 @@ fn api_compact_activated(raw: String, max_items: Int, snip: Int) -> String {
return out + "]"
}
// api_float_or parse a numeric JSON field of `obj` as Float, or `dflt` when
// the field is absent. Backs neighbor relevance scoring.
fn api_float_or(obj: String, key: String, dflt: Float) -> Float {
let v: String = json_get_raw(obj, key)
if str_eq(v, "") { return dflt }
return str_to_float(v)
}
// api_neigh_better strict relevance ordering of two neighbor elements
// {node,edge,hops}. Lexicographic and comparison-ONLY (no arithmetic): El's `+`
// operator is overloaded to string concatenation, so float scoring like
// weight*salience mis-compiles; ordering by `>`/`<` (always numeric on the
// int64 el_val_t, correct for the non-negative fields here) is safe. Keys, in
// order: fewer hops (closer), stronger edge weight, higher node salience, higher
// node importance. Returns true iff `a` ranks strictly ahead of `b`.
fn api_neigh_better(a: String, b: String) -> Bool {
let na: String = json_get_raw(a, "node")
let nb: String = json_get_raw(b, "node")
let ea: String = json_get_raw(a, "edge")
let eb: String = json_get_raw(b, "edge")
let ha: Float = api_float_or(a, "hops", 1.0)
let hb: Float = api_float_or(b, "hops", 1.0)
if ha < hb { return true }
if hb < ha { return false }
let wa: Float = api_float_or(ea, "weight", 0.0)
let wb: Float = api_float_or(eb, "weight", 0.0)
if wa > wb { return true }
if wb > wa { return false }
let sa: Float = api_float_or(na, "salience", 0.0)
let sb: Float = api_float_or(nb, "salience", 0.0)
if sa > sb { return true }
if sb > sa { return false }
let ia: Float = api_float_or(na, "importance", 0.0)
let ib: Float = api_float_or(nb, "importance", 0.0)
if ia > ib { return true }
return false
}
// api_neigh_rank count of elements that outrank element `i` under the
// api_neigh_better ordering, with array index as the final tiebreak. Element i
// belongs to the content tier iff rank < k. O(n) per element (n bounded ~90
// neighbors), so O(n^2) overall acceptable for a bounded neighborhood.
fn api_neigh_rank(raw: String, n: Int, i: Int) -> Int {
let el_i: String = json_array_get(raw, i)
let better: Int = 0
let j: Int = 0
while j < n {
let el_j: String = json_array_get(raw, j)
let j_better: Bool = api_neigh_better(el_j, el_i)
let i_better: Bool = api_neigh_better(el_i, el_j)
let eq: Bool = !j_better && !i_better
let wins: Bool = j_better || (eq && j < i)
let better = if wins { better + 1 } else { better }
let j = j + 1
}
return better
}
// api_neigh_full top-tier neighbor: the node compacted to a bounded content
// snippet, the full edge raw preserved (guard empty -> null), hops, pointer:false.
fn api_neigh_full(node: String, edge: String, el: String, snip: Int) -> String {
let e: String = if str_eq(edge, "") { "null" } else { edge }
return "{\"node\":" + api_compact_node(node, snip)
+ ",\"edge\":" + e
+ ",\"hops\":" + api_num_or_zero(el, "hops")
+ ",\"pointer\":false}"
}
// api_neigh_pointer tail neighbor: a lightweight, addressable POINTER with NO
// content. Just enough identity (id/label/node_type/tier) to dereference on
// demand, plus edge relation+weight and hops. This is what keeps the payload
// bounded on high-fanout nodes.
fn api_neigh_pointer(node: String, edge: String, el: String) -> String {
let id: String = json_get(node, "id")
let label: String = json_get(node, "label")
let ntype: String = json_get(node, "node_type")
let tier: String = json_get(node, "tier")
let relation: String = json_get(edge, "relation")
return "{\"node\":{\"id\":\"" + api_json_escape(id) + "\""
+ ",\"label\":\"" + api_json_escape(label) + "\""
+ ",\"node_type\":\"" + api_json_escape(ntype) + "\""
+ ",\"tier\":\"" + api_json_escape(tier) + "\"}"
+ ",\"edge\":{\"relation\":\"" + api_json_escape(relation) + "\""
+ ",\"weight\":" + api_num_or_zero(edge, "weight") + "}"
+ ",\"hops\":" + api_num_or_zero(el, "hops")
+ ",\"pointer\":true}"
}
// api_compact_neighbors bounded projection of an engram neighbor array
// [{node,edge,hops},...]. Relevance-ranks neighbors (via api_neigh_rank /
// api_neigh_better): the top `k_content` are emitted WITH a content snippet; every other neighbor is
// emitted as a lightweight POINTER (no content) the caller dereferences on
// demand. Every element is emitted (as full or pointer), so total fan-out COUNT
// stays visible. Mirrors api_compact_activated but adds the ranking + the
// content/pointer split, keeping high-fanout identity nodes (voice,
// writing-imprint) well under the transport socket-close threshold. Returns a
// valid JSON array.
fn api_compact_neighbors(raw: String, k_content: Int, snip: Int) -> String {
if !api_nonempty(raw) { return "[]" }
let n: Int = json_array_len(raw)
let out: String = "["
let i: Int = 0
while i < n {
let el: String = json_array_get(raw, i)
let node: String = json_get_raw(el, "node")
let edge: String = json_get_raw(el, "edge")
let rank: Int = api_neigh_rank(raw, n, i)
let sep: String = if i == 0 { "" } else { "," }
let elem: String = if rank < k_content {
api_neigh_full(node, edge, el, snip)
} else {
api_neigh_pointer(node, edge, el)
}
let out = out + sep + elem
let i = i + 1
}
return out + "]"
}
// api_persisted read-back-after-write guard against hallucinated saves.
// After a write builtin returns an id, confirm the node is actually queryable
// via engram_get_node_json(id) (returns "" or "null" when missing). Returns
@@ -678,6 +797,18 @@ fn handle_api_inspect_graph(method: String, path: String, body: String) -> Strin
return api_err("entity_id or name required. Known names: self, neuron, values, values_hub")
}
let results: String = engram_neighbors_json(resolved, depth, "both")
// Optional bounded projection. `compact=1` relevance-ranks the neighborhood
// (top-K get content snippets, the rest become lightweight pointers) so the
// MCP transport never socket-closes on high-fanout identity anchors (voice,
// writing-imprint). Absent the flag the studio app's calls are UNCHANGED.
let compact: String = if str_eq(method, "GET") { api_query_param(path, "compact") } else { json_get(body, "compact") }
if str_eq(compact, "1") || str_eq(compact, "true") {
let snip_q: Int = api_query_int(path, "snip", 0)
let snip: Int = if snip_q == 0 { 600 } else { snip_q }
let k_q: Int = api_query_int(path, "k", 0)
let k: Int = if k_q == 0 { 12 } else { k_q }
return api_or_empty(api_compact_neighbors(results, k, snip))
}
return api_or_empty(results)
}
+11
View File
@@ -8,6 +8,17 @@ extern fn api_ok(extra: String) -> String
extern fn api_err(msg: String) -> String
extern fn api_nonempty(s: String) -> Bool
extern fn api_or_empty(s: String) -> String
extern fn api_num_or_zero(obj: String, key: String) -> String
extern fn api_utf8_trunc(s: String, n: Int) -> String
extern fn api_compact_node(node: String, snip: Int) -> String
extern fn api_compact_node_array(raw: String, max_items: Int, snip: Int) -> String
extern fn api_compact_activated(raw: String, max_items: Int, snip: Int) -> String
extern fn api_float_or(obj: String, key: String, dflt: Float) -> Float
extern fn api_neigh_better(a: String, b: String) -> Bool
extern fn api_neigh_rank(raw: String, n: Int, i: Int) -> Int
extern fn api_neigh_full(node: String, edge: String, el: String, snip: Int) -> String
extern fn api_neigh_pointer(node: String, edge: String, el: String) -> String
extern fn api_compact_neighbors(raw: String, k_content: Int, snip: Int) -> String
extern fn api_persisted(id: String) -> Bool
extern fn api_not_persisted(id: String) -> String
extern fn tombstone_node(id: String) -> String