feat(memory): clean-room knowledge-graph MCP connector for SCORPIOX BOT nodes
The first OSS plugin to implement the connector extension of the plugin_<name> spec: one static C99 binary, five modes. --meta / SX_PLUGIN_META=1 discovery JSON carrying kind/mcp/daemon/ menus/verified, unauthenticated so /plugins and the router can probe it --mcp MCP JSON-RPC 2.0 over stdio - initialize, tools/list, tools/call, resources/list, resources/read, ping. Reached by agents through the single sx-connector-mcp router, so clang's MAX_SERVERS 16 is untouched and nine more tools never sit in the prompt. ?action= / POST the JSON node API, the same nine operations GET the graph browser page (search, type chips, inspector, add/link/delete, export) --version / --help / --schema Nine tools with the upstream reference server's names, schemas and error sentences, so a prompt or allowlist written for it works unchanged: create_entities, add_observations, delete_entities, create_relations, delete_relations, delete_observations, read_graph, search_nodes, open_nodes. A tool failure is a result with isError:true and the reason in content[0].text - never a JSON-RPC error - so the agent can read it and correct itself. Storage is one JSONL file in this connector's own data directory (~/.scorpiox/connectors/plugin_memory, /workspace/... when it exists, %LOCALAPPDATA%\scorpiox\connectors\... on Windows, $MEMORY_FILE_PATH to override). Saves stage to <path>.tmp.<pid>, fsync, chmod, rename, so a kill mid-write cannot truncate the graph; lines the loader cannot parse are carried through and written back byte for byte rather than dropped. Zero dependencies, zero network: no popen, system, exec, socket or curl anywhere in src/, asserted against the source by the suite. yyjson 0.12.0 is vendored and compiled in, so all six dist targets are standalone. tests/run.sh - 184 offline assertions, 0 failed: --meta field for field, a real JSON-RPC session across all nine tools, the skip/dedupe/not-found semantics, observationLimit 0 versus absent, the either-endpoint relation rule, cross-process persistence, verbatim survival of a malformed line, the auth matrix, every HTTP action's shape, source guards, and the same source under ASan + UBSan + _FORTIFY_SOURCE=2. tests/e2e.py drives the page in Chromium at 1440/1024/390 in both themes (102 checks, 0 failed) and writes docs/ui-*.png.
AuthorPico <picobot@scorpioplayer.com>
Date2026-11-13 20:50:31
Commit97832b99
Changed files
.gitignore+19−0■■■■■
LICENSE+21−0■■■■■
Makefile+93−0■■■■■
README.md+239−0■■■■■
build.ps1+66−0■■■■■
docs/usage.md+123−0■■■■■
plugin.json+20−0■■■■■
release-dist.sh+383−0■■■■■
src/api.c+844−0■■■■■
src/bot_theme_plugin.h+129−0■■■■■
src/graph.c+942−0■■■■■
src/memory.h+185−0■■■■■
src/plugin_memory.c+402−0■■■■■
src/tools.c+1127−0■■■■■
src/ui.html+384−0■■■■■
src/ui_html.h+392−0■■■■■
tests/e2e.py+304−0■■■■■
tests/run.sh+706−0■■■■■
tools/gen_ui.py+105−0■■■■■
vendor/yyjson-LICENSE.txt+21−0■■■■■
vendor/yyjson.c+11224−0■■■■■
vendor/yyjson.h+8332−0■■■■■
28 files+26061−0
Diff
Diff truncated at 200 KB
.gitignore+19−0■■■■■
11new file mode 100644
index 0000000..f373ac1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,19 @@
1+# build artifacts
2+plugin_memory
3+plugin_memory.exe
4+plugin_memory.musl
5+plugin_memory.arm64
6+plugin_memory.macos-arm64
7+plugin_memory.macos-x86_64
8+plugin_memory.asan
9+bin/
10+
11+# local graph stores (never commit anyone's memory)
12+.memory-store/
13+*.jsonl
14+*.jsonl.tmp.*
15+*.jsonl.lock
16+
17+# python tooling
18+__pycache__/
19+*.pyc
LICENSE+21−0■■■■■
11new file mode 100644
index 0000000..ef80120
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+93−0■■■■■
11new file mode 100644
index 0000000..19138f2
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,93 @@
1+# plugin_memory - SCORPIOX BOT open-source knowledge-graph memory connector
2+#
3+# Targets:
4+# make native build -> ./plugin_memory
5+# make musl static musl x86_64 -> ./plugin_memory.musl
6+# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_memory.arm64
7+# make win64 MinGW-w64 static -> ./plugin_memory.exe
8+# make macos Apple clang -> ./plugin_memory (run this on macOS)
9+# make ui regenerate src/ui_html.h from src/ui.html
10+# make asan ASan/UBSan + _FORTIFY_SOURCE=2 build -> ./plugin_memory.asan
11+# make test build + run tests/run.sh
12+# make e2e build + run tests/e2e.py (Playwright)
13+# make clean
14+#
15+# The binary is four translation units plus the vendored yyjson amalgamation:
16+# src/plugin_memory.c entry, --meta, the --mcp JSON-RPC loop
17+# src/graph.c JSONL storage, atomic save, the store, shared helpers
18+# src/tools.c the nine tools, shared by --mcp and the HTTP API
19+# src/api.c the CGI JSON actions and the HTML page
20+# vendor/yyjson.c vendored JSON parser/writer (zero runtime deps)
21+
22+CC ?= cc
23+SRCS := src/plugin_memory.c src/graph.c src/tools.c src/api.c vendor/yyjson.c
24+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -I vendor
25+MUSL_CC ?= musl-gcc
26+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor -static
27+ARM_CC ?= aarch64-linux-gnu-gcc
28+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor -static
29+WIN_CC ?= x86_64-w64-mingw32-gcc
30+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor -static
31+UI_SRC := src/ui.html
32+UI_HDR := src/ui_html.h
33+BIN := plugin_memory
34+EXE := plugin_memory.exe
35+
36+.PHONY: all native musl arm64 win64 macos ui asan test e2e clean help
37+
38+all: native
39+
40+$(UI_HDR): $(UI_SRC) tools/gen_ui.py
41+ @echo "==> regenerating $(UI_HDR)"
42+ python3 tools/gen_ui.py
43+
44+ui: $(UI_HDR)
45+
46+native: $(BIN)
47+
48+$(BIN): $(SRCS) $(UI_HDR)
49+ @echo "==> native build ($(CC))"
50+ $(CC) $(CFLAGS) -o $(BIN) $(SRCS)
51+
52+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
53+musl: $(SRCS) $(UI_HDR)
54+ @echo "==> static musl build ($(MUSL_CC))"
55+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRCS)
56+
57+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
58+arm64: $(SRCS) $(UI_HDR)
59+ @echo "==> static arm64 build ($(ARM_CC))"
60+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRCS)
61+
62+# Native Win64 static PE - runs on any Windows 10/11 x64 node
63+win64: $(SRCS) $(UI_HDR)
64+ @echo "==> MinGW-w64 build ($(WIN_CC))"
65+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRCS)
66+
67+# Apple clang build (run this on macOS)
68+macos: $(SRCS) $(UI_HDR)
69+ @echo "==> Apple clang build"
70+ $(CC) $(CFLAGS) -o $(BIN) $(SRCS)
71+
72+# Address/undefined sanitizers plus fortify. This is the build that finds the
73+# overlap, use-after-free and truncation bugs the -O2 suite cannot see, so it
74+# runs in tests/run.sh, not just by hand.
75+asan: $(SRCS) $(UI_HDR)
76+ @echo "==> sanitizer build"
77+ $(CC) -O1 -g -std=c99 -Wall -Wextra -I src -I vendor \
78+ -fsanitize=address,undefined -fno-omit-frame-pointer \
79+ -D_FORTIFY_SOURCE=2 -o $(BIN).asan $(SRCS)
80+
81+test: native
82+ @sh tests/run.sh
83+
84+e2e: native
85+ @python3 tests/e2e.py
86+
87+clean:
88+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 \
89+ $(BIN).macos-x86_64 $(BIN).asan
90+ rm -rf bin
91+
92+help:
93+ @echo "make | make musl | make arm64 | make win64 | make macos | make ui | make asan | make test | make e2e | make clean"
README.md+239−0■■■■■
11new file mode 100644
index 0000000..4672168
--- /dev/null
+++ b/README.md
@@ -0,0 +1,239 @@
1+# SCORPIOX BOT — memory
2+
3+A **persistent knowledge graph** your agents can write to and read back, living on
4+your **own node**.
5+
6+This is the standard MCP memory server, rebuilt as one static C99 binary. Entities
7+carry observations, typed relations link them, and the same nine tools an agent
8+sees over stdio back a browser UI for searching, inspecting and editing the graph.
9+The whole graph is a single JSONL file in this connector's own data directory.
10+No account, no database, no CDN, **no network request of any kind** — the binary
11+opens no socket and runs no other program.
12+
13+```
14+make # native build -> ./plugin_memory
15+make musl # static musl x86_64 -> ./plugin_memory.musl
16+make arm64 # static aarch64 -> ./plugin_memory.arm64
17+make win64 # MinGW-w64 static PE -> ./plugin_memory.exe
18+make macos # Apple clang (on macOS) -> ./plugin_memory
19+make ui # regenerate src/ui_html.h from src/ui.html
20+make test # offline suite (180+ assertions)
21+make e2e # Playwright viewport suite (1440 / 1024 / 390, dark + light)
22+```
23+
24+## Install
25+
26+Drop the binary where the node looks for plugins, then open
27+**Settings → Plugins**, or use the market installer:
28+
29+```sh
30+# node plugin directory (created by scorpiox-bot on startup)
31+cp plugin_memory ~/.scorpiox/plugins/plugin_memory
32+chmod +x ~/.scorpiox/plugins/plugin_memory
33+
34+# or from the market
35+curl -s -H "X-Bot-Password: $BOT_PASSWORD" \
36+ "http://127.0.0.1:8150/plugin_manage?action=install&slug=memory&mode=prebuilt"
37+```
38+
39+Windows: `%LOCALAPPDATA%\scorpiox\plugins\plugin_memory.exe`.
40+BotCloud container: `/workspace/.scorpiox/plugins/plugin_memory`.
41+
42+## Five modes, one binary
43+
44+| Mode | Trigger | Response |
45+|---|---|---|
46+| Discovery | `--meta` or `SX_PLUGIN_META=1` | `{"name":"memory","desc":"Knowledge graph","kind":"mcp","mcp":true,"daemon":false,"menus":false,"verified":"live","category":"devtools","version":"1.0.0"}` (unauthenticated) |
47+| **MCP tool provider** | `--mcp` | newline-delimited **JSON-RPC 2.0 over stdio** — `initialize`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `ping` |
48+| API | `?action=...`, `?format=json`, or any `POST` | `application/json; charset=utf-8` |
49+| UI | plain `GET` (`?embed=1` aware) | the graph browser, `text/html` |
50+| Info | `--version`, `--help`, `--schema` | id + version, usage, the nine tool schemas |
51+
52+Modes 3 and 4 sit behind `require_node_auth()`: `X-Bot-Password`,
53+`Authorization: Bearer <pwd>`, or `?pwd=`. With `BOT_PASSWORD` unset the check
54+is a no-op, which is the intended behaviour on a single-user box. `--meta` and
55+`--mcp` stay open — the node spawns the stdio server itself, so a CGI password
56+must not stop it, or the router could never reach an installed connector.
57+
58+### Why `--mcp` and not an MCP server entry
59+
60+`plugin_memory` is a **connector plugin**, not a new MCP server. `scorpiox-bot-api`
61+ships one lightweight stdio router, `sx-connector-mcp`, registered as a *single*
62+MCP server; it reads `mcp_plugins.json` and dispatches into every installed
63+`mcp:true` plugin. That keeps `clang`'s `MAX_SERVERS 16` untouched and adds zero
64+prompt bloat no matter how many connectors are installed:
65+
66+```sh
67+# what the router sees
68+sx-connector-mcp --list # memory kind mcp 9 tools
69+sx-connector-mcp --tools memory
70+sx-connector-mcp --call memory create_entities \
71+ '{"entities":[{"name":"Earl Grey","entityType":"tea","observations":["bergamot"]}]}'
72+sx-connector-mcp --call memory read_graph '{}'
73+```
74+
75+## The nine tools
76+
77+Names, schemas and error texts match the upstream reference server, so a prompt or
78+tool-allowlist written for it works unchanged.
79+
80+| Tool | Arguments | Notes |
81+|---|---|---|
82+| `create_entities` | `{entities:[{name,entityType,observations[]}]}` | a name already present, or repeating earlier in the same call, is **skipped** and listed in `skipped`; its observations are **not** added — use `add_observations` |
83+| `add_observations` | `{observations:[{entityName,contents[]}]}` | one unknown entity fails the whole call; repeats inside the call and against the graph are dropped |
84+| `delete_entities` | `{entityNames[]}` | cascades every relation touching them; reports `Deleted N of M entities. Not found: …` |
85+| `create_relations` | `{relations:[{from,to,relationType}]}` | both ends must exist (`Entity with name X not found`); the exact triple is never stored twice |
86+| `delete_relations` | `{relations:[{from,to,relationType}]}` | exact-triple match; entities are kept |
87+| `delete_observations` | `{deletions:[{entityName,observations[]}]}` | exact-text match |
88+| `read_graph` | `{entityTypes?, observationLimit?}` | `observationLimit: 0` returns counts only (`observationCount`) — *absent* returns full text |
89+| `search_nodes` | `{query, limit?, observationLimit?}` | case-insensitive substring over name, type **and** observations, first-N in stored order |
90+| `open_nodes` | `{names[], observationLimit?}` | exact names; relations kept when **either** endpoint is in the set |
91+
92+A tool failure is a `tools/call` **result** with `isError:true` and the human
93+sentence in `content[0].text` — never a JSON-RPC error — so an agent reading the
94+text can correct itself. Mutations also carry `structuredContent`, and
95+`create_entities` adds a second plain-text block naming what was skipped.
96+
97+## HTTP actions
98+
99+Every action maps onto one of the nine tools, so the page can never drift away
100+from what an agent sees.
101+
102+| Action | Call | Returns |
103+|---|---|---|
104+| `graph` | `GET ?action=graph` | `{"ok":true,"entities":[…],"relations":[…]}` |
105+| `search` | `GET ?action=search&q=<text>&limit=` | same shape, name / type / observation matched |
106+| `entity` | `GET ?action=entity&name=<name>` | `{"ok":true,"entities":[e],"relations":[…]}` — both directions |
107+| `stats` | `GET ?action=stats` | `{"ok":true,"entities":N,"relations":N,"observations":N,"unreadable_lines":N,"types":[…]}` |
108+| `add_entity` | `POST ?action=add_entity` `{"name","entityType","observations?":[]}` | `{"ok":true,…}` |
109+| `add_relation` | `POST ?action=add_relation` `{"from","to","relationType"}` | `{"ok":true,…}` |
110+| `add_obs` | `POST ?action=add_obs` `{"name","contents":[]}` | `{"ok":true,"results":[…]}` |
111+| `delete_entity` | `POST ?action=delete_entity&name=` | `{"ok":true,"message":"…"}` |
112+| `delete_obs` | `POST ?action=delete_obs` `{"name","observations":[]}` | `{"ok":true,"message":"…"}` |
113+| `delete_relation` | `POST ?action=delete_relation` `{"from","to","relationType"}` | `{"ok":true,"message":"…"}` |
114+| `tools` | `GET ?action=tools` | the nine MCP tool schemas + `kind:"mcp"` |
115+| `export` | `GET ?action=export` | the raw JSONL as `text/plain` download |
116+
117+`?action=` and a JSON body are both accepted, so the page can POST an array
118+(`contents`, `observations`) without stuffing it into a query string.
119+
120+```sh
121+P="pwd=$BOT_PASSWORD"
122+curl -s "http://127.0.0.1:8150/plugin_memory?action=stats&$P"
123+
124+curl -s -X POST -H "Content-Type: application/json" \
125+ "http://127.0.0.1:8150/plugin_memory?action=add_entity&$P" \
126+ -d '{"name":"Earl Grey","entityType":"tea","observations":["black tea","bergamot"]}'
127+
128+curl -s -X POST -H "Content-Type: application/json" \
129+ "http://127.0.0.1:8150/plugin_memory?action=add_relation&$P" \
130+ -d '{"from":"Earl Grey","to":"Cup","relationType":"is served in"}'
131+
132+curl -s "http://127.0.0.1:8150/plugin_memory?action=search&q=bergamot&$P"
133+```
134+
135+## Storage
136+
137+| Platform | Location |
138+|---|---|
139+| Linux / macOS | `~/.scorpiox/connectors/plugin_memory/memory.jsonl` |
140+| BotCloud container | `/workspace/.scorpiox/connectors/plugin_memory/memory.jsonl` (preferred when `/workspace` exists — the rootfs does not survive stop → start) |
141+| Windows | `%LOCALAPPDATA%\scorpiox\connectors\plugin_memory\memory.jsonl` |
142+| Override | `$MEMORY_FILE_PATH` (absolute, or relative to the connector directory) |
143+
144+One JSON object per line, exactly the upstream record shape:
145+
146+```
147+{"type":"entity","name":"Earl Grey","entityType":"tea","observations":["black tea","bergamot"]}
148+{"type":"relation","from":"Earl Grey","to":"Cup","relationType":"is served in"}
149+```
150+
151+* Entities are written first, then relations, then anything the loader could not
152+ parse — **verbatim**. A malformed line is never silently deleted by an unrelated
153+ write; it is carried through and written back byte for byte, and counted in
154+ `unreadable_lines`.
155+* Every save goes to `<path>.tmp.<pid>`, `fflush` + `fsync`, `chmod` to the
156+ existing mode, then `rename()`. A process killed mid-write leaves the previous
157+ graph intact rather than a half file, and the temp file is unlinked on failure.
158+* Parent directories are created `0700` — the graph holds the operator's notes
159+ about their own projects, so it is never world-readable.
160+
161+## Security model
162+
163+* **Authentication** — every HTTP action requires the node password (three forms
164+ above); `--meta` alone stays open so discovery works.
165+* **Write scope** — exactly one file, inside the connector directory above.
166+ `MEMORY_FILE_PATH` may not contain `..`.
167+* **No process spawn, no network** — no `popen`, `system`, `exec*`, `socket()` or
168+ `curl` anywhere in `src/`; `tests/run.sh` asserts it against the source.
169+ `plugin.json` declares `capabilities: ["fs_read_connector_dir","fs_write_connector_dir"]`
170+ and nothing else.
171+* **Input limits** — a request body is capped at 8 MiB and a single `--mcp` line
172+ at 8 MiB; entity names and relation ends at 1024 characters, a relation type at
173+ 1024, an observation at 8000. The graph itself is bounded (`MEMORY_MAX_ENTITIES`
174+ 20000, `MEMORY_MAX_RELATIONS` 40000, `MEMORY_MAX_OBS` 2000 per entity,
175+ `MEMORY_MAX_BAD` 5000 preserved lines) and a file over 24 MiB is refused rather
176+ than loaded. Every limit is an error naming the limit, never a crash.
177+* **XSS** — every byte of graph content is HTML-escaped before any tag is emitted,
178+ so a node named `<script>alert(1)</script>` renders as inert text.
179+* **CSP** — `default-src 'none'; script-src 'unsafe-inline'; style-src
180+ 'unsafe-inline'; connect-src 'self'; form-action 'none'; base-uri 'none'`, so a
181+ future regression still cannot fetch a remote script.
182+* **Robustness** — the whole suite also runs under ASan + UBSan +
183+ `_FORTIFY_SOURCE=2`, including a garbage-stdin pass and the CGI path.
184+
185+## UI
186+
187+One page, two panes: the entity list with search and type chips on the left,
188+the inspector on the right. Under 700 px it collapses to a single pane with a
189+back button, so the same page is usable at 390 px and inside the Chat floating
190+window.
191+
192+* live search over name, type and observations; type chips filter in one click
193+* entity inspector: observations with per-row remove, relations in **and** out,
194+ a "new relation from here" picker (both ends must already exist, exact
195+ duplicates are skipped)
196+* add observation, add relation, delete entity / observation / relation, all
197+ round-tripping into the JSONL immediately
198+* `stats` tally in the header, status line for every action, `export` as a file
199+* dark and light from the SCORPIOX BOT theme tokens — `?theme=`,
200+ `localStorage.bot_theme`, `prefers-color-scheme`, and the `sx-theme`
201+ postMessage handoff; the plugin's own toggle hides under `?embed=1`
202+* no `<script src=>`, no CDN, no framework, zero emoji — inline SVG only
203+
204+![1440 dark](docs/ui-1440-dark.png)
205+![390 dark](docs/ui-390-dark.png)
206+
207+## API routes the page uses
208+
209+The single most common plugin bug is calling the wrong route. This page branches
210+exactly once:
211+
212+* served through the hub (`/plugins?plugin=plugin_memory&node=...`) → call the hub
213+ proxy back: `/plugins?plugin=plugin_memory&action=...`
214+* opened directly on the node (`/plugin_memory`) → the plugin **is** the route:
215+ `/plugin_memory?action=...`
216+
217+Calling `/plugins?plugin=` on the node itself returns the discovery list, not the
218+plugin.
219+
220+## Test
221+
222+```sh
223+make test # 180+ offline assertions, 0 fail, no network, no Playwright
224+make e2e # Playwright: 6 viewports × theme, console/overflow/CRUD round trip
225+```
226+
227+The offline suite proves the contract: `--meta` field for field, `--mcp` as a real
228+JSON-RPC session (all nine tools, notifications, bad JSON, unknown method,
229+`ping`, resources), the skip / dedupe / not-found semantics, `observationLimit 0`
230+versus absent, the either-endpoint relation rule, cross-process persistence,
231+verbatim survival of a malformed line, no `.tmp` left behind, every HTTP action's
232+JSON shape, the auth matrix, the source guards, and the ASan/UBSan run. It also
233+cross-builds musl, aarch64 and MinGW where the toolchain is installed, and audits
234+git history for LAN IPs and tokens.
235+
236+## License
237+
238+MIT — see [LICENSE](LICENSE). Vendored: [yyjson](https://github.com/ibireme/yyjson)
239+0.12.0 (MIT, `vendor/`, compiled in — no runtime dependency on any target).
build.ps1+66−0■■■■■
11new file mode 100644
index 0000000..ff6dfc2
--- /dev/null
+++ b/build.ps1
@@ -0,0 +1,66 @@
1+# build.ps1 - Windows static build for plugin_memory
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_memory.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/MSYS2 UCRT gcc on PATH
8+# (or C:\gcc16\bin\gcc.exe).
9+#
10+# The binary is four translation units plus the vendored yyjson amalgamation -
11+# no DLLs, no libcurl, no sqlite, nothing to install on the node.
12+
13+$ErrorActionPreference = "Stop"
14+$ScriptDir = $PSScriptRoot
15+Push-Location $ScriptDir
16+try {
17+ $Srcs = @(
18+ "src\plugin_memory.c",
19+ "src\graph.c",
20+ "src\tools.c",
21+ "src\api.c",
22+ "vendor\yyjson.c"
23+ )
24+ $Out = Join-Path $ScriptDir "plugin_memory.exe"
25+ $Cc = "x86_64-w64-mingw32-gcc"
26+
27+ foreach ($s in $Srcs) {
28+ $p = Join-Path $ScriptDir $s
29+ if (-not (Test-Path $p)) { throw "source not found: $p" }
30+ }
31+
32+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
33+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
34+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
35+ $Cc = "C:\gcc16\bin\gcc.exe"
36+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
37+ $Cc = "gcc"
38+ } else {
39+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
40+ }
41+ }
42+
43+ # Regenerate the page header so the binary always matches src/ui.html.
44+ if (Get-Command python -ErrorAction SilentlyContinue) {
45+ python tools\gen_ui.py
46+ }
47+
48+ Write-Host "==> building plugin_memory.exe with $Cc"
49+ & $Cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor `
50+ -static -o $Out $Srcs
51+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
52+
53+ if (-not (Test-Path $Out)) { throw "build produced no output" }
54+
55+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
56+ $bytes = [System.IO.File]::ReadAllBytes($Out)
57+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
58+ throw "output is not a PE executable (missing MZ header)"
59+ }
60+
61+ Write-Host "==> ok: $Out ($($bytes.Length) bytes)"
62+ Write-Host " smoke test: .\plugin_memory.exe --meta"
63+ Write-Host " .\plugin_memory.exe --mcp (then paste a JSON-RPC line)"
64+} finally {
65+ Pop-Location
66+}
docs/ui-1024-dark.png+0−0■
11new file mode 100644
index 0000000..6ddb6ad
binary image
Binary image file
docs/ui-1024-light.png+0−0■
11new file mode 100644
index 0000000..0b624ec
binary image
Binary image file
docs/ui-1440-dark.png+0−0■
11new file mode 100644
index 0000000..54f9e3b
binary image
Binary image file
docs/ui-1440-light.png+0−0■
11new file mode 100644
index 0000000..056f181
binary image
Binary image file
docs/ui-390-dark.png+0−0■
11new file mode 100644
index 0000000..91fd07c
binary image
Binary image file
docs/ui-390-light.png+0−0■
11new file mode 100644
index 0000000..f4b1271
binary image
Binary image file
docs/usage.md+123−0■■■■■
11new file mode 100644
index 0000000..e486137
--- /dev/null
+++ b/docs/usage.md
@@ -0,0 +1,123 @@
1+# Using the memory connector
2+
3+## Registering it for agents
4+
5+`plugin_memory` is an **MCP connector**, not a standalone MCP server. Installed
6+through `plugin_manage` (or **Settings → Plugins**), it announces
7+`kind:"mcp"`, `mcp:true`, `menus:false`, and `scorpiox-bot-api` records it in
8+`<connectors_dir>/mcp_plugins.json`:
9+
10+```json
11+{
12+ "mcpServers": {
13+ "memory": { "command": "/root/.scorpiox/plugins/plugin_memory", "args": ["--mcp"] }
14+ }
15+}
16+```
17+
18+`clang` never sees that file. `scorpiox-bot-api` ships one stdio router,
19+`sx-connector-mcp`, registered as a **single** MCP server; it reads
20+`mcp_plugins.json` and exposes four compact meta-tools — `connector_list`,
21+`connector_search`, `connector_tools`, `connector_call`. That is why a node can
22+carry hundreds of connectors without touching `MAX_SERVERS 16` or bloating the
23+prompt: only the router's four tools are ever in context, and the nine memory
24+tools are fetched on demand.
25+
26+## Talking to it by hand
27+
28+```sh
29+# discovery (no password)
30+./plugin_memory --meta
31+
32+# the nine tool schemas
33+./plugin_memory --schema | python3 -m json.tool
34+
35+# a real JSON-RPC session: one request per line, one response per line
36+printf '%s\n' \
37+ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \
38+ '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
39+ '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' \
40+ '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"Earl Grey","entityType":"tea","observations":["black tea","bergamot"]}]}}}' \
41+ '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"read_graph","arguments":{}}}' \
42+ | ./plugin_memory --mcp
43+```
44+
45+Through the router, which is how an agent reaches it:
46+
47+```sh
48+sx-connector-mcp --list
49+sx-connector-mcp --tools memory
50+sx-connector-mcp --call memory create_entities \
51+ '{"entities":[{"name":"Earl Grey","entityType":"tea","observations":["black tea"]}]}'
52+sx-connector-mcp --call memory read_graph '{}'
53+```
54+
55+## Prompt recipes that work
56+
57+The tool names, schemas and error sentences match the upstream reference memory
58+server, so existing prompts transfer unchanged. Two that earn their keep:
59+
60+**Orient first, read second.** On a graph you did not build, do not open the
61+whole thing. Ask for the cheap overview, then open only what matters:
62+
63+> Read the graph with `observationLimit: 0` to see every entity name, type and
64+> observation **count**. Then `open_nodes` on the two or three names you
65+> actually need, without the limit, to read their full observations.
66+
67+**Facts, not prose.** An observation is one atomic claim an agent can match on
68+exactly (`delete_observations` matches exact text). "deploy runs on .100 via
69+tmux" is a fact; "notes about deploying" is not.
70+
71+## Session memory pattern
72+
73+A common shape for a long-running assistant:
74+
75+1. At the start of a session: `read_graph` with `observationLimit: 0` — one
76+ cheap call that tells the agent what it already knows.
77+2. When the user states something worth keeping: `create_entities` for the
78+ thing, then `create_relations` to hang it on something already in the graph.
79+ The relation is the memory; two unlinked entities are two facts nobody can
80+ find.
81+3. Before correcting: `delete_observations` on the exact stale text, then
82+ `add_observations` with the new one. Never delete and recreate the entity —
83+ that silently drops its relations.
84+
85+## Where the data lives, and how to move it
86+
87+| Situation | Do this |
88+|---|---|
89+| Default | `~/.scorpiox/connectors/plugin_memory/memory.jsonl` |
90+| BotCloud container (rootfs does not survive stop → start) | `/workspace/.scorpiox/connectors/plugin_memory/memory.jsonl` — used automatically when `/workspace` exists |
91+| Windows node | `%LOCALAPPDATA%\scorpiox\connectors\plugin_memory\memory.jsonl` |
92+| Put it somewhere else | `MEMORY_FILE_PATH=/srv/memory/graph.jsonl` (absolute, or relative to the connector dir; `..` is refused) |
93+
94+The file is plain JSONL — one `{"type":"entity",...}` or `{"type":"relation",...}`
95+per line. Back it up by copying it, edit it in any editor, `git` it, or move it
96+between nodes. Lines the loader cannot parse are preserved byte for byte and
97+reported as `unreadable_lines` in `?action=stats`, so a hand-edit that breaks one
98+line cannot lose the graph.
99+
100+`?action=export` downloads the file as-is; `GET /plugin_memory?action=export` with
101+the node password is the whole backup path.
102+
103+## Limits
104+
105+| Knob | Default | Effect |
106+|---|---|---|
107+| `MEMORY_MAX_ENTITIES` | 20000 | creating past this is refused with an instruction to delete |
108+| `MEMORY_MAX_RELATIONS` | 40000 | same |
109+| `MEMORY_MAX_OBS` | 2000 per entity | extra observations in a call are dropped, the call still succeeds |
110+| `MEMORY_MAX_BAD` | 5000 | how many unparseable lines are carried forward verbatim |
111+| `MEMORY_LOCK_STALE_MS` | 10000 | a `.lock` older than this is treated as abandoned and broken |
112+| `MEMORY_LOCK_TIMEOUT_MS` | 2000 | how long a second writer waits for the lock before proceeding best-effort |
113+
114+## Troubleshooting
115+
116+| Symptom | Cause |
117+|---|---|
118+| `--meta` fine, tools missing in the agent | the router has not re-read `mcp_plugins.json` — reinstall through `plugin_manage`, or restart the session so `scorpiox-mcp` respawns |
119+| `{"error":{"code":-32601}}` | method not supported by design (`prompts/*`, `tools/*` typos). Only `initialize`, `ping`, `notifications/*`, `tools/list`, `tools/call`, `resources/list`, `resources/read` answer |
120+| A tool "failed" but there is no JSON-RPC error | intentional: tool failures are results with `isError:true` and the reason in `content[0].text`, so the agent can read and correct |
121+| `create_entities` created nothing | the name already exists (check `skipped`) — use `add_observations`, which is the tool for that |
122+| `Entity with name X not found` on `create_relations` | both ends must exist first; create the entities, then link |
123+| Two processes writing at once | the second takes a `.lock` and waits; if it times out, a stale `.lock` older than `MEMORY_LOCK_STALE_MS` is broken automatically |
plugin.json+20−0■■■■■
11new file mode 100644
index 0000000..fcd7ab5
--- /dev/null
+++ b/plugin.json
@@ -0,0 +1,20 @@
1+{
2+ "slug": "memory",
3+ "id": "plugin_memory",
4+ "title": "Knowledge Graph Memory",
5+ "summary": "A persistent knowledge graph your agents can write to and read back: entities with observations, typed relations between them, and the nine standard MCP memory tools (create_entities, create_relations, add_observations, delete_entities, delete_observations, delete_relations, read_graph, search_nodes, open_nodes) served over stdio by this one binary. The same nine operations back a browser UI for searching, inspecting and editing the graph. The graph is a single JSONL file in this connector's own data directory, written through a staged temp file and renamed into place, so a crash mid-save cannot truncate it; lines the loader cannot parse are preserved byte for byte rather than dropped. Zero dependencies, zero network requests.",
6+ "category": "devtools",
7+ "license": "MIT",
8+ "kind": "mcp",
9+ "mcp": true,
10+ "daemon": false,
11+ "menus": false,
12+ "verified": "live",
13+ "capabilities": [
14+ "fs_read_connector_dir",
15+ "fs_write_connector_dir"
16+ ],
17+ "trust_notice": "Executes native C code on your node. Reads and writes exactly one file: memory.jsonl inside its own connector directory (~/.scorpiox/connectors/plugin_memory, or /workspace/.scorpiox/connectors/plugin_memory when /workspace exists, or $MEMORY_FILE_PATH when you set it). It opens no network connection, never runs another program, and reads nothing outside that directory.",
18+ "author": "SCORPIOX INC",
19+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-memory"
20+}
release-dist.sh+383−0■■■■■
11new file mode 100755
index 0000000..8084327
--- /dev/null
+++ b/release-dist.sh
@@ -0,0 +1,383 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_memory to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer
7+# CLI and is what publishes the connector fields (kind/mcp/daemon/menus/
8+# verified) into all four dist documents.
9+# B. Standalone (this script): secret scan -> multi-target build ->
10+# source.tar.gz -> manifest.json + SHA256SUMS -> upload -> latest.json /
11+# index.json -> plugingit mirror.
12+#
13+# Nothing here contains a host address or a credential. Everything environment-specific
14+# comes from the environment, so this file stays safe to publish:
15+#
16+# DIST_HOST ssh target for the dist server (required for upload)
17+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
18+# DIST_PATH remote web root of the dist server (default /data/dist)
19+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
20+# MAC_USER / MAC_PASS (optional)
21+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
22+# PLUGINGIT_REMOTE public mirror URL to push into
23+#
24+# Usage:
25+# ./release-dist.sh # full release
26+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
27+# ./release-dist.sh --no-macos # skip the macOS legs
28+# ./release-dist.sh --no-mirror # skip the plugingit mirror
29+# ./release-dist.sh --standalone # use this script even if the CLI is installed
30+
31+set -euo pipefail
32+
33+SLUG="memory"
34+ID="plugin_memory"
35+VERSION="1.0.0"
36+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
37+
38+ROOT="$(cd "$(dirname "$0")" && pwd)"
39+cd "$ROOT"
40+
41+DRY_RUN=0
42+DO_MACOS=1
43+DO_MIRROR=1
44+STANDALONE=0
45+for arg in "$@"; do
46+ case "$arg" in
47+ --standalone) STANDALONE=1 ;;
48+ --dry-run) DRY_RUN=1 ;;
49+ --no-macos) DO_MACOS=0 ;;
50+ --no-mirror) DO_MIRROR=0 ;;
51+ -h|--help) sed -n '2,30p' "$0"; exit 0 ;;
52+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
53+ esac
54+done
55+
56+DIST_HOST="${DIST_HOST:-}"
57+DIST_PASS="${DIST_PASS:-}"
58+DIST_PATH="${DIST_PATH:-/data/dist}"
59+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
60+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
61+
62+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
63+mkdir -p "$STAGE"
64+trap 'rm -rf "$STAGE"' EXIT
65+
66+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
67+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
68+
69+# ---------------------------------------------------------------- 0. preflight
70+say "0/7 preflight"
71+
72+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
73+ say "using scorpiox-cli-botplugin publish"
74+ exec scorpiox-cli-botplugin publish "$ROOT"
75+fi
76+echo " running the standalone pipeline (dist + plugingit mirror)"
77+
78+if [ -n "$(git status --porcelain 2>/dev/null)" ]; then
79+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
80+fi
81+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
82+echo " version $VERSION"
83+echo " commit $COMMIT"
84+
85+# ---------------------------------------------------------------- 1. secret scan
86+say "1/7 secret & LAN scan (full history)"
87+
88+SCAN_TMP="$STAGE/history.txt"
89+# Scan every added/removed line of every commit. Two exclusions, both about the
90+# audit rather than the code: the committer identity line, and any line that is
91+# itself a scan definition - otherwise this file's own detector patterns (and the
92+# identical checks in tests/run.sh) read as findings in every historical revision
93+# of them. A real secret on any other line still hits.
94+git log -p --all 2>/dev/null \
95+ | grep -v '^Author: ' \
96+ | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \
97+ > "$SCAN_TMP" || : > "$SCAN_TMP"
98+HITS=0
99+scan() { # scan <label> <regex>
100+ local out
101+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
102+ if [ -n "$out" ]; then
103+ printf ' \033[31mHIT\033[0m %s\n' "$1"
104+ printf '%s\n' "$out" | sed 's/^/ /'
105+ HITS=$((HITS + 1))
106+ else
107+ printf ' ok %s\n' "$1"
108+ fi
109+}
110+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
111+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
112+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
113+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
114+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
115+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
116+scan "hard-coded ssh password" 'sshpass -p [^"$]'
117+P_ROOT="/codebases"
118+P_PICOBOT="${P_ROOT}/pico""bot"
119+P_WT=".work""trees"
120+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
121+scan "run-token env assignment" 'RUNNER_'"PASS="
122+if [ "$HITS" -ne 0 ]; then
123+ die "secret scan found $HITS problem(s) - refusing to publish"
124+fi
125+echo " clean: 0 hits"
126+
127+# ---------------------------------------------------------------- 2. build
128+say "2/7 build targets"
129+
130+# Every target is the Makefile's own command line, so what ships is what the
131+# suite was tested against. yyjson is compiled in; no target needs any library.
132+make native >/dev/null || die "native build failed"
133+cp -f "$ID" "$STAGE/$ID"
134+echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
135+
136+if command -v musl-gcc >/dev/null 2>&1; then
137+ make musl >/dev/null || die "musl build failed"
138+ cp -f "$ID.musl" "$STAGE/$ID.musl"
139+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
140+else
141+ echo " skip linux-x86_64-musl (no musl-gcc)"
142+fi
143+
144+if command -v aarch64-linux-musl-gcc >/dev/null 2>&1; then
145+ ARM64_CC=aarch64-linux-musl-gcc make arm64 >/dev/null || die "arm64 musl build failed"
146+ cp -f "$ID.arm64" "$STAGE/$ID.arm64"
147+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
148+elif command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
149+ ARM_CC=aarch64-linux-gnu-gcc make arm64 >/dev/null || die "arm64 build failed"
150+ cp -f "$ID.arm64" "$STAGE/$ID.arm64"
151+ echo " built linux-arm64-static $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
152+else
153+ echo " skip linux-arm64-musl (no aarch64 cross compiler)"
154+fi
155+
156+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
157+ make win64 >/dev/null || die "MinGW build failed"
158+ cp -f "$ID.exe" "$STAGE/$ID.exe"
159+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
160+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
161+else
162+ echo " skip windows-x86_64 (no MinGW cross compiler)"
163+fi
164+
165+# macOS legs - Mach-O must be produced by Apple clang on a real Mac. The repo
166+# layout is preserved on the builder because api.c includes "ui_html.h" from
167+# next to the .c and yyjson.h from ../vendor.
168+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
169+ MAC_USER="${MAC_USER:-$(whoami)}"
170+ MAC_DIR="/tmp/${ID}-mac-$$"
171+ echo " building macOS legs on $MAC_HOST"
172+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
173+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
174+ if [ -n "${MAC_PASS:-}" ]; then
175+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
176+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
177+ fi
178+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
179+ "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR/src' '$MAC_DIR/vendor' '$MAC_DIR/tools'"; then
180+ if "${SCP_MAC[@]}" -q src/*.c src/*.h "$MAC_USER@$MAC_HOST:$MAC_DIR/src/" &&
181+ "${SCP_MAC[@]}" -q vendor/yyjson.c vendor/yyjson.h "$MAC_USER@$MAC_HOST:$MAC_DIR/vendor/" &&
182+ "${SCP_MAC[@]}" -q tools/gen_ui.py "$MAC_USER@$MAC_HOST:$MAC_DIR/tools/" &&
183+ "${SCP_MAC[@]}" -q src/ui.html Makefile "$MAC_USER@$MAC_HOST:$MAC_DIR/"; then
184+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && python3 tools/gen_ui.py" 2>/dev/null; then
185+ for slice in arm64 x86_64; do
186+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
187+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor -arch $slice -o $ID.$slice src/plugin_memory.c src/graph.c src/tools.c src/api.c vendor/yyjson.c" \
188+ 2>/dev/null; then
189+ "${SCP_MAC[@]}" -q "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" \
190+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
191+ else
192+ echo " warn: macos-$slice build failed on $MAC_HOST"
193+ fi
194+ done
195+ else
196+ echo " warn: gen_ui.py failed on $MAC_HOST (python3 missing?)"
197+ fi
198+ else
199+ echo " warn: mac scp failed"
200+ fi
201+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true
202+ else
203+ echo " warn: mac host unreachable"
204+ fi
205+else
206+ echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)"
207+fi
208+
209+# ---------------------------------------------------------------- 3. package
210+say "3/7 package"
211+
212+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
213+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
214+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
215+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
216+
217+target_meta() { # target_meta <key> <file> <format> <relpath>
218+ local key="$1" file="$2" fmt="$3" rel="$4"
219+ [ -f "$file" ] || return 0
220+ local sha size
221+ sha=$(sha256sum "$file" | awk '{print $1}')
222+ size=$(wc -c < "$file" | tr -d ' ')
223+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
224+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
225+}
226+
227+# summary / title / trust_notice are taken from plugin.json so there is exactly
228+# one place that says what this plugin does.
229+
230+{
231+ printf '{\n'
232+ printf ' "slug": "%s",\n' "$SLUG"
233+ printf ' "id": "%s",\n' "$ID"
234+ printf ' "name": "%s",\n' "$SLUG"
235+ printf ' "desc": "Knowledge graph",\n'
236+ printf ' "title": %s,\n' "$(python3 -c "import json;print(json.dumps(json.load(open('plugin.json'))['title']))")"
237+ printf ' "summary": %s,\n' "$(python3 -c "import json;print(json.dumps(json.load(open('plugin.json'))['summary']))")"
238+ printf ' "category": "devtools",\n'
239+ printf ' "version": "%s",\n' "$VERSION"
240+ printf ' "license": "MIT",\n'
241+ printf ' "kind": "mcp",\n'
242+ printf ' "mcp": true,\n'
243+ printf ' "daemon": false,\n'
244+ printf ' "menus": false,\n'
245+ printf ' "verified": "live",\n'
246+ printf ' "trust_notice": %s,\n' "$(python3 -c "import json;print(json.dumps(json.load(open('plugin.json'))['trust_notice']))")"
247+ printf ' "capabilities": ["fs_read_connector_dir", "fs_write_connector_dir"],\n'
248+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
249+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
250+ printf ' "git_commit": "%s",\n' "$COMMIT"
251+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
252+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
253+ printf ' "build_cmd_posix": "make",\n'
254+ printf ' "build_cmd_win64": "make win64",\n'
255+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
256+ printf ' "targets": {\n'
257+ first=1
258+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
259+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
260+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
261+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
262+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
263+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
264+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
265+ printf '\n }\n}\n'
266+} > "$STAGE/manifest.json"
267+
268+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
269+ || die "generated manifest.json is not valid JSON"
270+echo " manifest.json ok"
271+
272+# SHA256SUMS - relative paths, exactly as published
273+( cd "$STAGE"
274+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
275+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
276+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
277+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
278+ [ -f "$ID.macos-arm64" ] && sha256sum "$ID.macos-arm64" | sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
279+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64" | sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
280+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
281+ true ) > "$STAGE/SHA256SUMS"
282+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
283+
284+# ---------------------------------------------------------------- 4. stage
285+say "4/7 stage tree"
286+PKG="$STAGE/pkg"
287+mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \
288+ "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64"
289+cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID"
290+[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"
291+[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"
292+[ -f "$STAGE/$ID.macos-arm64" ] && cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"
293+[ -f "$STAGE/$ID.macos-x86_64" ]&& cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"
294+[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"
295+cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
296+chmod +x "$PKG"/*/"$ID" 2>/dev/null || true
297+find "$PKG" -type f | sed 's/^/ /'
298+
299+if [ "$DRY_RUN" -eq 1 ]; then
300+ say "dry run - staged at $STAGE/pkg (kept for inspection)"
301+ trap - EXIT
302+ exit 0
303+fi
304+
305+# ---------------------------------------------------------------- 5. upload
306+say "5/7 upload"
307+
308+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set - cannot upload"
309+SSH=(ssh -o StrictHostKeyChecking=no)
310+SCP=(scp -o StrictHostKeyChecking=no)
311+if [ -n "$DIST_PASS" ]; then
312+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
313+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
314+fi
315+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
316+
317+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
318+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
319+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
320+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
321+# OpenSSH 9 refuses to scp a bare "." source.
322+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
323+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
324+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
325+ || die "remote extract failed"
326+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
327+
328+# latest.json = copy of this version's manifest
329+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
330+ || die "latest.json update failed"
331+echo " updated bot-plugins/$SLUG/latest.json"
332+
333+# index.json - merge, preserving every sibling <slug>/latest.json
334+say "index.json merge"
335+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
336+import json, os, sys, glob
337+slug = sys.argv[1]
338+entries = {}
339+for p in sorted(glob.glob('*/latest.json')):
340+ s = os.path.dirname(p)
341+ try:
342+ entries[s] = json.load(open(p))
343+ except Exception:
344+ pass
345+index = {
346+ 'ok': True,
347+ 'service': 'bot-plugins-dist',
348+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
349+ 'count': len(entries),
350+ 'slugs': sorted(entries),
351+ 'plugins': [entries[k] for k in sorted(entries)],
352+}
353+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
354+os.replace('index.json.tmp', 'index.json')
355+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
356+PY" || die "index.json merge failed"
357+
358+# ---------------------------------------------------------------- 6. mirror
359+say "6/7 plugingit mirror"
360+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
361+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
362+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|")
363+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
364+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
365+ echo " mirrored to $PLUGINGIT_REMOTE"
366+else
367+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
368+fi
369+
370+# ---------------------------------------------------------------- 7. verify
371+say "7/7 verify"
372+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
373+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
374+if [ "$CODE" = "200" ]; then
375+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s), kind=%s mcp=%s menus=%s verified=%s" % (d["slug"], d["version"], len(d["targets"]), d.get("kind"), d.get("mcp"), d.get("menus"), d.get("verified")))' \
376+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
377+else
378+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
379+fi
380+
381+printf '\n\033[1mrelease complete\033[0m\n'
382+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
383+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/api.c+844−0■■■■■
11new file mode 100644
index 0000000..d50451c
--- /dev/null
+++ b/src/api.c
@@ -0,0 +1,844 @@
1+/*
2+ * api.c - the CGI front end for plugin_memory: the browser page and the JSON
3+ * actions it talks to.
4+ *
5+ * There is deliberately no second implementation of the graph operations here.
6+ * Every action maps onto one of the nine tools in tools.c, so the page and an
7+ * agent going through --mcp see exactly the same thing - the same skips, the
8+ * same not-found messages, the same relation rules. When the two are separate
9+ * they drift, and the drift only ever shows up in production.
10+ *
11+ * Parameters are read from the QUERY_STRING *and* from a JSON body, because
12+ * the UI posts JSON (it must: an observation can be any text) while a person
13+ * debugging with curl expects a query string. `action` and `format` are kept
14+ * in separate buffers on purpose - reading one into the other's variable
15+ * silently degrades an action request to the default action.
16+ *
17+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
18+ */
19+
20+#if defined(_WIN32) && !defined(_WIN32_WINNT)
21+# define _WIN32_WINNT 0x0601
22+#endif
23+
24+#if !defined(_WIN32)
25+# define _POSIX_C_SOURCE 200809L
26+# define _DEFAULT_SOURCE 1
27+# if defined(__APPLE__)
28+# define _DARWIN_C_SOURCE 1
29+# endif
30+#endif
31+
32+#include <stdio.h>
33+#include <stdlib.h>
34+#include <string.h>
35+#include <ctype.h>
36+#include <time.h>
37+
38+#if defined(_WIN32)
39+# define WIN32_LEAN_AND_MEAN
40+# include <windows.h>
41+#else
42+# include <unistd.h>
43+#endif
44+
45+#include "memory.h"
46+#include "bot_theme_plugin.h"
47+#include "ui_html.h"
48+
49+/* ------------------------------------------------------------------ */
50+/* Query string */
51+/* ------------------------------------------------------------------ */
52+
53+static void url_decode(char *s)
54+{
55+ char *o = s;
56+ if (!s) return;
57+ while (*s) {
58+ if (*s == '%' && isxdigit((unsigned char)s[1]) &&
59+ isxdigit((unsigned char)s[2])) {
60+ int hi = (s[1] <= '9') ? s[1] - '0'
61+ : (tolower((unsigned char)s[1]) - 'a' + 10);
62+ int lo = (s[2] <= '9') ? s[2] - '0'
63+ : (tolower((unsigned char)s[2]) - 'a' + 10);
64+ *o++ = (char)((hi << 4) | lo);
65+ s += 3;
66+ } else if (*s == '+') {
67+ *o++ = ' ';
68+ s++;
69+ } else {
70+ *o++ = *s++;
71+ }
72+ }
73+ *o = '\0';
74+}
75+
76+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
77+{
78+ size_t klen;
79+ const char *p = qs;
80+
81+ if (out && outsz) out[0] = '\0';
82+ if (!qs || !*qs || !key || !out || outsz == 0) return 0;
83+ klen = strlen(key);
84+
85+ while (p && *p) {
86+ const char *eq = strchr(p, '=');
87+ const char *amp = strchr(p, '&');
88+ if (!eq || (amp && eq > amp)) {
89+ p = amp ? amp + 1 : NULL;
90+ continue;
91+ }
92+ if ((size_t)(eq - p) == klen && strncmp(p, key, klen) == 0) {
93+ const char *vs = eq + 1;
94+ size_t n = amp ? (size_t)(amp - vs) : strlen(vs);
95+ if (n >= outsz) n = outsz - 1;
96+ memcpy(out, vs, n);
97+ out[n] = '\0';
98+ url_decode(out);
99+ return 1;
100+ }
101+ p = amp ? amp + 1 : NULL;
102+ }
103+ return 0;
104+}
105+
106+/* ------------------------------------------------------------------ */
107+/* Request body */
108+/* ------------------------------------------------------------------ */
109+
110+static char g_body[REQ_BODY_MAX];
111+
112+/* Read the body only when CONTENT_LENGTH says there is one: a CGI handler
113+ * that reads stdin unconditionally hangs on an inherited empty stdin. */
114+static int read_request_body(void)
115+{
116+ const char *cl = getenv("CONTENT_LENGTH");
117+ long len;
118+ size_t got;
119+
120+ g_body[0] = '\0';
121+ if (!cl || !*cl) return 0;
122+ len = strtol(cl, NULL, 10);
123+ if (len <= 0) return 0;
124+ if ((size_t)len >= sizeof g_body) return -1;
125+ got = fread(g_body, 1, (size_t)len, stdin);
126+ g_body[got] = '\0';
127+ return (int)got;
128+}
129+
130+static yyjson_doc *g_body_doc = NULL;
131+
132+static yyjson_val *body_root(void)
133+{
134+ return g_body_doc ? yyjson_doc_get_root(g_body_doc) : NULL;
135+}
136+
137+/* One parameter: query string first, then the JSON body. Strings are
138+ * returned in `out`; `has` says whether either source had it. */
139+static int param_str(const char *qs, const char *key, char *out, size_t outsz)
140+{
141+ if (out && outsz) out[0] = '\0';
142+ if (qs && get_query_val(qs, key, out, outsz) && out[0]) return 1;
143+ {
144+ yyjson_val *root = body_root();
145+ yyjson_val *v = root ? yyjson_obj_get(root, key) : NULL;
146+ if (v && yyjson_is_str(v)) {
147+ str_copy(out, outsz, yyjson_get_str(v));
148+ return 1;
149+ }
150+ }
151+ return 0;
152+}
153+
154+/* An array parameter (e.g. names[], observations[]) from either source. A
155+ * query string accepts a JSON array value or a |-separated list. */
156+static yyjson_val *body_arr(const char *key)
157+{
158+ yyjson_val *root = body_root();
159+ yyjson_val *v = root ? yyjson_obj_get(root, key) : NULL;
160+ return (v && yyjson_is_arr(v)) ? v : NULL;
161+}
162+
163+/* ------------------------------------------------------------------ */
164+/* Node authentication */
165+/* */
166+/* The node's :8150 is LAN-reachable, and this plugin can read and write the
167+ * operator's knowledge graph, so it must not answer a bare curl. Three
168+ * credential forms are accepted because the three callers differ: bot-web
169+ * proxies with a header, the plugin iframe appends ?pwd=, and a script may
170+ * send a bearer token. --meta stays open so /plugins can still discover us. */
171+/* ------------------------------------------------------------------ */
172+
173+static void require_node_auth(void)
174+{
175+ const char *np = getenv("BOT_PASSWORD");
176+ const char *xp, *auth, *qs;
177+ char qpwd[256];
178+
179+ if (!np || !*np) return; /* node has no password set */
180+
181+ xp = getenv("HTTP_X_BOT_PASSWORD");
182+ if (xp && strcmp(xp, np) == 0) return;
183+
184+ auth = getenv("HTTP_AUTHORIZATION");
185+ if (auth) {
186+ while (*auth == ' ') auth++;
187+ if (strncmp(auth, "Bearer ", 7) == 0) {
188+ auth += 7;
189+ while (*auth == ' ') auth++;
190+ if (strcmp(auth, np) == 0) return;
191+ }
192+ }
193+
194+ qs = getenv("QUERY_STRING");
195+ if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) &&
196+ strcmp(qpwd, np) == 0) return;
197+
198+ fputs("Status: 401 Unauthorized\r\n"
199+ "Content-Type: application/json; charset=utf-8\r\n"
200+ "Cache-Control: no-store\r\n"
201+ "X-Content-Type-Options: nosniff\r\n\r\n"
202+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
203+ exit(0);
204+}
205+
206+/* ------------------------------------------------------------------ */
207+/* Responses */
208+/* ------------------------------------------------------------------ */
209+
210+static void json_header(void)
211+{
212+ fputs("Content-Type: application/json; charset=utf-8\r\n"
213+ "Cache-Control: no-store\r\n"
214+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
215+}
216+
217+static void json_raw(const char *json)
218+{
219+ json_header();
220+ fputs(json ? json : "{\"ok\":true}", stdout);
221+ fputc('\n', stdout);
222+ fflush(stdout);
223+}
224+
225+static void json_err(int code, const char *msg)
226+{
227+ buf_t b;
228+ const char *status = NULL;
229+
230+ if (code == 400) status = "Status: 400 Bad Request\r\n";
231+ else if (code == 404) status = "Status: 404 Not Found\r\n";
232+ else if (code == 413) status = "Status: 413 Payload Too Large\r\n";
233+ else status = "Status: 500 Internal Server Error\r\n";
234+
235+ buf_init(&b);
236+ buf_puts(&b, status);
237+ buf_puts(&b, "Content-Type: application/json; charset=utf-8\r\n"
238+ "Cache-Control: no-store\r\n"
239+ "X-Content-Type-Options: nosniff\r\n\r\n"
240+ "{\"ok\":false,\"status\":");
241+ { char t[8]; snprintf(t, sizeof t, "%d", code); buf_puts(&b, t); }
242+ buf_puts(&b, ",\"error\":");
243+ json_str(&b, msg ? msg : "error");
244+ buf_puts(&b, "}");
245+ fputs(buf_str(&b), stdout);
246+ fputc('\n', stdout);
247+ fflush(stdout);
248+ buf_free(&b);
249+}
250+
251+/* Run a tool and answer with its result, mapping the tool's own error to a
252+ * 200 + ok:false so the UI can show the message the reference server gives
253+ * rather than a bare HTTP status. */
254+/* Run one tool for an HTTP action. The UI's arguments were assembled into a
255+ * mutable document, so serialize it and re-parse: the tools read the
256+ * immutable yyjson_val API, and a cast between the two types would be a
257+ * silent type-lie that only yyjson's internals could expose. At these sizes
258+ * one round trip costs nothing, and both types stay exactly what they are. */
259+static void run_tool(const char *name, yyjson_mut_doc *md,
260+ yyjson_mut_val *root)
261+{
262+ tool_out_t t;
263+ char *s;
264+ char *packed = NULL;
265+ yyjson_doc *parsed = NULL;
266+ yyjson_val *args = NULL;
267+
268+ if (md && root) {
269+ packed = yyjson_mut_write(md, 0, NULL);
270+ if (packed) {
271+ parsed = yyjson_read(packed, strlen(packed), 0);
272+ if (parsed) args = yyjson_doc_get_root(parsed);
273+ }
274+ }
275+
276+ tool_out_init(&t);
277+ if (tool_dispatch(name, args, &t) != 0) {
278+ tool_free(&t);
279+ free(packed);
280+ if (parsed) yyjson_doc_free(parsed);
281+ json_err(400, "unknown action");
282+ return;
283+ }
284+ s = tool_api_result(&t);
285+ json_raw(s);
286+ free(s);
287+ tool_free(&t);
288+ free(packed);
289+ if (parsed) yyjson_doc_free(parsed);
290+}
291+
292+/* ------------------------------------------------------------------ */
293+/* Args assembled from the request */
294+/* ------------------------------------------------------------------ */
295+
296+/* Build a mutable doc so we can graft arrays taken from the body together
297+ * with scalars from the query string, and hand the tools one object either
298+ * way. The doc owns the memory the tools read during dispatch. */
299+typedef struct {
300+ yyjson_mut_doc *md;
301+ yyjson_mut_val *root;
302+} args_t;
303+
304+static void args_init(args_t *a)
305+{
306+ memset(a, 0, sizeof *a);
307+ a->md = yyjson_mut_doc_new(NULL);
308+ if (!a->md) return;
309+ a->root = yyjson_mut_obj(a->md);
310+ if (a->root) yyjson_mut_doc_set_root(a->md, a->root);
311+}
312+
313+static void args_free(args_t *a)
314+{
315+ if (a && a->md) yyjson_mut_doc_free(a->md);
316+ memset(a, 0, sizeof *a);
317+}
318+
319+static void args_add_str(args_t *a, const char *k, const char *v)
320+{
321+ if (a->root) yyjson_mut_obj_add_str(a->md, a->root, k, v ? v : "");
322+}
323+
324+static void args_add_int(args_t *a, const char *k, long v)
325+{
326+ if (a->root) yyjson_mut_obj_add_sint(a->md, a->root, k, (int64_t)v);
327+}
328+
329+/* A string array: from the body when present, else a |-separated query value,
330+ * else a repeated single value. */
331+static void args_add_arr(args_t *a, const char *k, const char *qval)
332+{
333+ yyjson_val *src = body_arr(k);
334+ (void)qval;
335+ yyjson_mut_val *arr = a->root ? yyjson_mut_arr(a->md) : NULL;
336+ if (!arr) return;
337+
338+ if (src) {
339+ size_t i, n = yyjson_arr_size(src);
340+ for (i = 0; i < n; i++) {
341+ yyjson_val *v = yyjson_arr_get(src, i);
342+ if (v && yyjson_is_str(v))
343+ yyjson_mut_arr_add_str(a->md, arr, yyjson_get_str(v));
344+ }
345+ } else if (qval && *qval) {
346+ /* '|' separated, with \%7C available for a literal pipe. */
347+ const char *p = qval;
348+ while (*p) {
349+ const char *s = strchr(p, '|');
350+ size_t len = s ? (size_t)(s - p) : strlen(p);
351+ char tmp[OBS_TEXT_MAX];
352+ if (len >= sizeof tmp) len = sizeof tmp - 1;
353+ memcpy(tmp, p, len);
354+ tmp[len] = '\0';
355+ yyjson_mut_arr_add_str(a->md, arr, tmp);
356+ if (!s) break;
357+ p = s + 1;
358+ }
359+ }
360+ if (a->root) yyjson_mut_obj_add_val(a->md, a->root, k, arr);
361+}
362+
363+/* ------------------------------------------------------------------ */
364+/* Actions */
365+/* ------------------------------------------------------------------ */
366+
367+static void do_stats(const char *qs)
368+{
369+ long long size = 0;
370+ int exists = 0;
371+ size_t i, n_obs = 0, types_seen = 0;
372+ const char **types = NULL;
373+ buf_t b;
374+
375+ (void)qs;
376+ if (graph_load() != 0) { json_err(500, g_data_err); return; }
377+ graph_path_info(&size, &exists);
378+ for (i = 0; i < G.n_ent; i++) n_obs += G.ent[i].n_obs;
379+
380+ /* distinct types, for the filter chips */
381+ types = (const char **)calloc(G.n_ent ? G.n_ent : 1, sizeof *types);
382+ buf_init(&b);
383+ buf_puts(&b, "{\"ok\":true,\"entities\":");
384+ { char t[32]; snprintf(t, sizeof t, "%zu", G.n_ent); buf_puts(&b, t); }
385+ buf_puts(&b, ",\"relations\":");
386+ { char t[32]; snprintf(t, sizeof t, "%zu", G.n_rel); buf_puts(&b, t); }
387+ buf_puts(&b, ",\"observations\":");
388+ { char t[32]; snprintf(t, sizeof t, "%zu", n_obs); buf_puts(&b, t); }
389+ buf_puts(&b, ",\"unreadable_lines\":");
390+ { char t[32]; snprintf(t, sizeof t, "%zu", G.n_bad); buf_puts(&b, t); }
391+ buf_puts(&b, ",\"file_exists\":");
392+ buf_puts(&b, exists ? "true" : "false");
393+ buf_puts(&b, ",\"file_bytes\":");
394+ { char t[32]; snprintf(t, sizeof t, "%lld", size); buf_puts(&b, t); }
395+ buf_puts(&b, ",\"types\":[");
396+ if (types) {
397+ for (i = 0; i < G.n_ent; i++) {
398+ size_t j;
399+ int seen = 0;
400+ for (j = 0; j < types_seen; j++)
401+ if (strcmp(types[j], G.ent[i].etype) == 0) { seen = 1; break; }
402+ if (seen) continue;
403+ if (types_seen >= 200) break;
404+ types[types_seen++] = G.ent[i].etype;
405+ if (types_seen > 1) buf_putc(&b, ',');
406+ json_str(&b, G.ent[i].etype);
407+ }
408+ }
409+ buf_puts(&b, "]}");
410+ json_raw(buf_str(&b));
411+ buf_free(&b);
412+ free((void *)types);
413+}
414+
415+static void do_graph(const char *qs)
416+{
417+ char types[4096], lim[32];
418+ args_t a;
419+
420+ args_init(&a);
421+ if (param_str(qs, "entityTypes", types, sizeof types))
422+ args_add_arr(&a, "entityTypes", types);
423+ if (param_str(qs, "limit", lim, sizeof lim))
424+ args_add_int(&a, "limit", strtol(lim, NULL, 10));
425+ run_tool("read_graph", a.md, a.root);
426+ args_free(&a);
427+}
428+
429+static void do_search(const char *qs)
430+{
431+ char q[512], lim[32], ol[32];
432+ args_t a;
433+
434+ if (!param_str(qs, "q", q, sizeof q) || !q[0]) {
435+ json_err(400, "missing q");
436+ return;
437+ }
438+ args_init(&a);
439+ args_add_str(&a, "query", q);
440+ if (param_str(qs, "limit", lim, sizeof lim))
441+ args_add_int(&a, "limit", strtol(lim, NULL, 10));
442+ if (param_str(qs, "observationLimit", ol, sizeof ol))
443+ args_add_int(&a, "observationLimit", strtol(ol, NULL, 10));
444+ run_tool("search_nodes", a.md, a.root);
445+ args_free(&a);
446+}
447+
448+static void do_entity(const char *qs)
449+{
450+ char name[SX_NAME_MAX * 2];
451+ args_t a;
452+
453+ if (!param_str(qs, "name", name, sizeof name) || !name[0]) {
454+ json_err(400, "missing name");
455+ return;
456+ }
457+ args_init(&a);
458+ {
459+ yyjson_mut_val *arr = yyjson_mut_arr(a.md);
460+ yyjson_mut_arr_add_strcpy(a.md, arr, name);
461+ yyjson_mut_obj_add_val(a.md, a.root, "names", arr);
462+ }
463+ run_tool("open_nodes", a.md, a.root);
464+ args_free(&a);
465+}
466+
467+static void do_add_entity(const char *qs)
468+{
469+ char name[SX_NAME_MAX * 2], type[SX_TYPE_MAX * 2];
470+ args_t a;
471+ yyjson_mut_val *ents, *ent;
472+ yyjson_val *bobs;
473+
474+ if (!param_str(qs, "name", name, sizeof name) || !name[0]) {
475+ json_err(400, "missing name"); return;
476+ }
477+ if (!param_str(qs, "entityType", type, sizeof type) || !type[0]) {
478+ json_err(400, "missing entityType"); return;
479+ }
480+ args_init(&a);
481+ ents = yyjson_mut_arr(a.md);
482+ ent = yyjson_mut_obj(a.md);
483+ yyjson_mut_obj_add_strcpy(a.md, ent, "name", name);
484+ yyjson_mut_obj_add_strcpy(a.md, ent, "entityType", type);
485+ bobs = body_arr("observations");
486+ if (!bobs) {
487+ char obs[OBS_TEXT_MAX * 4];
488+ if (param_str(qs, "observations", obs, sizeof obs)) {
489+ const char *p = obs;
490+ yyjson_mut_val *arr = yyjson_mut_arr(a.md);
491+ while (*p) {
492+ const char *s = strchr(p, '|');
493+ size_t len = s ? (size_t)(s - p) : strlen(p);
494+ char tmp[OBS_TEXT_MAX];
495+ if (len >= sizeof tmp) len = sizeof tmp - 1;
496+ memcpy(tmp, p, len);
497+ tmp[len] = '\0';
498+ if (*tmp) yyjson_mut_arr_add_strcpy(a.md, arr, tmp);
499+ if (!s) break;
500+ p = s + 1;
501+ }
502+ yyjson_mut_obj_add_val(a.md, ent, "observations", arr);
503+ } else {
504+ yyjson_mut_obj_add_val(a.md, ent, "observations",
505+ yyjson_mut_arr(a.md));
506+ }
507+ } else {
508+ yyjson_mut_val *arr = yyjson_mut_arr(a.md);
509+ size_t i, n = yyjson_arr_size(bobs);
510+ for (i = 0; i < n; i++) {
511+ yyjson_val *v = yyjson_arr_get(bobs, i);
512+ if (v && yyjson_is_str(v))
513+ yyjson_mut_arr_add_strcpy(a.md, arr, yyjson_get_str(v));
514+ }
515+ yyjson_mut_obj_add_val(a.md, ent, "observations", arr);
516+ }
517+ yyjson_mut_arr_add_val(ents, ent);
518+ yyjson_mut_obj_add_val(a.md, a.root, "entities", ents);
519+ run_tool("create_entities", a.md, a.root);
520+ args_free(&a);
521+}
522+
523+static void do_add_relation(const char *qs)
524+{
525+ char from[SX_NAME_MAX * 2], to[SX_NAME_MAX * 2], type[SX_TYPE_MAX * 2];
526+ args_t a;
527+ yyjson_mut_val *rels, *rel;
528+
529+ if (!param_str(qs, "from", from, sizeof from) || !from[0]) {
530+ json_err(400, "missing from"); return;
531+ }
532+ if (!param_str(qs, "to", to, sizeof to) || !to[0]) {
533+ json_err(400, "missing to"); return;
534+ }
535+ if (!param_str(qs, "relationType", type, sizeof type) || !type[0]) {
536+ json_err(400, "missing relationType"); return;
537+ }
538+ args_init(&a);
539+ rels = yyjson_mut_arr(a.md);
540+ rel = yyjson_mut_obj(a.md);
541+ yyjson_mut_obj_add_strcpy(a.md, rel, "from", from);
542+ yyjson_mut_obj_add_strcpy(a.md, rel, "to", to);
543+ yyjson_mut_obj_add_strcpy(a.md, rel, "relationType", type);
544+ yyjson_mut_arr_add_val(rels, rel);
545+ yyjson_mut_obj_add_val(a.md, a.root, "relations", rels);
546+ run_tool("create_relations", a.md, a.root);
547+ args_free(&a);
548+}
549+
550+static void do_add_obs(const char *qs)
551+{
552+ char name[SX_NAME_MAX * 2];
553+ args_t a;
554+ yyjson_mut_val *obs, *one, *arr;
555+ yyjson_val *bcontents;
556+
557+ if (!param_str(qs, "name", name, sizeof name) || !name[0]) {
558+ json_err(400, "missing name"); return;
559+ }
560+ args_init(&a);
561+ obs = yyjson_mut_arr(a.md);
562+ one = yyjson_mut_obj(a.md);
563+ arr = yyjson_mut_arr(a.md);
564+ yyjson_mut_obj_add_strcpy(a.md, one, "entityName", name);
565+
566+ bcontents = body_arr("contents");
567+ if (bcontents) {
568+ size_t i, n = yyjson_arr_size(bcontents);
569+ for (i = 0; i < n; i++) {
570+ yyjson_val *v = yyjson_arr_get(bcontents, i);
571+ if (v && yyjson_is_str(v))
572+ yyjson_mut_arr_add_strcpy(a.md, arr, yyjson_get_str(v));
573+ }
574+ } else {
575+ char contents[OBS_TEXT_MAX * 4];
576+ if (param_str(qs, "contents", contents, sizeof contents)) {
577+ const char *p = contents;
578+ while (*p) {
579+ const char *s = strchr(p, '|');
580+ size_t len = s ? (size_t)(s - p) : strlen(p);
581+ char tmp[OBS_TEXT_MAX];
582+ if (len >= sizeof tmp) len = sizeof tmp - 1;
583+ memcpy(tmp, p, len);
584+ tmp[len] = '\0';
585+ if (*tmp) yyjson_mut_arr_add_strcpy(a.md, arr, tmp);
586+ if (!s) break;
587+ p = s + 1;
588+ }
589+ }
590+ }
591+ yyjson_mut_obj_add_val(a.md, one, "contents", arr);
592+ yyjson_mut_arr_add_val(obs, one);
593+ yyjson_mut_obj_add_val(a.md, a.root, "observations", obs);
594+ run_tool("add_observations", a.md, a.root);
595+ args_free(&a);
596+}
597+
598+static void do_delete_entity(const char *qs)
599+{
600+ char name[SX_NAME_MAX * 2];
601+ args_t a;
602+ yyjson_mut_val *arr;
603+
604+ if (!param_str(qs, "name", name, sizeof name) || !name[0]) {
605+ json_err(400, "missing name"); return;
606+ }
607+ args_init(&a);
608+ arr = yyjson_mut_arr(a.md);
609+ yyjson_mut_arr_add_strcpy(a.md, arr, name);
610+ yyjson_mut_obj_add_val(a.md, a.root, "entityNames", arr);
611+ run_tool("delete_entities", a.md, a.root);
612+ args_free(&a);
613+}
614+
615+static void do_delete_relation(const char *qs)
616+{
617+ char from[SX_NAME_MAX * 2], to[SX_NAME_MAX * 2], type[SX_TYPE_MAX * 2];
618+ args_t a;
619+ yyjson_mut_val *rels, *rel;
620+
621+ if (!param_str(qs, "from", from, sizeof from) || !from[0] ||
622+ !param_str(qs, "to", to, sizeof to) || !to[0] ||
623+ !param_str(qs, "relationType", type, sizeof type) || !type[0]) {
624+ json_err(400, "from, to and relationType are all required");
625+ return;
626+ }
627+ args_init(&a);
628+ rels = yyjson_mut_arr(a.md);
629+ rel = yyjson_mut_obj(a.md);
630+ yyjson_mut_obj_add_strcpy(a.md, rel, "from", from);
631+ yyjson_mut_obj_add_strcpy(a.md, rel, "to", to);
632+ yyjson_mut_obj_add_strcpy(a.md, rel, "relationType", type);
633+ yyjson_mut_arr_add_val(rels, rel);
634+ yyjson_mut_obj_add_val(a.md, a.root, "relations", rels);
635+ run_tool("delete_relations", a.md, a.root);
636+ args_free(&a);
637+}
638+
639+static void do_delete_obs(const char *qs)
640+{
641+ char name[SX_NAME_MAX * 2];
642+ args_t a;
643+ yyjson_mut_val *deletions, *one, *arr;
644+ yyjson_val *bobs;
645+
646+ if (!param_str(qs, "name", name, sizeof name) || !name[0]) {
647+ json_err(400, "missing name"); return;
648+ }
649+ args_init(&a);
650+ deletions = yyjson_mut_arr(a.md);
651+ one = yyjson_mut_obj(a.md);
652+ arr = yyjson_mut_arr(a.md);
653+ yyjson_mut_obj_add_strcpy(a.md, one, "entityName", name);
654+
655+ bobs = body_arr("observations");
656+ if (bobs) {
657+ size_t i, n = yyjson_arr_size(bobs);
658+ for (i = 0; i < n; i++) {
659+ yyjson_val *v = yyjson_arr_get(bobs, i);
660+ if (v && yyjson_is_str(v))
661+ yyjson_mut_arr_add_strcpy(a.md, arr, yyjson_get_str(v));
662+ }
663+ } else {
664+ char obs[OBS_TEXT_MAX * 4];
665+ if (param_str(qs, "observations", obs, sizeof obs)) {
666+ const char *p = obs;
667+ while (*p) {
668+ const char *s = strchr(p, '|');
669+ size_t len = s ? (size_t)(s - p) : strlen(p);
670+ char tmp[OBS_TEXT_MAX];
671+ if (len >= sizeof tmp) len = sizeof tmp - 1;
672+ memcpy(tmp, p, len);
673+ tmp[len] = '\0';
674+ if (*tmp) yyjson_mut_arr_add_strcpy(a.md, arr, tmp);
675+ if (!s) break;
676+ p = s + 1;
677+ }
678+ }
679+ }
680+ yyjson_mut_obj_add_val(a.md, one, "observations", arr);
681+ yyjson_mut_arr_add_val(deletions, one);
682+ yyjson_mut_obj_add_val(a.md, a.root, "deletions", deletions);
683+ run_tool("delete_observations", a.md, a.root);
684+ args_free(&a);
685+}
686+
687+/* The raw JSONL, for an operator who wants to diff or back up the graph.
688+ * Served as text/plain with a filename so the browser offers a download. */
689+static void do_export(void)
690+{
691+ char *text;
692+ size_t len = 0;
693+ const char *p = graph_path();
694+
695+ if (graph_load() != 0) { json_err(500, g_data_err); return; }
696+ {
697+ FILE *f = (p && *p) ? fopen(p, "rb") : NULL;
698+ text = NULL;
699+ if (f) {
700+ long sz;
701+ fseek(f, 0, SEEK_END);
702+ sz = ftell(f);
703+ if (sz < 0) sz = 0;
704+ if ((size_t)sz > (size_t)FILE_MAX) sz = (long)FILE_MAX;
705+ if (sz > 0) fseek(f, 0, SEEK_SET);
706+ text = (char *)malloc((size_t)sz + 1);
707+ if (text) len = fread(text, 1, (size_t)sz, f);
708+ text[len] = '\0';
709+ fclose(f);
710+ }
711+ }
712+
713+ fputs("Content-Type: text/plain; charset=utf-8\r\n"
714+ "Cache-Control: no-store\r\n"
715+ "X-Content-Type-Options: nosniff\r\n"
716+ "Content-Disposition: attachment; filename=\"memory.jsonl\"\r\n\r\n",
717+ stdout);
718+ if (text && len) fwrite(text, 1, len, stdout);
719+ free(text);
720+ fflush(stdout);
721+}
722+
723+/* tools/list over HTTP - the same schemas an MCP host gets, so the Setup UI
724+ * and an agent can never disagree about what this connector offers. */
725+static void do_tools(void)
726+{
727+ char *t = tools_list_json();
728+ buf_t b;
729+ buf_init(&b);
730+ buf_puts(&b, "{\"ok\":true,\"connector\":\"" PLUGIN_ID
731+ "\",\"kind\":\"mcp\",\"protocol\":\"" MCP_PROTOCOL
732+ "\",\"tools\":");
733+ buf_puts(&b, t ? t : "[]");
734+ buf_puts(&b, "}");
735+ json_raw(buf_str(&b));
736+ buf_free(&b);
737+ free(t);
738+}
739+
740+/* ------------------------------------------------------------------ */
741+/* The page */
742+/* ------------------------------------------------------------------ */
743+
744+static void emit_ui(void)
745+{
746+ const char *p = UI_HTML;
747+
748+ while (*p) {
749+ if (*p == '\001') {
750+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS
751+ "</style>", stdout);
752+ p++;
753+ } else if (*p == '\002') {
754+ fputs(SX_BOT_THEME_HANDOFF, stdout);
755+ p++;
756+ } else {
757+ putchar(*p++);
758+ }
759+ }
760+}
761+
762+static void mode_html(void)
763+{
764+ fputs("Content-Type: text/html; charset=utf-8\r\n"
765+ "Cache-Control: no-store\r\n"
766+ "X-Content-Type-Options: nosniff\r\n"
767+ "X-Frame-Options: SAMEORIGIN\r\n"
768+ "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
769+ "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
770+ "form-action 'none'; base-uri 'none'\r\n\r\n", stdout);
771+ emit_ui();
772+}
773+
774+/* ------------------------------------------------------------------ */
775+/* Entry */
776+/* ------------------------------------------------------------------ */
777+
778+static const char *method(void)
779+{
780+ const char *m = getenv("REQUEST_METHOD");
781+ return (m && *m) ? m : "GET";
782+}
783+
784+int api_handle(void)
785+{
786+ const char *qs = getenv("QUERY_STRING");
787+ char action[64], act[64], fmt[32];
788+ int got;
789+
790+ if (!qs) qs = "";
791+ action[0] = '\0';
792+ act[0] = '\0';
793+ fmt[0] = '\0';
794+
795+ require_node_auth();
796+
797+ got = read_request_body();
798+ if (got < 0) { json_err(413, "the request body is too large"); return 0; }
799+ if (got > 0) {
800+ g_body_doc = yyjson_read(g_body, strlen(g_body), 0);
801+ if (!g_body_doc) {
802+ json_err(400, "the request body is not valid JSON");
803+ return 0;
804+ }
805+ }
806+
807+ /* Two buffers on purpose: parsing `format` into `action` would clobber the
808+ * action we just parsed and silently answer the default one. */
809+ if (!get_query_val(qs, "action", action, sizeof action)) {
810+ if (param_str(qs, "action", action, sizeof action)) { /* body action */ }
811+ }
812+ if (!action[0]) {
813+ if (get_query_val(qs, "format", fmt, sizeof fmt) &&
814+ strcmp(fmt, "json") == 0)
815+ str_copy(action, sizeof action, "graph");
816+ else if (strcmp(method(), "POST") == 0) {
817+ json_err(400, "missing action");
818+ return 0;
819+ }
820+ }
821+ str_copy(act, sizeof act, action);
822+
823+ if (act[0]) {
824+ if (strcmp(act, "stats") == 0) { do_stats(qs); }
825+ else if (strcmp(act, "graph") == 0) { do_graph(qs); }
826+ else if (strcmp(act, "search") == 0) { do_search(qs); }
827+ else if (strcmp(act, "entity") == 0) { do_entity(qs); }
828+ else if (strcmp(act, "add_entity") == 0) { do_add_entity(qs); }
829+ else if (strcmp(act, "add_relation") == 0){ do_add_relation(qs); }
830+ else if (strcmp(act, "add_obs") == 0) { do_add_obs(qs); }
831+ else if (strcmp(act, "delete_entity") == 0) { do_delete_entity(qs); }
832+ else if (strcmp(act, "delete_relation") == 0) { do_delete_relation(qs); }
833+ else if (strcmp(act, "delete_obs") == 0) { do_delete_obs(qs); }
834+ else if (strcmp(act, "tools") == 0) { do_tools(); }
835+ else if (strcmp(act, "export") == 0) { do_export(); }
836+ else json_err(400, "unknown action");
837+ if (g_body_doc) yyjson_doc_free(g_body_doc);
838+ return 0;
839+ }
840+
841+ mode_html();
842+ if (g_body_doc) yyjson_doc_free(g_body_doc);
843+ return 0;
844+}
src/bot_theme_plugin.h+129−0■■■■■
11new file mode 100644
index 0000000..0dd243b
--- /dev/null
+++ b/src/bot_theme_plugin.h
@@ -0,0 +1,129 @@
1+/*
2+ * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins.
3+ *
4+ * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of
5+ * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session
6+ * Card modal, Chat floating window) or in its own tab, and in every case it
7+ * must look like part of the bot: same tokens, same dark/light pair, same
8+ * localStorage key, same prepaint order.
9+ *
10+ * Three rules, and nothing else:
11+ *
12+ * 1. Colours come from these tokens only. No plugin-private palette.
13+ * 2. The theme is decided BEFORE first paint, in this order:
14+ * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme
15+ * so a plugin opened from the bot paints in the bot's theme from frame 0.
16+ * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into
17+ * this window; the plugin follows without a reload. The plugin asks once
18+ * with {type:'sx-theme-request'} at startup, which covers the case where
19+ * it was already open when the bot changed theme.
20+ *
21+ * The bottom of :root carries aliases for the names older plugin CSS already
22+ * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn,
23+ * --ok), so adopting the bot palette is a swap, not a redesign. Because they
24+ * are var() references, one definition covers both themes.
25+ *
26+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
27+ */
28+#ifndef SX_BOT_THEME_PLUGIN_H
29+#define SX_BOT_THEME_PLUGIN_H
30+
31+/* Dark is the default; light is applied by html[data-theme=light] (chosen by
32+ * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */
33+#define SX_BOT_THEME_TOKENS \
34+":root{color-scheme:dark;" \
35+ "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \
36+ "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \
37+ "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \
38+ "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \
39+ "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \
40+ "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \
41+ "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \
42+ "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \
43+ "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \
44+ "--shadow:0 1px 2px rgba(0,0,0,.35);" \
45+ "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \
46+ "--ease:cubic-bezier(.16,1,.3,1);" \
47+ "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \
48+ "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \
49+ "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \
50+"}" \
51+"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \
52+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
53+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
54+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
55+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
56+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
57+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
58+ "--accent-dim:#0066d6;" \
59+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
60+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
61+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
62+ "color-scheme:light}}" \
63+"html[data-theme=light]{" \
64+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
65+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
66+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
67+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
68+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
69+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
70+ "--accent-dim:#0066d6;" \
71+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
72+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
73+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
74+ "color-scheme:light}" \
75+"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \
76+"*{box-sizing:border-box}" \
77+"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \
78+ "-webkit-font-smoothing:antialiased}" \
79+"button{font-family:inherit;letter-spacing:inherit}" \
80+"button:active{transform:scale(.98)}" \
81+"select option{background:var(--menu-bg);color:var(--text)}" \
82+"a{color:var(--blue);text-decoration:none;font-weight:600}" \
83+"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \
84+" * hides its own back link and its own toggle. */" \
85+"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \
86+"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}"
87+
88+/* Pre-paint: decide the theme before the first frame. Must be the first thing
89+ * in <head> so there is no flash of the wrong theme. Also flags embed mode as
90+ * html.embedded so the embed rules apply before first paint. */
91+#define SX_BOT_THEME_PREPAINT \
92+"<script>(function(){var t='';" \
93+"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \
94+"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \
95+"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \
96+"document.documentElement.setAttribute('data-theme',t);" \
97+"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \
98+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
99+"})();</script>\n"
100+
101+/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once
102+ * at startup in case it changed while this page was already open. Fires the
103+ * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can
104+ * re-skin themselves from one listener. */
105+#define SX_BOT_THEME_HANDOFF \
106+"<script>(function(){" \
107+"function apply(t){if(t!=='light'&&t!=='dark')return;" \
108+"if(document.documentElement.getAttribute('data-theme')===t)return;" \
109+"document.documentElement.setAttribute('data-theme',t);" \
110+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
111+"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \
112+"window.sxApplyTheme=apply;" \
113+"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \
114+"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \
115+"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \
116+"})();</script>\n"
117+
118+/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when
119+ * the plugin is opened in its own tab; inside the bot the host owns the theme.
120+ * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */
121+#define SX_BOT_THEME_TOGGLE_BTN \
122+"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>"
123+
124+#define SX_BOT_THEME_TOGGLE_JS \
125+"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \
126+"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \
127+"})();</script>\n"
128+
129+#endif /* SX_BOT_THEME_PLUGIN_H */
src/graph.c+942−0■■■■■
11new file mode 100644
index 0000000..3e4e898
--- /dev/null
+++ b/src/graph.c
@@ -0,0 +1,942 @@
1+/*
2+ * graph.c - storage engine for plugin_memory.
3+ *
4+ * The graph is one JSONL file: one JSON object per line, tagged
5+ * {"type":"entity",...} or {"type":"relation",...}. This file owns the
6+ * location of that file, the loader, the atomic writer, the in-memory store
7+ * and the little utilities the other units share.
8+ *
9+ * Two properties are load-bearing:
10+ *
11+ * 1. A save stages a temp file in the SAME directory (so the rename stays
12+ * on one filesystem), fsyncs it, restores the target's permission bits
13+ * and renames it over the graph. A kill -9 halfway through leaves the
14+ * previous graph intact and a stray .tmp behind - never a truncated
15+ * graph. The temp file is removed on every failure path.
16+ *
17+ * 2. A line the loader cannot parse is not dropped. It is kept verbatim in
18+ * G.bad and written back unchanged, so a hand-edited or half-imported
19+ * graph survives a round trip. Silently losing someone's data would be
20+ * worse than reporting it, so the count is also reported in stats.
21+ *
22+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
23+ */
24+
25+#if defined(_WIN32) && !defined(_WIN32_WINNT)
26+# define _WIN32_WINNT 0x0601
27+#endif
28+
29+#if !defined(_WIN32)
30+# define _POSIX_C_SOURCE 200809L
31+# define _DEFAULT_SOURCE 1
32+# if defined(__APPLE__)
33+# define _DARWIN_C_SOURCE 1
34+# endif
35+#endif
36+
37+#include <stdio.h>
38+#include <stdlib.h>
39+#include <string.h>
40+#include <ctype.h>
41+#include <errno.h>
42+#include <time.h>
43+#include <stdarg.h>
44+
45+#if defined(_WIN32)
46+# define WIN32_LEAN_AND_MEAN
47+# include <windows.h>
48+# include <direct.h>
49+# include <io.h>
50+# include <sys/stat.h>
51+# include <sys/types.h>
52+#else
53+# include <unistd.h>
54+# include <fcntl.h>
55+# include <sys/stat.h>
56+# include <sys/types.h>
57+#endif
58+
59+#include "memory.h"
60+
61+/* ------------------------------------------------------------------ */
62+/* Growable byte buffer */
63+/* ------------------------------------------------------------------ */
64+
65+void buf_init(buf_t *b)
66+{
67+ b->p = NULL;
68+ b->n = 0;
69+ b->cap = 0;
70+}
71+
72+int buf_need(buf_t *b, size_t extra)
73+{
74+ size_t want = b->n + extra + 1;
75+ char *np;
76+ if (want <= b->cap) return 1;
77+ if (b->cap == 0) b->cap = 1024;
78+ while (b->cap < want) {
79+ if (b->cap > (size_t)128 * 1024 * 1024) return 0; /* hard ceiling */
80+ b->cap *= 2;
81+ }
82+ np = (char *)realloc(b->p, b->cap);
83+ if (!np) return 0;
84+ b->p = np;
85+ return 1;
86+}
87+
88+void buf_add(buf_t *b, const char *s, size_t n)
89+{
90+ if (!s || n == 0) return;
91+ if (!buf_need(b, n)) return;
92+ memcpy(b->p + b->n, s, n);
93+ b->n += n;
94+ b->p[b->n] = '\0';
95+}
96+
97+void buf_puts(buf_t *b, const char *s)
98+{
99+ if (s) buf_add(b, s, strlen(s));
100+}
101+
102+void buf_putc(buf_t *b, int c)
103+{
104+ char ch = (char)c;
105+ buf_add(b, &ch, 1);
106+}
107+
108+const char *buf_str(const buf_t *b)
109+{
110+ return b->p ? b->p : "";
111+}
112+
113+void buf_free(buf_t *b)
114+{
115+ free(b->p);
116+ b->p = NULL;
117+ b->n = b->cap = 0;
118+}
119+
120+/* ------------------------------------------------------------------ */
121+/* Small helpers */
122+/* ------------------------------------------------------------------ */
123+
124+void str_copy(char *dst, size_t dsz, const char *src)
125+{
126+ size_t i;
127+ if (!dst || dsz == 0) return;
128+ dst[0] = '\0';
129+ if (!src) return;
130+ for (i = 0; i + 1 < dsz && src[i]; i++) dst[i] = src[i];
131+ dst[i] = '\0';
132+}
133+
134+/* Case-insensitive substring: the reference search is a plain includes()
135+ * over lower-cased fields, so this is the whole matching rule. */
136+int str_icontains(const char *hay, const char *needle)
137+{
138+ if (!needle || !*needle) return 1;
139+ if (!hay) return 0;
140+ for (; *hay; hay++) {
141+ const char *h = hay, *n = needle;
142+ while (*h && *n &&
143+ tolower((unsigned char)*h) == tolower((unsigned char)*n)) {
144+ h++; n++;
145+ }
146+ if (!*n) return 1;
147+ }
148+ return 0;
149+}
150+
151+void json_str(buf_t *b, const char *s)
152+{
153+ buf_putc(b, '"');
154+ if (s) {
155+ for (; *s; s++) {
156+ unsigned char c = (unsigned char)*s;
157+ if (c == '"') buf_puts(b, "\\\"");
158+ else if (c == '\\') buf_puts(b, "\\\\");
159+ else if (c == '\n') buf_puts(b, "\\n");
160+ else if (c == '\r') buf_puts(b, "\\r");
161+ else if (c == '\t') buf_puts(b, "\\t");
162+ else if (c == '\b') buf_puts(b, "\\b");
163+ else if (c == '\f') buf_puts(b, "\\f");
164+ else if (c < 0x20) {
165+ char tmp[8];
166+ snprintf(tmp, sizeof tmp, "\\u%04x", (unsigned)c);
167+ buf_puts(b, tmp);
168+ } else buf_putc(b, (char)c);
169+ }
170+ }
171+ buf_putc(b, '"');
172+}
173+
174+char *dup_or_null(const char *s)
175+{
176+ char *p;
177+ size_t n;
178+ if (!s) return NULL;
179+ n = strlen(s);
180+ p = (char *)malloc(n + 1);
181+ if (!p) return NULL;
182+ memcpy(p, s, n + 1);
183+ return p;
184+}
185+
186+int env_int(const char *name, int dflt, int lo, int hi)
187+{
188+ const char *v = getenv(name);
189+ long n;
190+ char *end;
191+ if (!v || !*v) return dflt;
192+ errno = 0;
193+ n = strtol(v, &end, 10);
194+ if (end == v || errno != 0) return dflt;
195+ if (n < lo) n = lo;
196+ if (n > hi) n = hi;
197+ return (int)n;
198+}
199+
200+/* ------------------------------------------------------------------ */
201+/* Filesystem helpers */
202+/* ------------------------------------------------------------------ */
203+
204+static int file_exists_p(const char *p)
205+{
206+ struct stat st;
207+ return p && *p && stat(p, &st) == 0;
208+}
209+
210+static int is_dir_p(const char *p)
211+{
212+ struct stat st;
213+ return p && *p && stat(p, &st) == 0 && S_ISDIR(st.st_mode);
214+}
215+
216+static void path_join(char *out, size_t osz, const char *a, const char *b)
217+{
218+ size_t la;
219+ if (!a || !*a) { str_copy(out, osz, b ? b : ""); return; }
220+ la = strlen(a);
221+ if (a[la - 1] == '/' || a[la - 1] == '\\')
222+ snprintf(out, osz, "%s%s", a, b ? b : "");
223+ else
224+ snprintf(out, osz, "%s/%s", a, b ? b : "");
225+}
226+
227+/* mkdir -p with 0700 - the graph holds the operator's notes about their own
228+ * projects, so it is never world-readable. Returns 1 when it exists after. */
229+static int mkdirs(const char *path)
230+{
231+ char tmp[PATH_SZ];
232+ size_t i, n;
233+
234+ if (!path || !*path) return 0;
235+ if (is_dir_p(path)) return 1;
236+ str_copy(tmp, sizeof tmp, path);
237+ n = strlen(tmp);
238+ while (n > 1 && (tmp[n - 1] == '/' || tmp[n - 1] == '\\')) tmp[--n] = '\0';
239+
240+ for (i = 1; i < n; i++) {
241+ if (tmp[i] == '/' || tmp[i] == '\\') {
242+ char save = tmp[i];
243+ tmp[i] = '\0';
244+ if (!is_dir_p(tmp)) {
245+#if defined(_WIN32)
246+ (void)_mkdir(tmp);
247+#else
248+ (void)mkdir(tmp, 0700);
249+#endif
250+ }
251+ tmp[i] = save;
252+ }
253+ }
254+ if (!is_dir_p(tmp)) {
255+#if defined(_WIN32)
256+ (void)_mkdir(tmp);
257+#else
258+ (void)mkdir(tmp, 0700);
259+#endif
260+ }
261+ return is_dir_p(tmp);
262+}
263+
264+static char *read_file_all(const char *path, size_t *len_out)
265+{
266+ FILE *f;
267+ long sz;
268+ char *mem;
269+ size_t got;
270+
271+ if (len_out) *len_out = 0;
272+ if (!path || !*path) return NULL;
273+ f = fopen(path, "rb");
274+ if (!f) return NULL;
275+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
276+ sz = ftell(f);
277+ if (sz < 0) { fclose(f); return NULL; }
278+ if ((size_t)sz > (size_t)FILE_MAX) { fclose(f); return NULL; }
279+ if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
280+ mem = (char *)malloc((size_t)sz + 1);
281+ if (!mem) { fclose(f); return NULL; }
282+ got = fread(mem, 1, (size_t)sz, f);
283+ fclose(f);
284+ mem[got] = '\0';
285+ if (len_out) *len_out = got;
286+ return mem;
287+}
288+
289+/* ------------------------------------------------------------------ */
290+/* Where the graph lives */
291+/* ------------------------------------------------------------------ */
292+
293+static void connector_dir(char *out, size_t osz)
294+{
295+ const char *env;
296+ struct stat st;
297+
298+ env = getenv("MEMORY_CONNECTOR_DIR");
299+ if (env && *env) { str_copy(out, osz, env); return; }
300+
301+ /* BotCloud containers lose their rootfs on stop -> start, so /workspace
302+ * is the durable place and wins whenever it exists. */
303+ if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode)) {
304+ str_copy(out, osz, "/workspace/.scorpiox/connectors/" PLUGIN_ID);
305+ return;
306+ }
307+#if defined(_WIN32)
308+ {
309+ const char *la = getenv("LOCALAPPDATA");
310+ if (la && *la) {
311+ snprintf(out, osz, "%s\\scorpiox\\connectors\\%s", la, PLUGIN_ID);
312+ return;
313+ }
314+ }
315+#endif
316+ env = getenv("HOME");
317+ if (!env || !*env) env = ".";
318+ snprintf(out, osz, "%s/.scorpiox/connectors/%s", env, PLUGIN_ID);
319+}
320+
321+static void expand_home(char *out, size_t osz, const char *in)
322+{
323+ const char *h;
324+ if (!in) { out[0] = '\0'; return; }
325+ h = getenv("HOME");
326+ if (strcmp(in, "~") == 0) { str_copy(out, osz, (h && *h) ? h : "."); return; }
327+ if (in[0] == '~' && (in[1] == '/' || in[1] == '\\')) {
328+ snprintf(out, osz, "%s%s", (h && *h) ? h : ".", in + 1);
329+ return;
330+ }
331+ str_copy(out, osz, in);
332+}
333+
334+static int path_is_abs(const char *p)
335+{
336+ if (!p || !*p) return 0;
337+ if (p[0] == '/') return 1;
338+#if defined(_WIN32)
339+ if (p[0] == '\\' || (isalpha((unsigned char)p[0]) && p[1] == ':')) return 1;
340+#endif
341+ return 0;
342+}
343+
344+static char g_path[PATH_SZ];
345+static int g_path_resolved;
346+
347+/* Resolve the graph path and create its parent. 1 on success. */
348+static int ensure_path(void)
349+{
350+ const char *env;
351+ char dir[PATH_SZ];
352+ char cand[PATH_SZ];
353+
354+ if (g_path_resolved) return 1;
355+
356+ connector_dir(dir, sizeof dir);
357+ env = getenv("MEMORY_FILE_PATH");
358+
359+ if (env && *env) {
360+ const char *slash;
361+ expand_home(cand, sizeof cand, env);
362+ if (path_is_abs(cand)) {
363+ char d[PATH_SZ];
364+ size_t dn;
365+ slash = strrchr(cand, '/');
366+#if defined(_WIN32)
367+ { const char *bs = strrchr(cand, '\\');
368+ if (!slash || (bs && bs > slash)) slash = bs; }
369+#endif
370+ if (!slash) {
371+ str_copy(g_data_err, sizeof g_data_err,
372+ "MEMORY_FILE_PATH must name a file, not a bare name");
373+ return 0;
374+ }
375+ dn = (size_t)(slash - cand);
376+ if (dn == 0) dn = 1; /* keep the root slash */
377+ if (dn >= sizeof d) dn = sizeof d - 1;
378+ memcpy(d, cand, dn);
379+ d[dn] = '\0';
380+ if (!mkdirs(d)) {
381+ str_copy(g_data_err, sizeof g_data_err,
382+ "cannot create the directory for MEMORY_FILE_PATH");
383+ return 0;
384+ }
385+ str_copy(g_path, sizeof g_path, cand);
386+ g_path_resolved = 1;
387+ return 1;
388+ }
389+ /* A relative MEMORY_FILE_PATH lands inside the connector dir, exactly
390+ * like the reference server resolving against its package dir. */
391+ if (strstr(cand, "..")) {
392+ str_copy(g_data_err, sizeof g_data_err,
393+ "MEMORY_FILE_PATH may not contain '..'");
394+ return 0;
395+ }
396+ if (!mkdirs(dir)) {
397+ str_copy(g_data_err, sizeof g_data_err,
398+ "cannot create the connector data directory");
399+ return 0;
400+ }
401+ path_join(g_path, sizeof g_path, dir, cand);
402+ g_path_resolved = 1;
403+ return 1;
404+ }
405+
406+ if (!mkdirs(dir)) {
407+ str_copy(g_data_err, sizeof g_data_err,
408+ "cannot create the connector data directory");
409+ return 0;
410+ }
411+ path_join(g_path, sizeof g_path, dir, "memory.jsonl");
412+ g_path_resolved = 1;
413+ return 1;
414+}
415+
416+const char *graph_path(void)
417+{
418+ if (!g_path_resolved && !ensure_path()) return "";
419+ return g_path;
420+}
421+
422+int graph_path_info(long long *size, int *exists)
423+{
424+ struct stat st;
425+ const char *p = graph_path();
426+ if (size) *size = 0;
427+ if (exists) *exists = 0;
428+ if (!p || !*p) return -1;
429+ if (stat(p, &st) != 0) return 0;
430+ if (exists) *exists = 1;
431+ if (size) *size = (long long)st.st_size;
432+ return 0;
433+}
434+
435+/* ------------------------------------------------------------------ */
436+/* A best-effort cross-process lock */
437+/* */
438+/* Every mutation is a read-modify-write of the whole file, so two */
439+/* concurrent agents could otherwise lose one of their writes. The */
440+/* reference server uses an O_EXCL lock file with a stale-break; this */
441+/* is the same idea in twenty lines. It is deliberately best-effort: */
442+/* if the lock cannot be taken we still serve the request, because */
443+/* losing a node's memory over a stuck lock file is the worse failure. */
444+/* ------------------------------------------------------------------ */
445+
446+static int g_lock_fd = -1;
447+static char g_lock_path[PATH_SZ + SUFFIX_SZ];
448+
449+static void lock_remove(void)
450+{
451+ if (g_lock_path[0]) {
452+#if defined(_WIN32)
453+ _unlink(g_lock_path);
454+#else
455+ unlink(g_lock_path);
456+#endif
457+ g_lock_path[0] = '\0';
458+ }
459+}
460+
461+static int lock_try_once(void)
462+{
463+ int fd;
464+ long stale_ms;
465+ struct stat st;
466+ time_t now;
467+
468+ snprintf(g_lock_path, sizeof g_lock_path, "%s.lock", graph_path());
469+
470+ /* Break a lock left behind by a killed process. */
471+ if (stat(g_lock_path, &st) == 0) {
472+ stale_ms = (long)env_int("MEMORY_LOCK_STALE_MS", 10000, 100, 600000);
473+ time(&now);
474+ if ((long)(now - st.st_mtime) * 1000 > stale_ms) lock_remove();
475+ }
476+
477+#if defined(_WIN32)
478+ fd = _open(g_lock_path, _O_CREAT | _O_EXCL | _O_WRONLY | _O_BINARY, _S_IREAD | _S_IWRITE);
479+#else
480+ fd = open(g_lock_path, O_CREAT | O_EXCL | O_WRONLY, 0600);
481+#endif
482+ if (fd < 0) return -1;
483+ {
484+ char pid[32];
485+ int n = snprintf(pid, sizeof pid, "%ld\n", (long)
486+#if defined(_WIN32)
487+ GetCurrentProcessId()
488+#else
489+ (long)getpid()
490+#endif
491+ );
492+ if (n > 0) {
493+#if defined(_WIN32)
494+ ssize_t w = _write(fd, pid, (unsigned)n);
495+#else
496+ ssize_t w = write(fd, pid, (size_t)n);
497+#endif
498+ (void)w;
499+ }
500+ }
501+#if defined(_WIN32)
502+ _close(fd);
503+#else
504+ close(fd);
505+#endif
506+ g_lock_fd = 0;
507+ return 0;
508+}
509+
510+void graph_lock(void)
511+{
512+ int tries, timeout_ms;
513+ if (!ensure_path()) return;
514+ timeout_ms = env_int("MEMORY_LOCK_TIMEOUT_MS", 2000, 0, 30000);
515+ tries = timeout_ms / 10 + 1;
516+ while (tries-- > 0) {
517+ if (lock_try_once() == 0) return;
518+#if defined(_WIN32)
519+ Sleep(10);
520+#else
521+ { struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 10 * 1000 * 1000L;
522+ nanosleep(&ts, NULL); }
523+#endif
524+ }
525+ /* Best effort: proceed unlocked rather than failing the user's write. */
526+ g_lock_path[0] = '\0';
527+}
528+
529+void graph_unlock(void)
530+{
531+ if (g_lock_fd == 0) lock_remove();
532+ g_lock_fd = -1;
533+}
534+
535+/* ------------------------------------------------------------------ */
536+/* The store */
537+/* ------------------------------------------------------------------ */
538+
539+graph_t G;
540+char g_data_err[256];
541+
542+static char *dup_or_empty(const char *s)
543+{
544+ return dup_or_null(s ? s : "");
545+}
546+
547+void graph_clear(graph_t *g)
548+{
549+ size_t i, j;
550+ for (i = 0; i < g->n_ent; i++) {
551+ free(g->ent[i].name);
552+ free(g->ent[i].etype);
553+ for (j = 0; j < g->ent[i].n_obs; j++) free(g->ent[i].obs[j]);
554+ free(g->ent[i].obs);
555+ }
556+ free(g->ent);
557+ for (i = 0; i < g->n_rel; i++) {
558+ free(g->rel[i].from);
559+ free(g->rel[i].to);
560+ free(g->rel[i].rtype);
561+ }
562+ free(g->rel);
563+ for (i = 0; i < g->n_bad; i++) free(g->bad[i]);
564+ free(g->bad);
565+ memset(g, 0, sizeof *g);
566+}
567+
568+entity_t *ent_find(graph_t *g, const char *name)
569+{
570+ size_t i;
571+ if (!name) return NULL;
572+ for (i = 0; i < g->n_ent; i++)
573+ if (strcmp(g->ent[i].name, name) == 0) return &g->ent[i];
574+ return NULL;
575+}
576+
577+int ent_add(graph_t *g, const char *name, const char *etype,
578+ char **obs, size_t n_obs, char *err, size_t errsz)
579+{
580+ entity_t *e;
581+ size_t i, cap_obs;
582+
583+ if (g->n_ent >= (size_t)env_int("MEMORY_MAX_ENTITIES",
584+ MAX_ENTITIES_DEFAULT, 1, 2000000)) {
585+ if (err) snprintf(err, errsz,
586+ "The graph is at its entity limit; delete entities "
587+ "before adding more.");
588+ return -1;
589+ }
590+ if (!name || !*name || strlen(name) > (size_t)SX_NAME_MAX ||
591+ !etype || !*etype || strlen(etype) > (size_t)SX_TYPE_MAX) {
592+ if (err) snprintf(err, errsz,
593+ "An entity needs a non-empty name and entityType "
594+ "(each at most %d characters).", SX_NAME_MAX);
595+ return -1;
596+ }
597+ if (n_obs > (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT,
598+ 1, 200000))
599+ n_obs = (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT,
600+ 1, 200000);
601+
602+ if (g->n_ent == g->cap_ent) {
603+ size_t nc = g->cap_ent ? g->cap_ent * 2 : 32;
604+ entity_t *nv = (entity_t *)realloc(g->ent, nc * sizeof *nv);
605+ if (!nv) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
606+ g->ent = nv;
607+ g->cap_ent = nc;
608+ }
609+ e = &g->ent[g->n_ent++];
610+ memset(e, 0, sizeof *e);
611+ e->name = dup_or_empty(name);
612+ e->etype = dup_or_empty(etype);
613+ if (!e->name || !e->etype) {
614+ if (err) snprintf(err, errsz, "out of memory");
615+ return -1;
616+ }
617+ cap_obs = n_obs;
618+ if (cap_obs) {
619+ e->obs = (char **)calloc(cap_obs, sizeof *e->obs);
620+ if (!e->obs) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
621+ for (i = 0; i < cap_obs; i++) {
622+ e->obs[i] = dup_or_empty(obs[i] ? obs[i] : "");
623+ if (!e->obs[i]) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
624+ }
625+ e->n_obs = cap_obs;
626+ }
627+ return 0;
628+}
629+
630+int rel_add(graph_t *g, const char *from, const char *to,
631+ const char *rtype, char *err, size_t errsz)
632+{
633+ relation_t *r;
634+
635+ if (g->n_rel >= (size_t)env_int("MEMORY_MAX_RELATIONS",
636+ MAX_RELATIONS_DEFAULT, 1, 4000000)) {
637+ if (err) snprintf(err, errsz,
638+ "The graph is at its relation limit; delete "
639+ "relations before adding more.");
640+ return -1;
641+ }
642+ if (!from || !*from || !to || !*to || !rtype || !*rtype ||
643+ strlen(from) > (size_t)SX_NAME_MAX || strlen(to) > (size_t)SX_NAME_MAX ||
644+ strlen(rtype) > (size_t)SX_TYPE_MAX) {
645+ if (err) snprintf(err, errsz,
646+ "A relation needs non-empty from, to and "
647+ "relationType fields.");
648+ return -1;
649+ }
650+ if (g->n_rel == g->cap_rel) {
651+ size_t nc = g->cap_rel ? g->cap_rel * 2 : 64;
652+ relation_t *nv = (relation_t *)realloc(g->rel, nc * sizeof *nv);
653+ if (!nv) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
654+ g->rel = nv;
655+ g->cap_rel = nc;
656+ }
657+ r = &g->rel[g->n_rel++];
658+ memset(r, 0, sizeof *r);
659+ r->from = dup_or_empty(from);
660+ r->to = dup_or_empty(to);
661+ r->rtype = dup_or_empty(rtype);
662+ if (!r->from || !r->to || !r->rtype) {
663+ if (err) snprintf(err, errsz, "out of memory");
664+ return -1;
665+ }
666+ return 0;
667+}
668+
669+void bad_add(graph_t *g, const char *line)
670+{
671+ size_t cap = (size_t)env_int("MEMORY_MAX_BAD", 5000, 1, 200000);
672+ if (g->n_bad >= cap) { g->truncated = 1; return; }
673+ if (g->n_bad == g->cap_bad) {
674+ size_t nc = g->cap_bad ? g->cap_bad * 2 : 16;
675+ char **nv = (char **)realloc(g->bad, nc * sizeof *nv);
676+ if (!nv) return;
677+ g->bad = nv;
678+ g->cap_bad = nc;
679+ }
680+ g->bad[g->n_bad++] = dup_or_empty(line);
681+}
682+
683+int obs_push(entity_t *e, const char *text)
684+{
685+ char *d;
686+ char **nv;
687+ size_t cap = (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT,
688+ 1, 200000);
689+ if (e->n_obs >= cap) return 0;
690+ d = dup_or_empty(text ? text : "");
691+ if (!d) return 0;
692+ nv = (char **)realloc(e->obs, (e->n_obs + 1) * sizeof *e->obs);
693+ if (!nv) { free(d); return 0; }
694+ e->obs = nv;
695+ e->obs[e->n_obs++] = d;
696+ return 1;
697+}
698+
699+int str_arr_from(yyjson_val *arr, char ***out, size_t *n_out, size_t cap)
700+{
701+ char **v = NULL;
702+ size_t n = 0, i, max;
703+
704+ *out = NULL;
705+ *n_out = 0;
706+ if (!arr || !yyjson_is_arr(arr)) return 0;
707+ max = yyjson_arr_size(arr);
708+ if (max > cap) max = cap;
709+ if (max == 0) return 0;
710+ v = (char **)calloc(max, sizeof *v);
711+ if (!v) return -1;
712+ for (i = 0; i < max; i++) {
713+ yyjson_val *it = yyjson_arr_get(arr, i);
714+ const char *s;
715+ if (!it || !yyjson_is_str(it)) continue;
716+ s = yyjson_get_str(it);
717+ if (!s || strlen(s) > (size_t)OBS_TEXT_MAX) continue;
718+ v[n] = dup_or_empty(s);
719+ if (v[n]) n++;
720+ }
721+ *out = v;
722+ *n_out = n;
723+ return 0;
724+}
725+
726+/* ------------------------------------------------------------------ */
727+/* Load */
728+/* ------------------------------------------------------------------ */
729+
730+/* One JSONL line into the graph. 0 = understood, -1 = keep verbatim. */
731+static int load_line(graph_t *g, const char *line)
732+{
733+ yyjson_doc *doc;
734+ yyjson_val *root, *type, *v;
735+ const char *ty;
736+ int rc = -1;
737+
738+ while (*line == ' ' || *line == '\t' || *line == '\r') line++;
739+ if (!*line) return 0; /* blank: not data */
740+
741+ doc = yyjson_read(line, strlen(line), 0);
742+ if (!doc) return -1;
743+ root = yyjson_doc_get_root(doc);
744+ if (!root || !yyjson_is_obj(root)) { yyjson_doc_free(doc); return -1; }
745+
746+ type = yyjson_obj_get(root, "type");
747+ ty = (type && yyjson_is_str(type)) ? yyjson_get_str(type) : NULL;
748+
749+ if (ty && strcmp(ty, "entity") == 0) {
750+ v = yyjson_obj_get(root, "name");
751+ if (yyjson_is_str(v)) {
752+ yyjson_val *nmv = v;
753+ yyjson_val *et = yyjson_obj_get(root, "entityType");
754+ yyjson_val *ob = yyjson_obj_get(root, "observations");
755+ if (yyjson_is_str(et) && yyjson_is_arr(ob)) {
756+ char **obs = NULL;
757+ size_t n_obs = 0, i;
758+ char err[128];
759+ if (str_arr_from(ob, &obs, &n_obs,
760+ (size_t)MAX_OBS_PER_ENT_DEFAULT) == 0) {
761+ if (ent_add(g, yyjson_get_str(nmv), yyjson_get_str(et),
762+ obs, n_obs, err, sizeof err) == 0)
763+ rc = 0;
764+ for (i = 0; i < n_obs; i++) free(obs[i]);
765+ free(obs);
766+ }
767+ }
768+ }
769+ } else if (ty && strcmp(ty, "relation") == 0) {
770+ yyjson_val *f = yyjson_obj_get(root, "from");
771+ yyjson_val *t = yyjson_obj_get(root, "to");
772+ yyjson_val *r = yyjson_obj_get(root, "relationType");
773+ if (yyjson_is_str(f) && yyjson_is_str(t) && yyjson_is_str(r)) {
774+ char err[128];
775+ if (rel_add(g, yyjson_get_str(f), yyjson_get_str(t),
776+ yyjson_get_str(r), err, sizeof err) == 0)
777+ rc = 0;
778+ }
779+ }
780+
781+ yyjson_doc_free(doc);
782+ return rc;
783+}
784+
785+int graph_load(void)
786+{
787+ char *text;
788+ size_t len, i, start;
789+ graph_t ng;
790+
791+ graph_clear(&G);
792+ g_data_err[0] = '\0';
793+ if (!ensure_path()) return -1;
794+
795+ memset(&ng, 0, sizeof ng);
796+ text = read_file_all(g_path, &len);
797+ if (!text) {
798+ if (file_exists_p(g_path)) {
799+ snprintf(g_data_err, sizeof g_data_err,
800+ "cannot read the graph file (permission, or larger "
801+ "than %d MB)", (int)(FILE_MAX / (1024 * 1024)));
802+ return -1;
803+ }
804+ G = ng; /* no file yet: empty */
805+ return 0;
806+ }
807+
808+ i = 0;
809+ while (i <= len) {
810+ start = i;
811+ while (i < len && text[i] != '\n') i++;
812+ text[i] = '\0';
813+ if (load_line(&ng, text + start) != 0) bad_add(&ng, text + start);
814+ i++;
815+ }
816+ free(text);
817+ G = ng;
818+ return 0;
819+}
820+
821+/* ------------------------------------------------------------------ */
822+/* Save */
823+/* ------------------------------------------------------------------ */
824+
825+static int write_over(const char *path, const char *data, size_t len,
826+ char *err, size_t errsz)
827+{
828+ char tmp[PATH_SZ + SUFFIX_SZ];
829+ FILE *f;
830+ int mode = -1;
831+ struct stat st;
832+
833+ if (err && errsz) err[0] = '\0';
834+ if (stat(path, &st) == 0 && S_ISREG(st.st_mode))
835+ mode = (int)(st.st_mode & 0777);
836+
837+ snprintf(tmp, sizeof tmp, "%s.tmp.%ld", path, (long)
838+#if defined(_WIN32)
839+ GetCurrentProcessId()
840+#else
841+ (long)getpid()
842+#endif
843+ );
844+
845+ f = fopen(tmp, "wb");
846+ if (!f) {
847+ if (err) snprintf(err, errsz, "cannot create a temp file beside %s", path);
848+ return -1;
849+ }
850+ if (len && fwrite(data, 1, len, f) != len) {
851+ fclose(f);
852+#if defined(_WIN32)
853+ _unlink(tmp);
854+#else
855+ unlink(tmp);
856+#endif
857+ if (err) snprintf(err, errsz, "the graph is too large to write");
858+ return -1;
859+ }
860+ if (fflush(f) != 0) {
861+ fclose(f);
862+#if defined(_WIN32)
863+ _unlink(tmp);
864+#else
865+ unlink(tmp);
866+#endif
867+ if (err) snprintf(err, errsz, "cannot flush the graph to disk");
868+ return -1;
869+ }
870+#if !defined(_WIN32)
871+ (void)fsync(fileno(f));
872+#endif
873+ fclose(f);
874+
875+ /* rename() gives the new file the process umask; restore the operator's
876+ * own bits so a 0600 graph does not come back world-readable. */
877+ if (mode >= 0) {
878+#if !defined(_WIN32)
879+ (void)chmod(tmp, (mode_t)mode);
880+#else
881+ (void)_chmod(tmp, (mode_t)mode);
882+#endif
883+ }
884+
885+#if defined(_WIN32)
886+ if (!MoveFileExA(tmp, path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
887+ _unlink(tmp);
888+ if (err) snprintf(err, errsz, "cannot replace the graph file");
889+ return -1;
890+ }
891+#else
892+ if (rename(tmp, path) != 0) {
893+ unlink(tmp);
894+ if (err) snprintf(err, errsz, "cannot replace the graph file");
895+ return -1;
896+ }
897+#endif
898+ return 0;
899+}
900+
901+int graph_save(char *err, size_t errsz)
902+{
903+ buf_t b;
904+ size_t i, j;
905+ int rc;
906+
907+ if (!ensure_path()) {
908+ snprintf(err, errsz, "%s", g_data_err[0] ? g_data_err
909+ : "the graph file is not reachable");
910+ return -1;
911+ }
912+ buf_init(&b);
913+ for (i = 0; i < G.n_ent; i++) {
914+ buf_puts(&b, "{\"type\":\"entity\",\"name\":");
915+ json_str(&b, G.ent[i].name);
916+ buf_puts(&b, ",\"entityType\":");
917+ json_str(&b, G.ent[i].etype);
918+ buf_puts(&b, ",\"observations\":[");
919+ for (j = 0; j < G.ent[i].n_obs; j++) {
920+ if (j) buf_putc(&b, ',');
921+ json_str(&b, G.ent[i].obs[j] ? G.ent[i].obs[j] : "");
922+ }
923+ buf_puts(&b, "]}\n");
924+ }
925+ for (i = 0; i < G.n_rel; i++) {
926+ buf_puts(&b, "{\"type\":\"relation\",\"from\":");
927+ json_str(&b, G.rel[i].from);
928+ buf_puts(&b, ",\"to\":");
929+ json_str(&b, G.rel[i].to);
930+ buf_puts(&b, ",\"relationType\":");
931+ json_str(&b, G.rel[i].rtype);
932+ buf_puts(&b, "}\n");
933+ }
934+ /* Unreadable lines last, byte for byte, so a round trip is lossless. */
935+ for (i = 0; i < G.n_bad; i++) {
936+ buf_puts(&b, G.bad[i] ? G.bad[i] : "");
937+ buf_putc(&b, '\n');
938+ }
939+ rc = write_over(g_path, buf_str(&b), b.n, err, errsz);
940+ buf_free(&b);
941+ return rc;
942+}
src/memory.h+185−0■■■■■
11new file mode 100644
index 0000000..52da038
--- /dev/null
+++ b/src/memory.h
@@ -0,0 +1,185 @@
1+/*
2+ * memory.h - shared declarations for plugin_memory.
3+ *
4+ * plugin_memory is a SCORPIOX BOT connector plugin that reimplements the
5+ * reference MCP "memory" knowledge graph in pure C99: entities with string
6+ * observations, relations between them, persisted as one JSONL file, exposed
7+ * both as nine MCP tools over stdio and as a JSON API behind a browser UI.
8+ *
9+ * The four translation units:
10+ * plugin_memory.c main(), --meta, --mcp loop, CGI dispatch, auth
11+ * graph.c storage: paths, load, atomic save, entity/relation store
12+ * tools.c the nine tools, shared by the MCP and the HTTP front end
13+ * api.c the CGI JSON actions and the HTML page
14+ *
15+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
16+ */
17+#ifndef SX_PLUGIN_MEMORY_H
18+#define SX_PLUGIN_MEMORY_H
19+
20+#include <stddef.h>
21+#include "yyjson.h"
22+
23+#define PLUGIN_SLUG "memory"
24+#define PLUGIN_ID "plugin_memory"
25+#define PLUGIN_VER "1.0.0"
26+#define PLUGIN_NAME "memory"
27+#define PLUGIN_DESC "Knowledge graph"
28+
29+#define MCP_PROTOCOL "2025-06-18"
30+#define RESOURCE_URI "memory://knowledge-graph"
31+#define SERVER_NAME "memory-server"
32+
33+/* ------------------------------------------------------------------ */
34+/* Limits */
35+/* */
36+/* Every cap is a deliberate, documented ceiling: a plugin runs inside */
37+/* the bot on someone's node, so a runaway agent must not be able to */
38+/* grow the graph until the node swaps. Each one has an env override so */
39+/* the tests can prove the truncation path on a tiny fixture. */
40+/* ------------------------------------------------------------------ */
41+
42+#define MAX_ENTITIES_DEFAULT 20000
43+#define MAX_RELATIONS_DEFAULT 40000
44+#define MAX_OBS_PER_ENT_DEFAULT 2000
45+#define SX_NAME_MAX 1024
46+#define SX_TYPE_MAX 1024
47+#define OBS_TEXT_MAX 8000
48+#define PATH_SZ 1024
49+/* Suffix room: "%s.lock" and "%s.tmp.<pid>" append to a full PATH_SZ path. */
50+#define SUFFIX_SZ 32
51+#define REQ_BODY_MAX (8 * 1024 * 1024)
52+#define FILE_MAX (24 * 1024 * 1024)
53+#define STDIN_LINE_MAX (8 * 1024 * 1024)
54+#define UI_LIMIT_DEFAULT 1000
55+
56+/* ------------------------------------------------------------------ */
57+/* Growable byte buffer (graph.c) */
58+/* ------------------------------------------------------------------ */
59+
60+typedef struct {
61+ char *p;
62+ size_t n;
63+ size_t cap;
64+} buf_t;
65+
66+void buf_init(buf_t *b);
67+int buf_need(buf_t *b, size_t extra);
68+void buf_add(buf_t *b, const char *s, size_t n);
69+void buf_puts(buf_t *b, const char *s);
70+void buf_putc(buf_t *b, int c);
71+const char *buf_str(const buf_t *b);
72+void buf_free(buf_t *b);
73+
74+/* ------------------------------------------------------------------ */
75+/* Small helpers (graph.c) */
76+/* ------------------------------------------------------------------ */
77+
78+void str_copy(char *dst, size_t dsz, const char *src);
79+int str_icontains(const char *hay, const char *needle);
80+void json_str(buf_t *b, const char *s);
81+int env_int(const char *name, int dflt, int lo, int hi);
82+char *dup_or_null(const char *s);
83+
84+/* ------------------------------------------------------------------ */
85+/* The graph (graph.c) */
86+/* ------------------------------------------------------------------ */
87+
88+typedef struct {
89+ char *name;
90+ char *etype;
91+ char **obs;
92+ size_t n_obs;
93+ int keep; /* scratch, used by the read tools */
94+} entity_t;
95+
96+typedef struct {
97+ char *from;
98+ char *to;
99+ char *rtype;
100+} relation_t;
101+
102+typedef struct {
103+ entity_t *ent; size_t n_ent, cap_ent;
104+ relation_t *rel; size_t n_rel, cap_rel;
105+ char **bad; size_t n_bad, cap_bad; /* lines kept verbatim */
106+ int truncated;
107+} graph_t;
108+
109+extern graph_t G;
110+extern char g_data_err[256];
111+
112+int graph_load(void); /* 0 ok, -1 + g_data_err */
113+int graph_save(char *err, size_t errsz);
114+void graph_lock(void);
115+void graph_unlock(void);
116+const char *graph_path(void);
117+int graph_path_info(long long *size, int *exists);
118+entity_t *ent_find(graph_t *g, const char *name);
119+int ent_add(graph_t *g, const char *name, const char *etype,
120+ char **obs, size_t n_obs, char *err, size_t errsz);
121+int rel_add(graph_t *g, const char *from, const char *to,
122+ const char *rtype, char *err, size_t errsz);
123+void bad_add(graph_t *g, const char *line);
124+int obs_push(entity_t *e, const char *text);
125+void graph_clear(graph_t *g);
126+int str_arr_from(yyjson_val *arr, char ***out, size_t *n_out, size_t cap);
127+
128+/* ------------------------------------------------------------------ */
129+/* Read options (tools.c) */
130+/* ------------------------------------------------------------------ */
131+
132+typedef struct {
133+ int has_limit; /* observationLimit present (0 is a real value) */
134+ int limit;
135+ int has_types; /* entityTypes present */
136+ char **types;
137+ size_t n_types;
138+ int has_count; /* emit observationCount (set with has_limit) */
139+ int max_entities;/* 0 = unlimited */
140+ int truncated;
141+} read_opt_t;
142+
143+void read_opt_init(read_opt_t *o);
144+
145+/* ------------------------------------------------------------------ */
146+/* Tool results (tools.c) */
147+/* ------------------------------------------------------------------ */
148+
149+typedef struct {
150+ yyjson_mut_doc *md; /* owns root */
151+ yyjson_mut_val *root; /* the result object */
152+ char *notice; /* optional second text block (skipped, etc.) */
153+ char *error; /* error text when is_error */
154+ int is_error;
155+} tool_out_t;
156+
157+void tool_out_init(tool_out_t *t);
158+void tool_err(tool_out_t *t, const char *fmt, ...);
159+void tool_free(tool_out_t *t);
160+
161+/* The nine tools. Each reads `args` (may be NULL) and fills `t`. */
162+void tool_create_entities(yyjson_val *args, tool_out_t *t);
163+void tool_create_relations(yyjson_val *args, tool_out_t *t);
164+void tool_add_observations(yyjson_val *args, tool_out_t *t);
165+void tool_delete_entities(yyjson_val *args, tool_out_t *t);
166+void tool_delete_observations(yyjson_val *args, tool_out_t *t);
167+void tool_delete_relations(yyjson_val *args, tool_out_t *t);
168+void tool_read_graph(yyjson_val *args, tool_out_t *t);
169+void tool_search_nodes(yyjson_val *args, tool_out_t *t);
170+void tool_open_nodes(yyjson_val *args, tool_out_t *t);
171+
172+/* The full tools/list array as JSON text (caller frees). */
173+char *tools_list_json(void);
174+/* Dispatch by name; returns 0 when the name is one of the nine. */
175+int tool_dispatch(const char *name, yyjson_val *args, tool_out_t *out);
176+
177+/* Build the MCP result object for a tool call: content[] + isError
178+ * (+ structuredContent when the reference server emits one). */
179+char *tool_mcp_result(tool_out_t *t);
180+
181+/* Serialize the tool result for the HTTP API: {"ok":true,...} or
182+ * {"ok":false,"error":"..."}. Caller frees. */
183+char *tool_api_result(tool_out_t *t);
184+
185+#endif /* SX_PLUGIN_MEMORY_H */
src/plugin_memory.c+402−0■■■■■
11new file mode 100644
index 0000000..f7235b6
--- /dev/null
+++ b/src/plugin_memory.c
@@ -0,0 +1,402 @@
1+/*
2+ * plugin_memory.c - entry point for the SCORPIOX BOT knowledge-graph memory
3+ * connector.
4+ *
5+ * One binary, five modes, exactly as the plugin_<name> spec requires:
6+ *
7+ * 1. --meta / SX_PLUGIN_META=1 -> one line of discovery JSON, exit 0.
8+ * Unauthenticated on purpose: /plugins on the node probes it, and the
9+ * sx-connector-mcp router probes it before it will run anything else.
10+ * 2. --mcp -> MCP JSON-RPC 2.0 over stdio, one request
11+ * per line on stdin, one response per line on stdout. This is what makes
12+ * the plugin a tool provider for SCORPIOX CODE through the single
13+ * sx-connector-mcp router, with no clang change and no extra MCP server
14+ * slot.
15+ * 3. ?action=... | ?format=json | POST -> the JSON node API the browser UI
16+ * talks to. Same nine operations as --mcp, so the UI can never drift
17+ * away from what an agent sees.
18+ * 4. GET (default) -> the knowledge-graph browser page.
19+ * 5. --version -> id + version.
20+ *
21+ * Modes 3 and 4 sit behind require_node_auth(): the node's :8150 is reachable
22+ * from the LAN, so a plugin that reads and writes the operator's knowledge
23+ * graph must not answer a bare curl. --meta stays open so discovery works.
24+ *
25+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
26+ */
27+
28+#if defined(_WIN32) && !defined(_WIN32_WINNT)
29+# define _WIN32_WINNT 0x0601
30+#endif
31+
32+#if !defined(_WIN32)
33+# define _POSIX_C_SOURCE 200809L
34+# define _DEFAULT_SOURCE 1
35+# if defined(__APPLE__)
36+# define _DARWIN_C_SOURCE 1
37+# endif
38+#endif
39+
40+#include <stdio.h>
41+#include <stdlib.h>
42+#include <string.h>
43+#include <ctype.h>
44+
45+#if defined(_WIN32)
46+# define WIN32_LEAN_AND_MEAN
47+# include <windows.h>
48+# include <io.h>
49+# include <fcntl.h>
50+/* MinGW's CRT starts stdout in TEXT mode and rewrites every \n we emit into
51+ * \r\n. A CGI header block must end with exactly CRLF CRLF; text mode turns
52+ * that into \r\r\n\r\r\n, scorpiox-server cannot find the header/body
53+ * separator, and the whole reply (headers included) is served as a body. Same
54+ * for the MCP loop: a JSON-RPC line with a stray \r confuses line readers.
55+ * Force binary stdio before main() runs. */
56+__attribute__((constructor))
57+static void sx_plugin_binary_stdio(void)
58+{
59+ _setmode(_fileno(stdout), _O_BINARY);
60+ _setmode(_fileno(stdin), _O_BINARY);
61+}
62+#else
63+# include <unistd.h>
64+#endif
65+
66+#include "memory.h"
67+
68+/* In api.c */
69+int api_handle(void); /* returns process exit code */
70+
71+/* ------------------------------------------------------------------ */
72+/* --meta */
73+/* ------------------------------------------------------------------ */
74+
75+static int mode_meta(void)
76+{
77+ printf("{\"name\":\"%s\",\"desc\":\"%s\",\"kind\":\"mcp\",\"mcp\":true,"
78+ "\"daemon\":false,\"menus\":false,\"verified\":\"live\","
79+ "\"category\":\"devtools\",\"version\":\"%s\"}\n",
80+ PLUGIN_NAME, PLUGIN_DESC, PLUGIN_VER);
81+ fflush(stdout);
82+ return 0;
83+}
84+
85+/* ------------------------------------------------------------------ */
86+/* --mcp : MCP JSON-RPC 2.0 over stdio */
87+/* */
88+/* The contract sx-connector-mcp (and any other MCP host) exercises: */
89+/* */
90+/* initialize -> notifications/initialized -> tools/list -> */
91+/* tools/call */
92+/* */
93+/* Rules that matter: */
94+/* */
95+/* - one request per line, one response per line, flushed every time. */
96+/* A host reads stdout blocking, so an unflushed reply is a hang. */
97+/* - a notification (no "id" member) gets NO response, not an empty */
98+/* one. Answering a notification is how a router deadlocks. */
99+/* - the id is echoed back exactly as it arrived (number in, number */
100+/* out; string in, string out). */
101+/* - a tool that fails returns a RESULT with isError:true, because */
102+/* the JSON-RPC call itself succeeded and this is what hosts render */
103+/* for the user. Only protocol problems are JSON-RPC errors. */
104+/* ------------------------------------------------------------------ */
105+
106+static void put_id(buf_t *b, yyjson_val *id)
107+{
108+ if (!id) { buf_puts(b, "null"); return; }
109+ switch (yyjson_get_type(id)) {
110+ case YYJSON_TYPE_STR:
111+ json_str(b, yyjson_get_str(id));
112+ break;
113+ case YYJSON_TYPE_NUM:
114+ if (yyjson_get_subtype(id) == YYJSON_SUBTYPE_UINT) {
115+ char t[32];
116+ snprintf(t, sizeof t, "%llu",
117+ (unsigned long long)yyjson_get_uint(id));
118+ buf_puts(b, t);
119+ } else if (yyjson_get_subtype(id) == YYJSON_SUBTYPE_SINT) {
120+ char t[32];
121+ snprintf(t, sizeof t, "%lld", (long long)yyjson_get_sint(id));
122+ buf_puts(b, t);
123+ } else {
124+ char t[64];
125+ snprintf(t, sizeof t, "%g", yyjson_get_num(id));
126+ buf_puts(b, t);
127+ }
128+ break;
129+ case YYJSON_TYPE_BOOL:
130+ buf_puts(b, yyjson_get_bool(id) ? "true" : "false");
131+ break;
132+ default:
133+ buf_puts(b, "null");
134+ break;
135+ }
136+}
137+
138+static void send_result(yyjson_val *id, const char *result_json)
139+{
140+ buf_t b;
141+ buf_init(&b);
142+ buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");
143+ put_id(&b, id);
144+ buf_puts(&b, ",\"result\":");
145+ buf_puts(&b, result_json ? result_json : "{}");
146+ buf_puts(&b, "}");
147+ fputs(buf_str(&b), stdout);
148+ fputc('\n', stdout);
149+ fflush(stdout);
150+ buf_free(&b);
151+}
152+
153+static void send_error(yyjson_val *id, int code, const char *message)
154+{
155+ buf_t b;
156+ buf_init(&b);
157+ buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");
158+ put_id(&b, id);
159+ buf_puts(&b, ",\"error\":{\"code\":");
160+ { char t[16]; snprintf(t, sizeof t, "%d", code); buf_puts(&b, t); }
161+ buf_puts(&b, ",\"message\":");
162+ json_str(&b, message ? message : "error");
163+ buf_puts(&b, "}}");
164+ fputs(buf_str(&b), stdout);
165+ fputc('\n', stdout);
166+ fflush(stdout);
167+ buf_free(&b);
168+}
169+
170+/* resources/read serves the same graph the tools read, as one JSON text
171+ * under the well-known URI. A subscription notification is not emitted: the
172+ * reference server sends resources/updated to subscribers, and this connector
173+ * is a single request/response process with no channel to notify on. */
174+static char *resource_text(void)
175+{
176+ tool_out_t t;
177+ char *s = NULL;
178+
179+ tool_out_init(&t);
180+ tool_read_graph(NULL, &t);
181+ if (!t.is_error && t.md && t.root)
182+ s = yyjson_mut_write(t.md, 0, NULL);
183+ tool_free(&t);
184+ return s;
185+}
186+
187+static void handle_request(yyjson_val *root, yyjson_val *id, const char *method)
188+{
189+ if (strcmp(method, "initialize") == 0) {
190+ buf_t b;
191+ buf_init(&b);
192+ buf_puts(&b, "{\"protocolVersion\":\"" MCP_PROTOCOL
193+ "\",\"capabilities\":{\"tools\":{\"listChanged\":false},"
194+ "\"resources\":{\"subscribe\":false,"
195+ "\"listChanged\":false}},\"serverInfo\":{\"name\":\""
196+ SERVER_NAME "\",\"title\":\"Knowledge Graph Memory\","
197+ "\"version\":\"" PLUGIN_VER "\"}}");
198+ send_result(id, buf_str(&b));
199+ buf_free(&b);
200+ return;
201+ }
202+ if (strcmp(method, "ping") == 0) {
203+ send_result(id, "{}");
204+ return;
205+ }
206+ if (strcmp(method, "tools/list") == 0) {
207+ char *tools = tools_list_json();
208+ buf_t b;
209+ buf_init(&b);
210+ buf_puts(&b, "{\"tools\":");
211+ buf_puts(&b, tools ? tools : "[]");
212+ buf_puts(&b, "}");
213+ send_result(id, buf_str(&b));
214+ buf_free(&b);
215+ free(tools);
216+ return;
217+ }
218+ if (strcmp(method, "tools/call") == 0) {
219+ yyjson_val *params = yyjson_obj_get(root, "params");
220+ const char *name = NULL;
221+ yyjson_val *args = NULL;
222+ tool_out_t t;
223+ char *res;
224+
225+ if (params && yyjson_is_obj(params)) {
226+ yyjson_val *nv = yyjson_obj_get(params, "name");
227+ if (nv && yyjson_is_str(nv)) name = yyjson_get_str(nv);
228+ args = yyjson_obj_get(params, "arguments");
229+ if (args && !yyjson_is_obj(args)) args = NULL;
230+ }
231+ if (!name) {
232+ send_error(id, -32602, "tools/call needs params.name");
233+ return;
234+ }
235+ if (tool_dispatch(name, args, &t) != 0) {
236+ buf_t b;
237+ buf_init(&b);
238+ buf_puts(&b, "Unknown tool: ");
239+ buf_puts(&b, name);
240+ send_error(id, -32602, buf_str(&b));
241+ buf_free(&b);
242+ tool_free(&t);
243+ return;
244+ }
245+ res = tool_mcp_result(&t);
246+ send_result(id, res ? res : "{\"content\":[],\"isError\":true}");
247+ free(res);
248+ tool_free(&t);
249+ return;
250+ }
251+ if (strcmp(method, "resources/list") == 0) {
252+ send_result(id,
253+ "{\"resources\":[{\"uri\":\"" RESOURCE_URI "\","
254+ "\"name\":\"knowledge-graph\",\"title\":\"Knowledge Graph\","
255+ "\"description\":\"The full knowledge graph with all entities "
256+ "and relations\",\"mimeType\":\"application/json\"}]}");
257+ return;
258+ }
259+ if (strcmp(method, "resources/templates/list") == 0) {
260+ send_result(id, "{\"resourceTemplates\":[]}");
261+ return;
262+ }
263+ if (strcmp(method, "prompts/list") == 0) {
264+ send_result(id, "{\"prompts\":[]}");
265+ return;
266+ }
267+ if (strcmp(method, "resources/read") == 0) {
268+ yyjson_val *params = yyjson_obj_get(root, "params");
269+ const char *uri = NULL;
270+ char *text;
271+ buf_t b;
272+
273+ if (params && yyjson_is_obj(params)) {
274+ yyjson_val *u = yyjson_obj_get(params, "uri");
275+ if (u && yyjson_is_str(u)) uri = yyjson_get_str(u);
276+ }
277+ if (!uri) { send_error(id, -32602, "resources/read needs params.uri"); return; }
278+ if (strcmp(uri, RESOURCE_URI) != 0) {
279+ send_error(id, -32002, "Unknown resource: this server serves "
280+ RESOURCE_URI " only");
281+ return;
282+ }
283+ text = resource_text();
284+ buf_init(&b);
285+ buf_puts(&b, "{\"contents\":[{\"uri\":\"" RESOURCE_URI
286+ "\",\"mimeType\":\"application/json\",\"text\":");
287+ json_str(&b, text ? text : "{}");
288+ buf_puts(&b, "}]}");
289+ send_result(id, buf_str(&b));
290+ buf_free(&b);
291+ free(text);
292+ return;
293+ }
294+ if (strcmp(method, "resources/subscribe") == 0 ||
295+ strcmp(method, "resources/unsubscribe") == 0) {
296+ /* Accepted and ignored: there is no channel to notify on from a
297+ * request/response connector, so a host that subscribes must not be
298+ * left with an error. */
299+ send_result(id, "{}");
300+ return;
301+ }
302+ send_error(id, -32601, "Method not found");
303+}
304+
305+static int mode_mcp(void)
306+{
307+ char *line = (char *)malloc((size_t)STDIN_LINE_MAX);
308+ if (!line) return 1;
309+
310+ for (;;) {
311+ size_t n = 0;
312+ int c;
313+
314+ /* Read one line by hand: fgets with a fixed buffer would truncate a
315+ * tools/call whose arguments carry a long observation, and a
316+ * truncated line parses as valid-but-wrong JSON rather than failing. */
317+ for (;;) {
318+ c = fgetc(stdin);
319+ if (c == EOF) { if (n == 0) { free(line); return 0; } break; }
320+ if (c == '\n') break;
321+ if (c == '\r') continue;
322+ if (n + 1 < (size_t)STDIN_LINE_MAX) line[n++] = (char)c;
323+ }
324+ line[n] = '\0';
325+ if (n == 0) {
326+ if (c == EOF) { free(line); return 0; }
327+ continue; /* blank line */
328+ }
329+
330+ {
331+ yyjson_doc *doc = yyjson_read(line, n, 0);
332+ yyjson_val *root, *mv, *id;
333+ const char *method;
334+
335+ if (!doc) {
336+ send_error(NULL, -32700, "Parse error: not valid JSON");
337+ continue;
338+ }
339+ root = yyjson_doc_get_root(doc);
340+ if (!root || !yyjson_is_obj(root)) {
341+ yyjson_doc_free(doc);
342+ send_error(NULL, -32600, "Invalid request: expected an object");
343+ continue;
344+ }
345+ mv = yyjson_obj_get(root, "method");
346+ method = (mv && yyjson_is_str(mv)) ? yyjson_get_str(mv) : NULL;
347+ id = yyjson_obj_get(root, "id");
348+
349+ if (!method) {
350+ /* No method: either a response to something we never sent, or
351+ * a malformed request. A response gets no reply. */
352+ yyjson_doc_free(doc);
353+ if (yyjson_obj_get(root, "result") ||
354+ yyjson_obj_get(root, "error")) continue;
355+ send_error(id, -32600, "Invalid request: missing method");
356+ continue;
357+ }
358+ if (!id) { /* notification */
359+ yyjson_doc_free(doc);
360+ continue;
361+ }
362+
363+ handle_request(root, id, method);
364+ yyjson_doc_free(doc);
365+ }
366+ }
367+}
368+
369+/* ------------------------------------------------------------------ */
370+/* main */
371+/* ------------------------------------------------------------------ */
372+
373+int main(int argc, char **argv)
374+{
375+ int i;
376+
377+ for (i = 1; i < argc; i++) {
378+ if (strcmp(argv[i], "--meta") == 0) return mode_meta();
379+ if (strcmp(argv[i], "--mcp") == 0) return mode_mcp();
380+ if (strcmp(argv[i], "--version") == 0) {
381+ printf("%s %s\n", PLUGIN_ID, PLUGIN_VER);
382+ return 0;
383+ }
384+ if (strcmp(argv[i], "--schema") == 0) {
385+ char *t = tools_list_json();
386+ printf("%s\n", t ? t : "[]");
387+ free(t);
388+ return 0;
389+ }
390+ if (strcmp(argv[i], "--help") == 0) {
391+ printf("usage: %s [--meta|--mcp|--schema|--version]\n"
392+ "With no arguments this plugin runs as a CGI handler: the\n"
393+ "browser page on GET, the JSON API on ?action=... or POST.\n",
394+ PLUGIN_ID);
395+ return 0;
396+ }
397+ }
398+ if (getenv("SX_PLUGIN_META")) return mode_meta();
399+ if (getenv("SX_PLUGIN_MCP")) return mode_mcp();
400+
401+ return api_handle();
402+}
src/tools.c+1127−0■■■■■
11new file mode 100644
index 0000000..ecab2ac
--- /dev/null
+++ b/src/tools.c
@@ -0,0 +1,1127 @@
1+/*
2+ * tools.c - the nine knowledge-graph tools for plugin_memory.
3+ *
4+ * These are exactly the tools of the reference MCP memory server, with the
5+ * same names, the same input schemas and the same semantics, so an agent that
6+ * was tuned against the reference cannot tell the difference:
7+ *
8+ * create_entities skip existing names, report them in `skipped`
9+ * create_relations both ends must exist, dedupe the triple
10+ * add_observations entity must exist, dedupe within call and store
11+ * delete_entities report deleted/notFound, cascade relations
12+ * delete_observations exact-text match, count across missing entities
13+ * delete_relations exact triple match, count what actually went
14+ * read_graph optional entityTypes + observationLimit
15+ * search_nodes case-insensitive substring, limit, either-end
16+ * open_nodes exact names, either-end relations
17+ *
18+ * The rules that are easy to lose, and are therefore pinned by tests:
19+ *
20+ * - create_entities SKIPS a name that already exists (or repeats earlier in
21+ * the same batch) rather than adding its observations, and must say so in
22+ * the result - otherwise an agent reads a skip as a store.
23+ * - create_relations validates EVERY relation before adding ANY, so one bad
24+ * end fails the whole call and nothing is written.
25+ * - add_observations keeps the first occurrence of a string repeated within
26+ * one call.
27+ * - the read tools keep a relation when EITHER endpoint is in the result
28+ * set; requiring both made a node's outside connections undiscoverable.
29+ * - observationLimit 0 is a real value (names, types and counts only) and is
30+ * not the same as omitting the option; observationCount appears only when
31+ * the limit was given.
32+ * - a line the loader cannot parse is preserved and written back, so a
33+ * hand-edited graph survives every tool call.
34+ *
35+ * A tool never frees its own result: the caller serialises and then calls
36+ * tool_free(). That keeps the MCP loop leak-free and stops an error path from
37+ * destroying the error it is about to report.
38+ *
39+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
40+ */
41+
42+#if defined(_WIN32) && !defined(_WIN32_WINNT)
43+# define _WIN32_WINNT 0x0601
44+#endif
45+
46+#if !defined(_WIN32)
47+# define _POSIX_C_SOURCE 200809L
48+# define _DEFAULT_SOURCE 1
49+#endif
50+
51+#include <stdio.h>
52+#include <stdlib.h>
53+#include <string.h>
54+#include <stdarg.h>
55+
56+#include "memory.h"
57+
58+/* ------------------------------------------------------------------ */
59+/* Read options */
60+/* ------------------------------------------------------------------ */
61+
62+void read_opt_init(read_opt_t *o)
63+{
64+ memset(o, 0, sizeof *o);
65+ o->max_entities = 0; /* 0 = unlimited */
66+}
67+
68+static void read_opt_free_types(read_opt_t *o)
69+{
70+ size_t i;
71+ for (i = 0; i < o->n_types; i++) free(o->types[i]);
72+ free(o->types);
73+ o->types = NULL;
74+ o->n_types = 0;
75+}
76+
77+/* ------------------------------------------------------------------ */
78+/* Result record */
79+/* ------------------------------------------------------------------ */
80+
81+void tool_out_init(tool_out_t *t)
82+{
83+ memset(t, 0, sizeof *t);
84+}
85+
86+void tool_err(tool_out_t *t, const char *fmt, ...)
87+{
88+ char tmp[768];
89+ va_list ap;
90+ va_start(ap, fmt);
91+ vsnprintf(tmp, sizeof tmp, fmt, ap);
92+ va_end(ap);
93+ if (!t->error) t->error = dup_or_null(tmp);
94+ t->is_error = 1;
95+}
96+
97+void tool_free(tool_out_t *t)
98+{
99+ if (!t) return;
100+ if (t->md) yyjson_mut_doc_free(t->md);
101+ free(t->notice);
102+ free(t->error);
103+ memset(t, 0, sizeof *t);
104+}
105+
106+static void tool_start(tool_out_t *t)
107+{
108+ if (t->md) return;
109+ t->md = yyjson_mut_doc_new(NULL);
110+ if (!t->md) { tool_err(t, "out of memory"); return; }
111+ t->root = yyjson_mut_obj(t->md);
112+ if (!t->root) { tool_err(t, "out of memory"); return; }
113+ yyjson_mut_doc_set_root(t->md, t->root);
114+}
115+
116+/* ------------------------------------------------------------------ */
117+/* Argument helpers */
118+/* ------------------------------------------------------------------ */
119+
120+static yyjson_val *arg_get(yyjson_val *obj, const char *key)
121+{
122+ return obj ? yyjson_obj_get(obj, key) : NULL;
123+}
124+
125+static const char *arg_str(yyjson_val *obj, const char *key)
126+{
127+ yyjson_val *v = arg_get(obj, key);
128+ return (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL;
129+}
130+
131+/* Optional integer >= lo. Returns 1 when present and valid. */
132+static int arg_opt_int(yyjson_val *obj, const char *key, int lo, int *out)
133+{
134+ yyjson_val *v = arg_get(obj, key);
135+ long long n;
136+ if (!v || yyjson_is_null(v)) return 0;
137+ if (!yyjson_is_int(v)) return -1;
138+ n = (long long)yyjson_get_sint(v);
139+ if (n < lo) return -1;
140+ if (n > 100000000LL) n = 100000000LL;
141+ *out = (int)n;
142+ return 1;
143+}
144+
145+/* ------------------------------------------------------------------ */
146+/* Mut helpers */
147+/* ------------------------------------------------------------------ */
148+
149+static yyjson_mut_val *ent_to_mut(yyjson_mut_doc *md, const entity_t *e,
150+ const read_opt_t *o)
151+{
152+ yyjson_mut_val *o_ = yyjson_mut_obj(md);
153+ yyjson_mut_val *arr = yyjson_mut_arr(md);
154+ size_t i, lim;
155+
156+ if (!o_ || !arr) return o_;
157+ yyjson_mut_obj_add_str(md, o_, "name", e->name ? e->name : "");
158+ yyjson_mut_obj_add_str(md, o_, "entityType", e->etype ? e->etype : "");
159+ lim = e->n_obs;
160+ if (o && o->has_limit && (size_t)o->limit < lim) lim = (size_t)o->limit;
161+ for (i = 0; i < lim; i++)
162+ yyjson_mut_arr_add_str(md, arr, e->obs[i] ? e->obs[i] : "");
163+ yyjson_mut_obj_add_val(md, o_, "observations", arr);
164+ if (o && o->has_limit && o->has_count)
165+ yyjson_mut_obj_add_uint(md, o_, "observationCount", (uint64_t)e->n_obs);
166+ return o_;
167+}
168+
169+static yyjson_mut_val *rel_to_mut(yyjson_mut_doc *md, const char *from,
170+ const char *to, const char *rtype)
171+{
172+ yyjson_mut_val *r = yyjson_mut_obj(md);
173+ if (!r) return NULL;
174+ yyjson_mut_obj_add_str(md, r, "from", from ? from : "");
175+ yyjson_mut_obj_add_str(md, r, "to", to ? to : "");
176+ yyjson_mut_obj_add_str(md, r, "relationType", rtype ? rtype : "");
177+ return r;
178+}
179+
180+static int rel_same(const relation_t *a, const char *from, const char *to,
181+ const char *rtype)
182+{
183+ return strcmp(a->from, from) == 0 && strcmp(a->to, to) == 0 &&
184+ strcmp(a->rtype, rtype) == 0;
185+}
186+/* The same triple test for two plain field triples - used when one side is a
187+ * JSON object rather than a stored relation. A NULL on either side means
188+ * "no match", never a strcmp on NULL. */
189+static int rel_same_fields(const char *af, const char *at, const char *ar,
190+ const char *bf, const char *bt, const char *br)
191+{
192+ if (!af || !at || !ar || !bf || !bt || !br) return 0;
193+ return strcmp(af, bf) == 0 && strcmp(at, bt) == 0 && strcmp(ar, br) == 0;
194+}
195+
196+
197+/* Emit {"entities":[...],"relations":[...]} for a chosen set of entities.
198+ * A relation survives when EITHER endpoint is in the set, which is what makes
199+ * a node's connections to nodes outside the result set discoverable. */
200+static void emit_set(tool_out_t *t, entity_t **ents, size_t n_ents,
201+ const read_opt_t *o)
202+{
203+ yyjson_mut_doc *md = t->md;
204+ yyjson_mut_val *ea = yyjson_mut_arr(md);
205+ yyjson_mut_val *ra = yyjson_mut_arr(md);
206+ size_t i, r;
207+
208+ for (i = 0; i < n_ents; i++)
209+ yyjson_mut_arr_add_val(ea, ent_to_mut(md, ents[i], o));
210+
211+ for (r = 0; r < G.n_rel; r++) {
212+ int hit = 0;
213+ for (i = 0; i < n_ents; i++) {
214+ if (strcmp(G.rel[r].from, ents[i]->name) == 0 ||
215+ strcmp(G.rel[r].to, ents[i]->name) == 0) { hit = 1; break; }
216+ }
217+ if (!hit) continue;
218+ yyjson_mut_arr_add_val(ra, rel_to_mut(md, G.rel[r].from, G.rel[r].to,
219+ G.rel[r].rtype));
220+ }
221+ yyjson_mut_obj_add_val(md, t->root, "entities", ea);
222+ yyjson_mut_obj_add_val(md, t->root, "relations", ra);
223+}
224+
225+/* Emit the whole graph, honouring entityTypes + observationLimit. The kept
226+ * entities are collected as pointers first so the relation filter is a
227+ * pointer compare rather than a re-read of the JSON just built. */
228+static void emit_all(tool_out_t *t, const read_opt_t *o)
229+{
230+ entity_t **kept;
231+ size_t i, k, w;
232+
233+ kept = (entity_t **)malloc((G.n_ent ? G.n_ent : 1) * sizeof *kept);
234+ if (!kept) { tool_err(t, "out of memory"); return; }
235+
236+ w = 0;
237+ for (i = 0; i < G.n_ent; i++) {
238+ if (o->has_types) {
239+ size_t q;
240+ int ok = 0;
241+ for (q = 0; q < o->n_types; q++)
242+ if (strcmp(o->types[q], G.ent[i].etype) == 0) { ok = 1; break; }
243+ if (!ok) continue;
244+ }
245+ if (o->max_entities > 0 && w >= (size_t)o->max_entities) break;
246+ kept[w++] = &G.ent[i];
247+ }
248+ k = w;
249+ emit_set(t, kept, k, o);
250+ free(kept);
251+}
252+
253+/* Pull observationLimit / entityTypes out of args. 0 ok, -1 malformed. */
254+static int parse_read_opts(yyjson_val *args, read_opt_t *o)
255+{
256+ yyjson_val *v;
257+ if (!args) return 0;
258+
259+ v = yyjson_obj_get(args, "observationLimit");
260+ if (v && !yyjson_is_null(v)) {
261+ int r = arg_opt_int(args, "observationLimit", 0, &o->limit);
262+ if (r != 1) return -1;
263+ o->has_limit = 1;
264+ o->has_count = 1;
265+ }
266+ v = yyjson_obj_get(args, "entityTypes");
267+ if (v && !yyjson_is_null(v)) {
268+ if (!yyjson_is_arr(v) || yyjson_arr_size(v) == 0) return -1;
269+ if (str_arr_from(v, &o->types, &o->n_types, 1000) != 0) return -1;
270+ if (o->n_types == 0) return -1;
271+ o->has_types = 1;
272+ }
273+ return 0;
274+}
275+
276+/* ------------------------------------------------------------------ */
277+/* create_entities */
278+/* ------------------------------------------------------------------ */
279+
280+void tool_create_entities(yyjson_val *args, tool_out_t *t)
281+{
282+ yyjson_val *arr = arg_get(args, "entities");
283+ yyjson_mut_val *created, *skipped;
284+ size_t i, max;
285+ char err[256];
286+
287+ if (!arr || !yyjson_is_arr(arr)) {
288+ tool_err(t, "Missing required parameter: entities");
289+ return;
290+ }
291+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
292+
293+ tool_start(t);
294+ if (t->is_error) return;
295+ created = yyjson_mut_arr(t->md);
296+ skipped = yyjson_mut_arr(t->md);
297+ max = yyjson_arr_size(arr);
298+
299+ /* Names already requested earlier in this same batch. */
300+ for (i = 0; i < max; i++) {
301+ yyjson_val *e = yyjson_arr_get(arr, i);
302+ const char *nm, *ty, *prior;
303+ yyjson_val *ob;
304+ char **obs = NULL;
305+ size_t n_obs = 0, j;
306+ int dup = 0;
307+
308+ if (!e || !yyjson_is_obj(e)) {
309+ tool_err(t, "Each entity must be an object with name, entityType "
310+ "and observations.");
311+ return;
312+ }
313+ nm = arg_str(e, "name");
314+ ty = arg_str(e, "entityType");
315+ ob = arg_get(e, "observations");
316+ if (!nm || !*nm || !ty || !*ty) {
317+ tool_err(t, "Each entity needs a non-empty name and entityType.");
318+ return;
319+ }
320+ if (ob && !yyjson_is_arr(ob)) {
321+ tool_err(t, "Entity '%s': observations must be an array of "
322+ "strings.", nm);
323+ return;
324+ }
325+ /* repeat earlier in this batch? */
326+ for (j = 0; j < i && !dup; j++) {
327+ prior = arg_str(yyjson_arr_get(arr, j), "name");
328+ if (prior && strcmp(prior, nm) == 0) dup = 1;
329+ }
330+ if (dup || ent_find(&G, nm) != NULL) {
331+ yyjson_mut_arr_add_str(t->md, skipped, nm);
332+ continue;
333+ }
334+ if (ob && str_arr_from(ob, &obs, &n_obs,
335+ (size_t)MAX_OBS_PER_ENT_DEFAULT) != 0) {
336+ tool_err(t, "out of memory");
337+ return;
338+ }
339+ if (ent_add(&G, nm, ty, obs, n_obs, err, sizeof err) != 0) {
340+ for (j = 0; j < n_obs; j++) free(obs[j]);
341+ free(obs);
342+ tool_err(t, "%s", err[0] ? err : "cannot add the entity");
343+ return;
344+ }
345+ for (j = 0; j < n_obs; j++) free(obs[j]);
346+ free(obs);
347+ G.ent[G.n_ent - 1].keep = 1;
348+ }
349+
350+ if (graph_save(err, sizeof err) != 0) {
351+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
352+ return;
353+ }
354+
355+ {
356+ read_opt_t no;
357+ size_t k;
358+ read_opt_init(&no);
359+ for (k = 0; k < G.n_ent; k++) {
360+ if (!G.ent[k].keep) continue;
361+ yyjson_mut_arr_add_val(created, ent_to_mut(t->md, &G.ent[k], &no));
362+ }
363+ yyjson_mut_obj_add_val(t->md, t->root, "entities", created);
364+ if (yyjson_mut_arr_size(skipped) > 0) {
365+ size_t ns = yyjson_mut_arr_size(skipped), q;
366+ buf_t nb;
367+ char head[128];
368+ yyjson_mut_obj_add_val(t->md, t->root, "skipped", skipped);
369+ buf_init(&nb);
370+ snprintf(head, sizeof head, "Skipped %zu %s: ", ns,
371+ ns == 1 ? "entity that already exists"
372+ : "entities that already exist");
373+ buf_puts(&nb, head);
374+ {
375+ /* Walk the array we just built with the iterator that matches
376+ * it: yyjson's immutable getters on a mutable value are a
377+ * type-lie, not a convenience. */
378+ yyjson_mut_arr_iter ai;
379+ yyjson_mut_val *item;
380+ size_t seen = 0;
381+ yyjson_mut_arr_iter_init(skipped, &ai);
382+ while ((item = yyjson_mut_arr_iter_next(&ai)) != NULL) {
383+ if (seen++) buf_puts(&nb, ", ");
384+ buf_puts(&nb, yyjson_mut_get_str(item));
385+ }
386+ (void)q;
387+ }
388+ buf_puts(&nb, ns == 1
389+ ? ". Its observations were not added; use "
390+ "add_observations for existing entities."
391+ : ". Their observations were not added; use "
392+ "add_observations for existing entities.");
393+ t->notice = dup_or_null(buf_str(&nb));
394+ buf_free(&nb);
395+ }
396+ }
397+
398+ for (i = 0; i < G.n_ent; i++) G.ent[i].keep = 0;
399+}
400+
401+/* ------------------------------------------------------------------ */
402+/* create_relations */
403+/* ------------------------------------------------------------------ */
404+
405+void tool_create_relations(yyjson_val *args, tool_out_t *t)
406+{
407+ yyjson_val *arr = arg_get(args, "relations");
408+ yyjson_mut_val *created;
409+ size_t i, max;
410+ char err[256];
411+
412+ if (!arr || !yyjson_is_arr(arr)) {
413+ tool_err(t, "Missing required parameter: relations");
414+ return;
415+ }
416+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
417+ max = yyjson_arr_size(arr);
418+
419+ /* Validate every relation before adding any: one missing end fails the
420+ * whole call and nothing is written. */
421+ for (i = 0; i < max; i++) {
422+ yyjson_val *r = yyjson_arr_get(arr, i);
423+ const char *from = r ? arg_str(r, "from") : NULL;
424+ const char *to = r ? arg_str(r, "to") : NULL;
425+ const char *ty = r ? arg_str(r, "relationType") : NULL;
426+ if (!r || !yyjson_is_obj(r) || !from || !*from || !to || !*to ||
427+ !ty || !*ty) {
428+ tool_err(t, "Each relation must be an object with non-empty from, "
429+ "to and relationType.");
430+ return;
431+ }
432+ if (!ent_find(&G, from)) {
433+ tool_err(t, "Entity with name %s not found", from);
434+ return;
435+ }
436+ if (!ent_find(&G, to)) {
437+ tool_err(t, "Entity with name %s not found", to);
438+ return;
439+ }
440+ }
441+
442+ tool_start(t);
443+ if (t->is_error) return;
444+ created = yyjson_mut_arr(t->md);
445+
446+ for (i = 0; i < max; i++) {
447+ yyjson_val *r = yyjson_arr_get(arr, i);
448+ const char *from = arg_str(r, "from");
449+ const char *to = arg_str(r, "to");
450+ const char *ty = arg_str(r, "relationType");
451+ size_t j;
452+ int dup = 0;
453+
454+ for (j = 0; j < G.n_rel; j++)
455+ if (rel_same(&G.rel[j], from, to, ty)) { dup = 1; break; }
456+ for (j = 0; j < i && !dup; j++) {
457+ yyjson_val *q = yyjson_arr_get(arr, j);
458+ if (rel_same_fields(arg_str(q, "from"), arg_str(q, "to"),
459+ arg_str(q, "relationType"), from, to, ty))
460+ dup = 1;
461+ }
462+ if (dup) continue;
463+ if (rel_add(&G, from, to, ty, err, sizeof err) != 0) {
464+ tool_err(t, "%s", err[0] ? err : "cannot add the relation");
465+ return;
466+ }
467+ yyjson_mut_arr_add_val(created, rel_to_mut(t->md, from, to, ty));
468+ }
469+
470+ if (graph_save(err, sizeof err) != 0) {
471+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
472+ return;
473+ }
474+ yyjson_mut_obj_add_val(t->md, t->root, "relations", created);
475+}
476+
477+/* ------------------------------------------------------------------ */
478+/* add_observations */
479+/* ------------------------------------------------------------------ */
480+
481+void tool_add_observations(yyjson_val *args, tool_out_t *t)
482+{
483+ yyjson_val *arr = arg_get(args, "observations");
484+ yyjson_mut_val *results;
485+ size_t i, max;
486+ char err[256];
487+
488+ if (!arr || !yyjson_is_arr(arr)) {
489+ tool_err(t, "Missing required parameter: observations");
490+ return;
491+ }
492+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
493+
494+ /* Validate first: an unknown entity fails the whole call. */
495+ max = yyjson_arr_size(arr);
496+ for (i = 0; i < max; i++) {
497+ yyjson_val *o_ = yyjson_arr_get(arr, i);
498+ const char *nm = o_ ? arg_str(o_, "entityName") : NULL;
499+ yyjson_val *contents = o_ ? arg_get(o_, "contents") : NULL;
500+ if (!nm || !*nm) {
501+ tool_err(t, "Each observation needs a non-empty entityName.");
502+ return;
503+ }
504+ if (!contents || !yyjson_is_arr(contents)) {
505+ tool_err(t, "Observations for %s must be an array of strings.", nm);
506+ return;
507+ }
508+ if (!ent_find(&G, nm)) {
509+ tool_err(t, "Entity with name %s not found", nm);
510+ return;
511+ }
512+ }
513+
514+ tool_start(t);
515+ if (t->is_error) return;
516+ results = yyjson_mut_arr(t->md);
517+
518+ for (i = 0; i < max; i++) {
519+ yyjson_val *o_ = yyjson_arr_get(arr, i);
520+ const char *nm = arg_str(o_, "entityName");
521+ yyjson_val *contents = arg_get(o_, "contents");
522+ entity_t *e = ent_find(&G, nm);
523+ yyjson_mut_val *one, *added_arr;
524+ size_t j, n_c;
525+
526+ if (!e) continue;
527+ one = yyjson_mut_obj(t->md);
528+ added_arr = yyjson_mut_arr(t->md);
529+ yyjson_mut_obj_add_str(t->md, one, "entityName", nm);
530+
531+ n_c = yyjson_arr_size(contents);
532+ for (j = 0; j < n_c; j++) {
533+ yyjson_val *cv = yyjson_arr_get(contents, j);
534+ const char *c;
535+ size_t k;
536+ int repeat_in_call = 0, already_there = 0;
537+ if (!cv || !yyjson_is_str(cv)) continue;
538+ c = yyjson_get_str(cv);
539+ if (!c) continue;
540+ /* A string repeated within one call is stored and reported once. */
541+ for (k = 0; k < j && !repeat_in_call; k++) {
542+ yyjson_val *pv = yyjson_arr_get(contents, k);
543+ if (pv && yyjson_is_str(pv) &&
544+ strcmp(yyjson_get_str(pv), c) == 0) repeat_in_call = 1;
545+ }
546+ if (repeat_in_call) continue;
547+ for (k = 0; k < e->n_obs; k++)
548+ if (strcmp(e->obs[k], c) == 0) { already_there = 1; break; }
549+ if (already_there) continue;
550+ if (obs_push(e, c))
551+ yyjson_mut_arr_add_str(t->md, added_arr, c);
552+ }
553+ yyjson_mut_obj_add_val(t->md, one, "addedObservations", added_arr);
554+ yyjson_mut_arr_add_val(results, one);
555+ }
556+
557+ if (graph_save(err, sizeof err) != 0) {
558+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
559+ return;
560+ }
561+ yyjson_mut_obj_add_val(t->md, t->root, "results", results);
562+}
563+
564+/* ------------------------------------------------------------------ */
565+/* delete_entities */
566+/* ------------------------------------------------------------------ */
567+
568+void tool_delete_entities(yyjson_val *args, tool_out_t *t)
569+{
570+ yyjson_val *arr = arg_get(args, "entityNames");
571+ size_t i, n_req, n_deleted = 0;
572+ char err[256];
573+ const char **names = NULL;
574+ int *present = NULL;
575+
576+ if (!arr || !yyjson_is_arr(arr)) {
577+ tool_err(t, "Missing required parameter: entityNames");
578+ return;
579+ }
580+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
581+
582+ n_req = yyjson_arr_size(arr);
583+ names = (const char **)calloc(n_req ? n_req : 1, sizeof *names);
584+ present = (int *)calloc(n_req ? n_req : 1, sizeof *present);
585+ if (!names || !present) {
586+ free((void *)names);
587+ free(present);
588+ tool_err(t, "out of memory");
589+ return;
590+ }
591+
592+ /* Record each requested name and whether the graph held it BEFORE anything
593+ * is removed. Deriving "not found" after the compaction is not possible:
594+ * a name that was deleted and a name that never existed both read as
595+ * absent, so both facts are captured here, as plain ints - the compaction
596+ * below moves G.ent entries, so no entity_t pointer may outlive this loop
597+ * (lesson: a grid of records is not a set of stable addresses). */
598+ for (i = 0; i < n_req; i++) {
599+ yyjson_val *v = yyjson_arr_get(arr, i);
600+ const char *nm = (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL;
601+ size_t k;
602+ int counted = 0;
603+ names[i] = nm;
604+ if (!nm) continue;
605+ for (k = 0; k < G.n_ent; k++)
606+ if (strcmp(G.ent[k].name, nm) == 0) { present[i] = 1; G.ent[k].keep = 1; break; }
607+ for (k = 0; k < i; k++)
608+ if (names[k] && strcmp(names[k], nm) == 0) { counted = 1; break; }
609+ if (present[i] && !counted) n_deleted++;
610+ }
611+
612+ {
613+ size_t w = 0, r2;
614+ for (r2 = 0; r2 < G.n_rel; r2++) {
615+ size_t q;
616+ int hit = 0;
617+ for (q = 0; q < n_req; q++) {
618+ const char *nm = names[q];
619+ if (!nm) continue;
620+ if (strcmp(G.rel[r2].from, nm) == 0 ||
621+ strcmp(G.rel[r2].to, nm) == 0) { hit = 1; break; }
622+ }
623+ if (hit) {
624+ free(G.rel[r2].from);
625+ free(G.rel[r2].to);
626+ free(G.rel[r2].rtype);
627+ continue;
628+ }
629+ G.rel[w++] = G.rel[r2];
630+ }
631+ G.n_rel = w;
632+ }
633+ {
634+ size_t w = 0, r2;
635+ for (r2 = 0; r2 < G.n_ent; r2++) {
636+ if (G.ent[r2].keep) {
637+ size_t q;
638+ for (q = 0; q < G.ent[r2].n_obs; q++) free(G.ent[r2].obs[q]);
639+ free(G.ent[r2].obs);
640+ free(G.ent[r2].name);
641+ free(G.ent[r2].etype);
642+ continue;
643+ }
644+ G.ent[w++] = G.ent[r2];
645+ }
646+ G.n_ent = w;
647+ }
648+
649+ if (graph_save(err, sizeof err) != 0) {
650+ free((void *)names);
651+ free(present);
652+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
653+ return;
654+ }
655+
656+ tool_start(t);
657+ if (!t->is_error) {
658+ buf_t msg;
659+ buf_init(&msg);
660+ if (n_deleted == n_req) {
661+ buf_puts(&msg, "Entities deleted successfully");
662+ } else {
663+ char tmp[96];
664+ int first = 1;
665+ snprintf(tmp, sizeof tmp, "Deleted %zu of %zu entities. Not found: ",
666+ n_deleted, n_req);
667+ buf_puts(&msg, tmp);
668+ for (i = 0; i < n_req; i++) {
669+ if (!names[i] || present[i]) continue;
670+ if (!first) buf_puts(&msg, ", ");
671+ buf_puts(&msg, names[i]);
672+ first = 0;
673+ }
674+ }
675+ yyjson_mut_obj_add_bool(t->md, t->root, "success", 1);
676+ /* add_str keeps the pointer, add_strcpy copies into the doc. The message
677+ * lives in a buf_t that is freed the moment this block ends, so the
678+ * copy is the only way it survives into the serialised result. */
679+ yyjson_mut_obj_add_strcpy(t->md, t->root, "message", buf_str(&msg));
680+ buf_free(&msg);
681+ }
682+ free((void *)names);
683+ free(present);
684+}
685+
686+/* ------------------------------------------------------------------ */
687+/* delete_observations */
688+/* ------------------------------------------------------------------ */
689+
690+void tool_delete_observations(yyjson_val *args, tool_out_t *t)
691+{
692+ yyjson_val *arr = arg_get(args, "deletions");
693+ size_t i, max, requested = 0, deleted = 0;
694+ char err[256];
695+ buf_t missing;
696+
697+ if (!arr || !yyjson_is_arr(arr)) {
698+ tool_err(t, "Missing required parameter: deletions");
699+ return;
700+ }
701+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
702+
703+ buf_init(&missing);
704+ max = yyjson_arr_size(arr);
705+ for (i = 0; i < max; i++) {
706+ yyjson_val *d = yyjson_arr_get(arr, i);
707+ const char *nm = d ? arg_str(d, "entityName") : NULL;
708+ yyjson_val *obs = d ? arg_get(d, "observations") : NULL;
709+ entity_t *e;
710+ size_t j, n_o;
711+
712+ if (!nm || !*nm) {
713+ buf_free(&missing);
714+ tool_err(t, "Each deletion needs a non-empty entityName.");
715+ return;
716+ }
717+ if (!obs || !yyjson_is_arr(obs)) {
718+ buf_free(&missing);
719+ tool_err(t, "Observations for %s must be an array of strings.", nm);
720+ return;
721+ }
722+ e = ent_find(&G, nm);
723+ n_o = yyjson_arr_size(obs);
724+ requested += n_o;
725+ if (!e) {
726+ if (missing.n) buf_puts(&missing, ", ");
727+ buf_puts(&missing, nm);
728+ continue;
729+ }
730+ for (j = 0; j < n_o; j++) {
731+ yyjson_val *v = yyjson_arr_get(obs, j);
732+ const char *c = (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL;
733+ size_t w = 0, q;
734+ if (!c) continue;
735+ for (q = 0; q < e->n_obs; q++) {
736+ if (strcmp(e->obs[q], c) == 0) { free(e->obs[q]); deleted++; continue; }
737+ e->obs[w++] = e->obs[q];
738+ }
739+ e->n_obs = w;
740+ }
741+ }
742+
743+ if (graph_save(err, sizeof err) != 0) {
744+ buf_free(&missing);
745+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
746+ return;
747+ }
748+
749+ tool_start(t);
750+ if (!t->is_error) {
751+ buf_t msg;
752+ buf_init(&msg);
753+ if (deleted == requested) {
754+ buf_puts(&msg, "Observations deleted successfully");
755+ } else {
756+ char tmp[96];
757+ snprintf(tmp, sizeof tmp, "Deleted %zu of %zu observations.",
758+ deleted, requested);
759+ buf_puts(&msg, tmp);
760+ if (missing.n) {
761+ buf_puts(&msg, " Entities not found: ");
762+ buf_puts(&msg, buf_str(&missing));
763+ }
764+ }
765+ yyjson_mut_obj_add_bool(t->md, t->root, "success", 1);
766+ /* add_str keeps the pointer, add_strcpy copies into the doc. The message
767+ * lives in a buf_t that is freed the moment this block ends, so the
768+ * copy is the only way it survives into the serialised result. */
769+ yyjson_mut_obj_add_strcpy(t->md, t->root, "message", buf_str(&msg));
770+ buf_free(&msg);
771+ }
772+ buf_free(&missing);
773+}
774+
775+/* ------------------------------------------------------------------ */
776+/* delete_relations */
777+/* ------------------------------------------------------------------ */
778+
779+void tool_delete_relations(yyjson_val *args, tool_out_t *t)
780+{
781+ yyjson_val *arr = arg_get(args, "relations");
782+ size_t max, before, deleted;
783+ char err[256];
784+
785+ if (!arr || !yyjson_is_arr(arr)) {
786+ tool_err(t, "Missing required parameter: relations");
787+ return;
788+ }
789+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
790+ max = yyjson_arr_size(arr);
791+
792+ before = G.n_rel;
793+ {
794+ size_t w = 0, r2;
795+ for (r2 = 0; r2 < G.n_rel; r2++) {
796+ size_t q;
797+ int hit = 0;
798+ for (q = 0; q < max; q++) {
799+ yyjson_val *d = yyjson_arr_get(arr, q);
800+ if (!d || !yyjson_is_obj(d)) continue;
801+ if (rel_same_fields(arg_str(d, "from"), arg_str(d, "to"),
802+ arg_str(d, "relationType"),
803+ G.rel[r2].from, G.rel[r2].to,
804+ G.rel[r2].rtype)) { hit = 1; break; }
805+ }
806+ if (hit) {
807+ free(G.rel[r2].from);
808+ free(G.rel[r2].to);
809+ free(G.rel[r2].rtype);
810+ continue;
811+ }
812+ G.rel[w++] = G.rel[r2];
813+ }
814+ G.n_rel = w;
815+ }
816+ deleted = before - G.n_rel;
817+
818+ if (graph_save(err, sizeof err) != 0) {
819+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
820+ return;
821+ }
822+
823+ tool_start(t);
824+ if (!t->is_error) {
825+ buf_t msg;
826+ buf_init(&msg);
827+ if (deleted == max) {
828+ buf_puts(&msg, "Relations deleted successfully");
829+ } else {
830+ char tmp[128];
831+ snprintf(tmp, sizeof tmp,
832+ "Deleted %zu of %zu relations. The rest matched nothing.",
833+ deleted, max);
834+ buf_puts(&msg, tmp);
835+ }
836+ yyjson_mut_obj_add_bool(t->md, t->root, "success", 1);
837+ /* add_str keeps the pointer, add_strcpy copies into the doc. The message
838+ * lives in a buf_t that is freed the moment this block ends, so the
839+ * copy is the only way it survives into the serialised result. */
840+ yyjson_mut_obj_add_strcpy(t->md, t->root, "message", buf_str(&msg));
841+ buf_free(&msg);
842+ }
843+}
844+
845+/* ------------------------------------------------------------------ */
846+/* The read tools */
847+/* ------------------------------------------------------------------ */
848+
849+void tool_read_graph(yyjson_val *args, tool_out_t *t)
850+{
851+ read_opt_t o;
852+ read_opt_init(&o);
853+ if (parse_read_opts(args, &o) != 0) {
854+ read_opt_free_types(&o);
855+ tool_err(t, "observationLimit must be an integer >= 0 and entityTypes "
856+ "a non-empty array of strings.");
857+ return;
858+ }
859+ if (graph_load() != 0) {
860+ read_opt_free_types(&o);
861+ tool_err(t, "%s", g_data_err[0]);
862+ return;
863+ }
864+ tool_start(t);
865+ if (!t->is_error) emit_all(t, &o);
866+ read_opt_free_types(&o);
867+}
868+
869+void tool_search_nodes(yyjson_val *args, tool_out_t *t)
870+{
871+ read_opt_t o;
872+ const char *query;
873+ entity_t **hits;
874+ size_t i, n_hits = 0, cap;
875+ int rc;
876+
877+ read_opt_init(&o);
878+ if (!args || !yyjson_is_str(yyjson_obj_get(args, "query"))) {
879+ tool_err(t, "Missing required parameter: query");
880+ return;
881+ }
882+ query = yyjson_get_str(yyjson_obj_get(args, "query"));
883+ rc = arg_opt_int(args, "limit", 1, &o.max_entities);
884+ if (rc == -1) { tool_err(t, "limit must be an integer >= 1"); return; }
885+ if (parse_read_opts(args, &o) != 0) {
886+ read_opt_free_types(&o);
887+ tool_err(t, "observationLimit must be an integer >= 0.");
888+ return;
889+ }
890+ if (graph_load() != 0) {
891+ read_opt_free_types(&o);
892+ tool_err(t, "%s", g_data_err[0]);
893+ return;
894+ }
895+
896+ cap = G.n_ent ? G.n_ent : 1;
897+ hits = (entity_t **)malloc(cap * sizeof *hits);
898+ if (!hits) { read_opt_free_types(&o); tool_err(t, "out of memory"); return; }
899+
900+ for (i = 0; i < G.n_ent; i++) {
901+ size_t q;
902+ int hit = str_icontains(G.ent[i].name, query) ||
903+ str_icontains(G.ent[i].etype, query);
904+ for (q = 0; !hit && q < G.ent[i].n_obs; q++)
905+ if (str_icontains(G.ent[i].obs[q], query)) hit = 1;
906+ if (hit) hits[n_hits++] = &G.ent[i];
907+ if (o.max_entities > 0 && n_hits >= (size_t)o.max_entities) break;
908+ }
909+
910+ tool_start(t);
911+ if (!t->is_error) emit_set(t, hits, n_hits, &o);
912+ free(hits);
913+ read_opt_free_types(&o);
914+}
915+
916+void tool_open_nodes(yyjson_val *args, tool_out_t *t)
917+{
918+ read_opt_t o;
919+ yyjson_val *arr;
920+ entity_t **want;
921+ size_t i, max, n_want = 0;
922+
923+ read_opt_init(&o);
924+ if (!args) { tool_err(t, "Missing required parameter: names"); return; }
925+ arr = yyjson_obj_get(args, "names");
926+ if (!arr || !yyjson_is_arr(arr)) {
927+ tool_err(t, "Missing required parameter: names");
928+ return;
929+ }
930+ if (parse_read_opts(args, &o) != 0) {
931+ read_opt_free_types(&o);
932+ tool_err(t, "observationLimit must be an integer >= 0.");
933+ return;
934+ }
935+ if (graph_load() != 0) {
936+ read_opt_free_types(&o);
937+ tool_err(t, "%s", g_data_err[0]);
938+ return;
939+ }
940+
941+ max = yyjson_arr_size(arr);
942+ want = (entity_t **)malloc(((max ? max : 1)) * sizeof *want);
943+ if (!want) { read_opt_free_types(&o); tool_err(t, "out of memory"); return; }
944+
945+ /* Stored order, one entry per matching entity; names that miss are
946+ * simply skipped. */
947+ for (i = 0; i < G.n_ent && n_want < max; i++) {
948+ size_t q;
949+ for (q = 0; q < max; q++) {
950+ yyjson_val *v = yyjson_arr_get(arr, q);
951+ const char *nm = (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL;
952+ if (nm && strcmp(nm, G.ent[i].name) == 0) { want[n_want++] = &G.ent[i]; break; }
953+ }
954+ }
955+
956+ tool_start(t);
957+ if (!t->is_error) emit_set(t, want, n_want, &o);
958+ free(want);
959+ read_opt_free_types(&o);
960+}
961+
962+/* ------------------------------------------------------------------ */
963+/* tools/list */
964+/* ------------------------------------------------------------------ */
965+
966+static const char *TOOLS_LIST_JSON =
967+"["
968+"{\"name\":\"create_entities\","
969+"\"description\":\"Create multiple new entities in the knowledge graph. An entity whose name already exists, or repeats an earlier entity in the same call, is skipped and its observations are not added; the result lists the skipped names in `skipped`. Use add_observations to add observations to an existing entity.\","
970+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"entities\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\",\"description\":\"The name of the entity\"},\"entityType\":{\"type\":\"string\",\"description\":\"The type of the entity\"},\"observations\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of observation contents associated with the entity\"}},\"required\":[\"name\",\"entityType\",\"observations\"]},\"description\":\"The entities to create, each with a name unique in the graph\"}},\"required\":[\"entities\"]},"
971+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}},"
972+
973+"{\"name\":\"create_relations\","
974+"\"description\":\"Create multiple new relations between entities in the knowledge graph. Relations should be in active voice.\","
975+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"relations\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"from\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation starts\"},\"to\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation ends\"},\"relationType\":{\"type\":\"string\",\"description\":\"The type of the relation\"}},\"required\":[\"from\",\"to\",\"relationType\"]},\"description\":\"The relations to create. Both ends must name existing entities; a relation already in the graph is not added again\"}},\"required\":[\"relations\"]},"
976+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}},"
977+
978+"{\"name\":\"add_observations\","
979+"\"description\":\"Add new observations to existing entities in the knowledge graph.\","
980+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"observations\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"entityName\":{\"type\":\"string\",\"description\":\"The name of the entity to add the observations to\"},\"contents\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of observation contents to add\"}},\"required\":[\"entityName\",\"contents\"]},\"description\":\"The observations to add, grouped by entity. Each entity must already exist; an observation it already has is not added again\"}},\"required\":[\"observations\"]},"
981+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}},"
982+
983+"{\"name\":\"delete_entities\","
984+"\"description\":\"Delete whole entities from the knowledge graph, together with every relation that points to or from them and all their observations. Use it only to remove an entity entirely; to remove a link between two entities and keep both, use delete_relations, and to remove facts from an entity, use delete_observations. Cannot be undone.\","
985+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"entityNames\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of entity names to delete\"}},\"required\":[\"entityNames\"]},"
986+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":true,\"openWorldHint\":false}},"
987+
988+"{\"name\":\"delete_observations\","
989+"\"description\":\"Delete specific observations from entities in the knowledge graph.\","
990+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"deletions\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"entityName\":{\"type\":\"string\",\"description\":\"The name of the entity containing the observations\"},\"observations\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of observations to delete\"}},\"required\":[\"entityName\",\"observations\"]},\"description\":\"The observations to delete, grouped by entity, each matched by its exact text\"}},\"required\":[\"deletions\"]},"
991+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":true,\"openWorldHint\":false}},"
992+
993+"{\"name\":\"delete_relations\","
994+"\"description\":\"Delete specific relations (from, to, relationType) from the knowledge graph and keep the entities they connect. Each relation must match an existing one exactly on all three fields; if unsure, call open_nodes (or search_nodes) first to read the stored relationType. Use it to remove a link between two entities; to remove an entity itself, use delete_entities. Cannot be undone.\","
995+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"relations\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"from\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation starts\"},\"to\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation ends\"},\"relationType\":{\"type\":\"string\",\"description\":\"The type of the relation\"}},\"required\":[\"from\",\"to\",\"relationType\"]},\"description\":\"An array of relations to delete\"}},\"required\":[\"relations\"]},"
996+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":true,\"openWorldHint\":false}},"
997+
998+"{\"name\":\"read_graph\","
999+"\"description\":\"Read the entire knowledge graph: every entity with its observations, and every relation. The result grows with the graph, so use this only when you need everything; prefer search_nodes to find entities by keyword and open_nodes to read entities whose names you know.\","
1000+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"entityTypes\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"Return only entities whose entityType is one of these (exact match), and only the relations that touch one of them. Omit to return every entity.\"},\"observationLimit\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"Return at most this many observations per entity (the first ones, in the order they were added) and add each entity's total as observationCount. Use 0 for names, types and counts only: a cheap overview of a large graph, after which open_nodes reads the entities you need in full. Omit to return every observation.\"}}},"
1001+"\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}},"
1002+
1003+"{\"name\":\"search_nodes\","
1004+"\"description\":\"Search the knowledge graph for entities whose name, type or observations contain the query (case-insensitive). Use this when you have a keyword, a topic or part of a name but not the exact entity names. Prefer open_nodes when you already know the exact names, and use read_graph only when you need the whole graph. Returns the matching entities and every relation that touches one of them.\","
1005+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\",\"description\":\"The search query to match against entity names, types and observation content\"},\"limit\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Return at most this many matching entities (the first matches, in stored order), with the relations that touch them. Omit to return every match.\"},\"observationLimit\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"Return at most this many observations per entity (the first ones, in the order they were added) and add each entity's total as observationCount. Use 0 for names, types and counts only: a cheap overview of a large graph, after which open_nodes reads the entities you need in full. Omit to return every observation.\"}},\"required\":[\"query\"]},"
1006+"\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}},"
1007+
1008+"{\"name\":\"open_nodes\","
1009+"\"description\":\"Retrieve specific entities by their exact names, with every relation that touches one of them. Use this when you already know the names (from the conversation, or from an earlier search_nodes or read_graph result); it is the cheapest way to read entities you can name. Prefer search_nodes when you only have a keyword or part of a name. Names that do not exist are skipped.\","
1010+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"names\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of entity names to retrieve\"},\"observationLimit\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"Return at most this many observations per entity (the first ones, in the order they were added) and add each entity's total as observationCount. Use 0 for names, types and counts only: a cheap overview of a large graph, after which open_nodes reads the entities you need in full. Omit to return every observation.\"}},\"required\":[\"names\"]},"
1011+"\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}}"
1012+"]";
1013+
1014+char *tools_list_json(void)
1015+{
1016+ return dup_or_null(TOOLS_LIST_JSON);
1017+}
1018+
1019+int tool_dispatch(const char *name, yyjson_val *args, tool_out_t *out)
1020+{
1021+ tool_out_init(out);
1022+ if (!name) return -1;
1023+ if (strcmp(name, "create_entities") == 0) { tool_create_entities(args, out); return 0; }
1024+ if (strcmp(name, "create_relations") == 0) { tool_create_relations(args, out); return 0; }
1025+ if (strcmp(name, "add_observations") == 0) { tool_add_observations(args, out); return 0; }
1026+ if (strcmp(name, "delete_entities") == 0) { tool_delete_entities(args, out); return 0; }
1027+ if (strcmp(name, "delete_observations") == 0) { tool_delete_observations(args, out); return 0; }
1028+ if (strcmp(name, "delete_relations") == 0) { tool_delete_relations(args, out); return 0; }
1029+ if (strcmp(name, "read_graph") == 0) { tool_read_graph(args, out); return 0; }
1030+ if (strcmp(name, "search_nodes") == 0) { tool_search_nodes(args, out); return 0; }
1031+ if (strcmp(name, "open_nodes") == 0) { tool_open_nodes(args, out); return 0; }
1032+ return -1;
1033+}
1034+
1035+/* ------------------------------------------------------------------ */
1036+/* Serialisation */
1037+/* ------------------------------------------------------------------ */
1038+
1039+char *tool_mcp_result(tool_out_t *t)
1040+{
1041+ buf_t b;
1042+ char *out;
1043+
1044+ buf_init(&b);
1045+ if (t->is_error) {
1046+ /* A tool-level failure is a *result* with isError, not a JSON-RPC
1047+ * error: the call itself succeeded and this is what hosts render. */
1048+ buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":");
1049+ json_str(&b, t->error ? t->error : "the tool could not be completed");
1050+ buf_puts(&b, "}],\"isError\":true}");
1051+ out = dup_or_null(buf_str(&b));
1052+ buf_free(&b);
1053+ return out;
1054+ }
1055+
1056+ {
1057+ char *pretty = (t->md && t->root)
1058+ ? yyjson_mut_write(t->md, YYJSON_WRITE_PRETTY_TWO_SPACES, NULL)
1059+ : dup_or_null("{}");
1060+ buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":");
1061+ json_str(&b, pretty ? pretty : "{}");
1062+ buf_puts(&b, "}");
1063+ free(pretty);
1064+ if (t->notice && *t->notice) {
1065+ buf_puts(&b, ",{\"type\":\"text\",\"text\":");
1066+ json_str(&b, t->notice);
1067+ buf_puts(&b, "}");
1068+ }
1069+ buf_puts(&b, "],\"isError\":false");
1070+ }
1071+
1072+ if (t->md && t->root && yyjson_mut_obj_size(t->root) > 0) {
1073+ char *compact = yyjson_mut_write(t->md, 0, NULL);
1074+ if (compact) {
1075+ buf_puts(&b, ",\"structuredContent\":");
1076+ buf_puts(&b, compact);
1077+ free(compact);
1078+ }
1079+ }
1080+ buf_puts(&b, "}");
1081+ out = dup_or_null(buf_str(&b));
1082+ buf_free(&b);
1083+ return out;
1084+}
1085+
1086+char *tool_api_result(tool_out_t *t)
1087+{
1088+ buf_t b;
1089+ char *out;
1090+
1091+ buf_init(&b);
1092+ if (t->is_error) {
1093+ buf_puts(&b, "{\"ok\":false,\"error\":");
1094+ json_str(&b, t->error ? t->error : "the tool could not be completed");
1095+ buf_puts(&b, "}");
1096+ out = dup_or_null(buf_str(&b));
1097+ buf_free(&b);
1098+ return out;
1099+ }
1100+ if (!t->md || !t->root || yyjson_mut_obj_size(t->root) == 0) {
1101+ buf_free(&b);
1102+ return dup_or_null("{\"ok\":true}");
1103+ }
1104+ {
1105+ /* The result object always begins with '{', so splicing ok in front
1106+ * of it is a byte-level operation on JSON this very document
1107+ * produced - one buffer, one write, no re-parsing (and no field
1108+ * reordering, which a half-buffer/half-printf builder causes). */
1109+ char *compact = yyjson_mut_write(t->md, 0, NULL);
1110+ if (!compact) {
1111+ buf_free(&b);
1112+ return dup_or_null("{\"ok\":false,\"error\":\"could not "
1113+ "serialise the result\"}");
1114+ }
1115+ buf_puts(&b, "{\"ok\":true");
1116+ if (compact[0] == '{' && compact[1] != '}') {
1117+ buf_putc(&b, ',');
1118+ buf_puts(&b, compact + 1); /* keeps the trailing '}' */
1119+ } else {
1120+ buf_puts(&b, "}");
1121+ }
1122+ free(compact);
1123+ }
1124+ out = dup_or_null(buf_str(&b));
1125+ buf_free(&b);
1126+ return out;
1127+}
src/ui.html+266−0■■■■■
11new file mode 100644
index 0000000..c300526
--- /dev/null
+++ b/src/ui.html
@@ -0,0 +1,384 @@
1+<!DOCTYPE html>
2+<html lang="en"><head><meta charset="utf-8">
3+<meta name="viewport" content="width=device-width,initial-scale=1">
4+<title>memory - knowledge graph</title>
5+<!--TOKENS-->
6+<style>
7+*{box-sizing:border-box}
8+html,body{margin:0;height:100%}
9+body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;
10+ line-height:1.5;-webkit-font-smoothing:antialiased;overflow:hidden}
11+#app{display:grid;grid-template-columns:320px minmax(0,1fr);height:100%;min-height:0}
12+.pane{min-width:0;min-height:0;display:flex;flex-direction:column}
13+#side{background:var(--bg-2);border-right:1px solid var(--line)}
14+.hd{display:flex;align-items:center;gap:8px;padding:11px 12px 9px}
15+.brand{font-size:12px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;
16+ color:var(--text-2);flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
17+.icon{display:inline-flex;align-items:center;justify-content:center;background:var(--surface-2);
18+ border:1px solid var(--line);color:var(--text);border-radius:9px;width:30px;height:30px;
19+ padding:0;cursor:pointer;font-family:inherit;font-size:13px;font-weight:600;flex:none}
20+.icon:hover{background:var(--surface-hover);border-color:var(--line-2)}
21+.icon:active{transform:scale(.96)}
22+.icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor;stroke-width:1.8;
23+ stroke-linecap:round;stroke-linejoin:round}
24+.search{margin:0 12px 8px;padding:8px 11px;border-radius:9px;border:1px solid var(--line);
25+ background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px;width:calc(100% - 24px)}
26+.search:focus{outline:2px solid var(--blue);outline-offset:-1px}
27+.chips{display:flex;flex-wrap:wrap;gap:5px;padding:0 12px 8px}
28+.chip{background:var(--surface-2);border:1px solid var(--line);color:var(--text-2);
29+ border-radius:980px;padding:2px 9px;font-size:11px;font-family:inherit;cursor:pointer;
30+ max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
31+.chip.on{background:var(--blue);border-color:var(--blue);color:#fff}
32+.list{flex:1 1 auto;overflow-y:auto;padding:0 8px 8px}
33+.item{display:block;width:100%;text-align:left;background:transparent;border:0;border-radius:10px;
34+ padding:8px 10px;color:var(--text);cursor:pointer;font-family:inherit;margin-bottom:2px}
35+.item:hover{background:var(--surface-hover)}
36+.item.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)}
37+.irow{display:flex;align-items:baseline;gap:7px}
38+.iname{font-weight:600;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
39+.icount{font-size:11px;color:var(--text-2);font-variant-numeric:tabular-nums;flex:none}
40+.itype{display:inline-block;margin-top:2px;font-size:10.5px;letter-spacing:.03em;text-transform:uppercase;
41+ color:var(--teal);background:var(--surface-2);border-radius:5px;padding:1px 6px;max-width:100%;
42+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
43+#main{overflow-y:auto}
44+.mainhd{display:flex;align-items:center;gap:8px;padding:11px 14px;border-bottom:1px solid var(--line);
45+ position:sticky;top:0;background:var(--bg);z-index:2;flex-wrap:wrap}
46+.title{font-size:15px;font-weight:700;flex:1;min-width:0;overflow-wrap:anywhere}
47+.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:6px 13px;font-weight:600;
48+ font-size:12.5px;cursor:pointer;font-family:inherit;white-space:nowrap}
49+.btn:active{transform:scale(.98)}
50+.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}
51+.btn.danger{background:transparent;color:var(--red);border:1px solid var(--line);padding:3px 9px;
52+ font-size:11.5px;font-weight:600}
53+.body{padding:14px;display:flex;flex-direction:column;gap:16px}
54+.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;padding:13px 14px}
55+.card h3{margin:0 0 9px;font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;
56+ color:var(--text-2)}
57+.obs{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
58+.obs li{display:flex;gap:9px;align-items:flex-start;background:var(--surface-2);border-radius:9px;
59+ padding:7px 10px;font-size:13px}
60+.obs li span{flex:1;min-width:0;overflow-wrap:anywhere}
61+.rel{display:flex;gap:9px;align-items:baseline;padding:6px 0;border-top:1px solid var(--line);font-size:13px}
62+.rel:first-of-type{border-top:0;padding-top:0}
63+.rel .arrow{color:var(--text-2);flex:none;font-size:12px}
64+.rel b{font-weight:600;overflow-wrap:anywhere}
65+.rel .rt{color:var(--orange);font-size:11.5px;font-weight:600;overflow-wrap:anywhere}
66+.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
67+input,select{background:var(--input-bg);border:1px solid var(--line);color:var(--text);
68+ border-radius:9px;padding:7px 10px;font-family:inherit;font-size:13px;min-width:0;flex:1 1 130px}
69+input:focus,select:focus{outline:2px solid var(--blue);outline-offset:-1px}
70+.hint{font-size:11.5px;color:var(--text-2);margin:0}
71+.empty{text-align:center;padding:56px 22px;color:var(--text-2)}
72+.empty b{display:block;color:var(--text);font-size:15px;margin-bottom:6px;font-weight:600}
73+.svgwrap{margin:0 auto 12px;width:74px;height:74px;opacity:.85}
74+.svgwrap svg{width:100%;height:100%;fill:none;stroke:var(--blue);stroke-width:1.6}
75+.status{font-size:11.5px;color:var(--text-2);padding:0 14px 12px;min-height:16px;overflow-wrap:anywhere}
76+.status.bad{color:var(--red)}
77+.status.ok{color:var(--green)}
78+.ft{border-top:1px solid var(--line);display:flex;align-items:center;gap:8px;padding:8px 12px;
79+ font-size:11px;color:var(--text-2)}
80+.ft .grow{flex:1}
81+.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}
82+@media (max-width:820px){
83+ #app{grid-template-columns:1fr}
84+ #side{border-right:0;border-bottom:1px solid var(--line);max-height:46vh}
85+ body[data-view="detail"] #side{display:none}
86+ body:not([data-view="detail"]) #main{display:none}
87+}
88+</style>
89+</head><body>
90+<div id="app">
91+ <section class="pane" id="side">
92+ <div class="hd">
93+ <span class="brand">knowledge graph</span>
94+ <button class="icon" id="btnTheme" title="Theme" aria-label="Toggle theme">
95+ <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4.2"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M18.4 5.6L17 7M7 17l-1.4 1.4"/></svg>
96+ </button>
97+ </div>
98+ <input class="search" id="q" type="search" placeholder="Search names, types, observations" aria-label="Search the graph">
99+ <div class="chips" id="chips"></div>
100+ <div class="list" id="list"></div>
101+ <div class="ft">
102+ <span class="grow" id="tally">loading</span>
103+ <button class="icon" id="btnNew" title="New entity" aria-label="New entity">
104+ <svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>
105+ </button>
106+ </div>
107+ </section>
108+
109+ <section class="pane" id="main">
110+ <div class="mainhd">
111+ <button class="icon" id="btnBack" title="Back to list" aria-label="Back to list" style="display:none">
112+ <svg viewBox="0 0 24 24"><path d="M14 6l-6 6 6 6"/></svg>
113+ </button>
114+ <span class="title" id="title">Select an entity</span>
115+ <button class="btn ghost" id="btnReload" title="Reload">Reload</button>
116+ </div>
117+ <div id="detail" class="body"></div>
118+ <div class="status" id="status"></div>
119+ </section>
120+</div>
121+
122+<script>
123+(function(){
124+"use strict";
125+var q=new URLSearchParams(location.search);
126+var node=q.get('node')||'';
127+var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||
128+ localStorage.getItem('bot_active_pwd')||'';
129+/* Two ways to reach us: the bot's hub proxies /plugins?plugin=plugin_memory,
130+ * while a directly-opened node route is /plugin_memory. Hitting the wrong one
131+ * renders the plugin-LIST JSON instead of the page, so branch on the URL
132+ * rather than assuming the hub. */
133+var ROUTE=q.has('plugin')?'plugins':'plugin_memory';
134+
135+function url(action,extra){
136+ var p=[];
137+ if(q.has('plugin'))p.push('plugin=plugin_memory');
138+ p.push('action='+encodeURIComponent(action));
139+ if(node)p.push('node='+encodeURIComponent(node));
140+ if(pwd)p.push('pwd='+encodeURIComponent(pwd));
141+ if(extra)for(var k in extra)p.push(encodeURIComponent(k)+'='+encodeURIComponent(extra[k]));
142+ return '/'+ROUTE+'?'+p.join('&');
143+}
144+function hdr(x){var h={};for(var k in x)h[k]=x[k];if(pwd)h['X-Bot-Password']=pwd;return h;}
145+function api(action,extra){
146+ return fetch(url(action,extra),{headers:hdr({})}).then(function(r){
147+ if(!r.ok)throw new Error('HTTP '+r.status);
148+ return r.json();
149+ });
150+}
151+function post(action,obj){
152+ return fetch(url(action),{method:'POST',headers:hdr({'Content-Type':'application/json'}),
153+ body:JSON.stringify(obj)}).then(function(r){return r.json().then(function(j){j.__s=r.status;return j;});});
154+}
155+
156+var el=function(id){return document.getElementById(id);};
157+var listEl=el('list'),titleEl=el('title'),detailEl=el('detail'),statusEl=el('status'),
158+ tallyEl=el('tally'),chipsEl=el('chips'),qEl=el('q');
159+var entities=[],sel=null,typeFilter='',timer=null;
160+
161+function say(msg,cls){statusEl.textContent=msg||'';statusEl.className='status'+(cls?' '+cls:'');}
162+
163+function esc(s){return String(s==null?'':s).replace(/[&<>"']/g,function(c){
164+ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];});}
165+
166+function graphThen(fn){
167+ api('graph',{limit:'2000'}).then(function(j){
168+ if(j.ok===false){say(j.error,'bad');return;}
169+ entities=j.entities||[];
170+ fn&&fn();
171+ }).catch(function(e){say('could not read the graph: '+e.message,'bad');});
172+}
173+
174+function tally(){
175+ var n=0,i;
176+ for(i=0;i<entities.length;i++)n+=entities[i].observations.length;
177+ tallyEl.textContent=entities.length+' entities, '+n+' observations';
178+}
179+
180+function chips(){
181+ var seen={},out=[],i;
182+ for(i=0;i<entities.length;i++){var t=entities[i].entityType;if(!seen[t]){seen[t]=1;out.push(t);}}
183+ out.sort(function(a,b){return a.toLowerCase()<b.toLowerCase()?-1:1;});
184+ var h='<button class="chip'+(typeFilter===''?' on':'')+'" data-t="">all</button>';
185+ for(i=0;i<out.length&&i<40;i++)
186+ h+='<button class="chip'+(typeFilter===out[i]?' on':'')+'" data-t="'+esc(out[i])+'">'+esc(out[i])+'</button>';
187+ chipsEl.innerHTML=h;
188+ Array.prototype.forEach.call(chipsEl.querySelectorAll('.chip'),function(b){
189+ b.onclick=function(){typeFilter=b.getAttribute('data-t')||'';renderList();};
190+ });
191+}
192+
193+function renderList(){
194+ var term=(qEl.value||'').toLowerCase().trim(),rows=[],i,j,hit;
195+ for(i=0;i<entities.length;i++){
196+ var e=entities[i];
197+ if(typeFilter&&e.entityType!==typeFilter)continue;
198+ if(term){
199+ hit=e.name.toLowerCase().indexOf(term)>=0||
200+ e.entityType.toLowerCase().indexOf(term)>=0;
201+ for(j=0;!hit&&j<e.observations.length;j++)
202+ if(e.observations[j].toLowerCase().indexOf(term)>=0)hit=true;
203+ if(!hit)continue;
204+ }
205+ rows.push(e);
206+ }
207+ if(!rows.length){
208+ listEl.innerHTML='<div class="empty"><b>Nothing here</b>'+
209+ (entities.length?'No entity matches this filter.':'Add your first entity with the plus below.')+
210+ '</div>';
211+ chips();tally();return;
212+ }
213+ listEl.innerHTML=rows.map(function(e){
214+ return '<button class="item'+(sel&&sel===e.name?' sel':'')+'" data-n="'+esc(e.name)+'">'+
215+ '<span class="irow"><span class="iname">'+esc(e.name)+'</span>'+
216+ '<span class="icount">'+e.observations.length+'</span></span>'+
217+ '<span class="itype">'+esc(e.entityType)+'</span></button>';
218+ }).join('');
219+ Array.prototype.forEach.call(listEl.querySelectorAll('.item'),function(b){
220+ b.onclick=function(){open(b.getAttribute('data-n'));};
221+ });
222+ chips();tally();
223+}
224+
225+function relationRows(rels,dir){
226+ if(!rels.length)return '<p class="hint">None yet.</p>';
227+ return rels.map(function(r){
228+ var other=dir==='out'?r.to:r.from;
229+ return '<div class="rel"><b>'+esc(dir==='out'?r.from:r.to)+'</b>'+
230+ '<span class="arrow">'+(dir==='out'?'to':'from')+'</span>'+
231+ '<span class="rt">'+esc(r.relationType)+'</span>'+
232+ '<span style="flex:1"></span>'+
233+ '<button class="btn danger" data-delrel="'+esc(r.from)+'|'+esc(r.to)+'|'+esc(r.relationType)+'">remove</button>'+
234+ '</div>';
235+ }).join('');
236+}
237+
238+function open(name){
239+ sel=name;
240+ document.body.setAttribute('data-view','detail');
241+ el('btnBack').style.display='';
242+ renderList();
243+ api('entity',{name:name}).then(function(j){
244+ if(j.ok===false){say(j.error,'bad');return;}
245+ var ents=j.entities||[],rels=j.relations||[];
246+ if(!ents.length){titleEl.textContent=name;detailEl.innerHTML=
247+ '<div class="empty"><b>Gone</b>That entity is no longer in the graph.</div>';return;}
248+ var e=ents[0],i,out=[],inn=[];
249+ for(i=0;i<rels.length;i++){
250+ if(rels[i].from===e.name)out.push(rels[i]);
251+ if(rels[i].to===e.name)inn.push(rels[i]);
252+ }
253+ titleEl.textContent=e.name;
254+ detailEl.innerHTML=
255+ '<div class="card"><h3>'+esc(e.entityType)+'</h3><div class="row">'+
256+ '<button class="btn danger" data-dele="'+esc(e.name)+'">Delete entity</button>'+
257+ '<span class="hint">'+e.observations.length+' observation(s), '+rels.length+' relation(s)</span>'+
258+ '</div></div>'+
259+ '<div class="card"><h3>Observations</h3><ul class="obs">'+
260+ (e.observations.length?e.observations.map(function(o){
261+ return '<li><span>'+esc(o)+'</span><button class="btn danger" data-delo="'+
262+ esc(e.name)+'|'+esc(o)+'">remove</button></li>';}).join('')
263+ :'<li><span class="hint">No observations yet.</span></li>')+
264+ '</ul><div class="row" style="margin-top:10px">'+
265+ '<input id="newObs" placeholder="Add an observation" aria-label="New observation">'+
266+ '<button class="btn" id="addObs">Add</button></
.gitignore+19−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..f373ac1index 0000000..f373ac1
--- /dev/null--- /dev/null
+++ b/.gitignore+++ b/.gitignore
@@ -0,0 +1,19 @@@@ -0,0 +1,19 @@
1+# build artifacts
2+plugin_memory
3+plugin_memory.exe
4+plugin_memory.musl
5+plugin_memory.arm64
6+plugin_memory.macos-arm64
7+plugin_memory.macos-x86_64
8+plugin_memory.asan
9+bin/
10+
11+# local graph stores (never commit anyone's memory)
12+.memory-store/
13+*.jsonl
14+*.jsonl.tmp.*
15+*.jsonl.lock
16+
17+# python tooling
18+__pycache__/
19+*.pyc
LICENSE+21−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ef80120index 0000000..ef80120
--- /dev/null--- /dev/null
+++ b/LICENSE+++ b/LICENSE
@@ -0,0 +1,21 @@@@ -0,0 +1,21 @@
1+MIT License
2+
3+Copyright (c) 2026 SCORPIOX INC
4+
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
11+
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
14+
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
Makefile+93−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..19138f2index 0000000..19138f2
--- /dev/null--- /dev/null
+++ b/Makefile+++ b/Makefile
@@ -0,0 +1,93 @@@@ -0,0 +1,93 @@
1+# plugin_memory - SCORPIOX BOT open-source knowledge-graph memory connector
2+#
3+# Targets:
4+# make native build -> ./plugin_memory
5+# make musl static musl x86_64 -> ./plugin_memory.musl
6+# make arm64 static arm64 musl (aarch64 cross) -> ./plugin_memory.arm64
7+# make win64 MinGW-w64 static -> ./plugin_memory.exe
8+# make macos Apple clang -> ./plugin_memory (run this on macOS)
9+# make ui regenerate src/ui_html.h from src/ui.html
10+# make asan ASan/UBSan + _FORTIFY_SOURCE=2 build -> ./plugin_memory.asan
11+# make test build + run tests/run.sh
12+# make e2e build + run tests/e2e.py (Playwright)
13+# make clean
14+#
15+# The binary is four translation units plus the vendored yyjson amalgamation:
16+# src/plugin_memory.c entry, --meta, the --mcp JSON-RPC loop
17+# src/graph.c JSONL storage, atomic save, the store, shared helpers
18+# src/tools.c the nine tools, shared by --mcp and the HTTP API
19+# src/api.c the CGI JSON actions and the HTML page
20+# vendor/yyjson.c vendored JSON parser/writer (zero runtime deps)
21+
22+CC ?= cc
23+SRCS := src/plugin_memory.c src/graph.c src/tools.c src/api.c vendor/yyjson.c
24+CFLAGS ?= -O2 -std=c99 -Wall -Wextra -pedantic -Wno-overlength-strings -I src -I vendor
25+MUSL_CC ?= musl-gcc
26+MUSL_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor -static
27+ARM_CC ?= aarch64-linux-gnu-gcc
28+ARM_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor -static
29+WIN_CC ?= x86_64-w64-mingw32-gcc
30+WIN_CFLAGS := -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor -static
31+UI_SRC := src/ui.html
32+UI_HDR := src/ui_html.h
33+BIN := plugin_memory
34+EXE := plugin_memory.exe
35+
36+.PHONY: all native musl arm64 win64 macos ui asan test e2e clean help
37+
38+all: native
39+
40+$(UI_HDR): $(UI_SRC) tools/gen_ui.py
41+ @echo "==> regenerating $(UI_HDR)"
42+ python3 tools/gen_ui.py
43+
44+ui: $(UI_HDR)
45+
46+native: $(BIN)
47+
48+$(BIN): $(SRCS) $(UI_HDR)
49+ @echo "==> native build ($(CC))"
50+ $(CC) $(CFLAGS) -o $(BIN) $(SRCS)
51+
52+# Static musl build - the universal Linux artifact (Alpine, Debian, Arch, Omarchy)
53+musl: $(SRCS) $(UI_HDR)
54+ @echo "==> static musl build ($(MUSL_CC))"
55+ $(MUSL_CC) $(MUSL_CFLAGS) -o $(BIN).musl $(SRCS)
56+
57+# Static aarch64 build - Raspberry Pi 5 / ARM64 servers
58+arm64: $(SRCS) $(UI_HDR)
59+ @echo "==> static arm64 build ($(ARM_CC))"
60+ $(ARM_CC) $(ARM_CFLAGS) -o $(BIN).arm64 $(SRCS)
61+
62+# Native Win64 static PE - runs on any Windows 10/11 x64 node
63+win64: $(SRCS) $(UI_HDR)
64+ @echo "==> MinGW-w64 build ($(WIN_CC))"
65+ $(WIN_CC) $(WIN_CFLAGS) -o $(EXE) $(SRCS)
66+
67+# Apple clang build (run this on macOS)
68+macos: $(SRCS) $(UI_HDR)
69+ @echo "==> Apple clang build"
70+ $(CC) $(CFLAGS) -o $(BIN) $(SRCS)
71+
72+# Address/undefined sanitizers plus fortify. This is the build that finds the
73+# overlap, use-after-free and truncation bugs the -O2 suite cannot see, so it
74+# runs in tests/run.sh, not just by hand.
75+asan: $(SRCS) $(UI_HDR)
76+ @echo "==> sanitizer build"
77+ $(CC) -O1 -g -std=c99 -Wall -Wextra -I src -I vendor \
78+ -fsanitize=address,undefined -fno-omit-frame-pointer \
79+ -D_FORTIFY_SOURCE=2 -o $(BIN).asan $(SRCS)
80+
81+test: native
82+ @sh tests/run.sh
83+
84+e2e: native
85+ @python3 tests/e2e.py
86+
87+clean:
88+ rm -f $(BIN) $(EXE) $(BIN).musl $(BIN).arm64 $(BIN).macos-arm64 \
89+ $(BIN).macos-x86_64 $(BIN).asan
90+ rm -rf bin
91+
92+help:
93+ @echo "make | make musl | make arm64 | make win64 | make macos | make ui | make asan | make test | make e2e | make clean"
README.md+239−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..4672168index 0000000..4672168
--- /dev/null--- /dev/null
+++ b/README.md+++ b/README.md
@@ -0,0 +1,239 @@@@ -0,0 +1,239 @@
1+# SCORPIOX BOT — memory
2+
3+A **persistent knowledge graph** your agents can write to and read back, living on
4+your **own node**.
5+
6+This is the standard MCP memory server, rebuilt as one static C99 binary. Entities
7+carry observations, typed relations link them, and the same nine tools an agent
8+sees over stdio back a browser UI for searching, inspecting and editing the graph.
9+The whole graph is a single JSONL file in this connector's own data directory.
10+No account, no database, no CDN, **no network request of any kind** — the binary
11+opens no socket and runs no other program.
12+
13+```
14+make # native build -> ./plugin_memory
15+make musl # static musl x86_64 -> ./plugin_memory.musl
16+make arm64 # static aarch64 -> ./plugin_memory.arm64
17+make win64 # MinGW-w64 static PE -> ./plugin_memory.exe
18+make macos # Apple clang (on macOS) -> ./plugin_memory
19+make ui # regenerate src/ui_html.h from src/ui.html
20+make test # offline suite (180+ assertions)
21+make e2e # Playwright viewport suite (1440 / 1024 / 390, dark + light)
22+```
23+
24+## Install
25+
26+Drop the binary where the node looks for plugins, then open
27+**Settings → Plugins**, or use the market installer:
28+
29+```sh
30+# node plugin directory (created by scorpiox-bot on startup)
31+cp plugin_memory ~/.scorpiox/plugins/plugin_memory
32+chmod +x ~/.scorpiox/plugins/plugin_memory
33+
34+# or from the market
35+curl -s -H "X-Bot-Password: $BOT_PASSWORD" \
36+ "http://127.0.0.1:8150/plugin_manage?action=install&slug=memory&mode=prebuilt"
37+```
38+
39+Windows: `%LOCALAPPDATA%\scorpiox\plugins\plugin_memory.exe`.
40+BotCloud container: `/workspace/.scorpiox/plugins/plugin_memory`.
41+
42+## Five modes, one binary
43+
44+| Mode | Trigger | Response |
45+|---|---|---|
46+| Discovery | `--meta` or `SX_PLUGIN_META=1` | `{"name":"memory","desc":"Knowledge graph","kind":"mcp","mcp":true,"daemon":false,"menus":false,"verified":"live","category":"devtools","version":"1.0.0"}` (unauthenticated) |
47+| **MCP tool provider** | `--mcp` | newline-delimited **JSON-RPC 2.0 over stdio** — `initialize`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `ping` |
48+| API | `?action=...`, `?format=json`, or any `POST` | `application/json; charset=utf-8` |
49+| UI | plain `GET` (`?embed=1` aware) | the graph browser, `text/html` |
50+| Info | `--version`, `--help`, `--schema` | id + version, usage, the nine tool schemas |
51+
52+Modes 3 and 4 sit behind `require_node_auth()`: `X-Bot-Password`,
53+`Authorization: Bearer <pwd>`, or `?pwd=`. With `BOT_PASSWORD` unset the check
54+is a no-op, which is the intended behaviour on a single-user box. `--meta` and
55+`--mcp` stay open — the node spawns the stdio server itself, so a CGI password
56+must not stop it, or the router could never reach an installed connector.
57+
58+### Why `--mcp` and not an MCP server entry
59+
60+`plugin_memory` is a **connector plugin**, not a new MCP server. `scorpiox-bot-api`
61+ships one lightweight stdio router, `sx-connector-mcp`, registered as a *single*
62+MCP server; it reads `mcp_plugins.json` and dispatches into every installed
63+`mcp:true` plugin. That keeps `clang`'s `MAX_SERVERS 16` untouched and adds zero
64+prompt bloat no matter how many connectors are installed:
65+
66+```sh
67+# what the router sees
68+sx-connector-mcp --list # memory kind mcp 9 tools
69+sx-connector-mcp --tools memory
70+sx-connector-mcp --call memory create_entities \
71+ '{"entities":[{"name":"Earl Grey","entityType":"tea","observations":["bergamot"]}]}'
72+sx-connector-mcp --call memory read_graph '{}'
73+```
74+
75+## The nine tools
76+
77+Names, schemas and error texts match the upstream reference server, so a prompt or
78+tool-allowlist written for it works unchanged.
79+
80+| Tool | Arguments | Notes |
81+|---|---|---|
82+| `create_entities` | `{entities:[{name,entityType,observations[]}]}` | a name already present, or repeating earlier in the same call, is **skipped** and listed in `skipped`; its observations are **not** added — use `add_observations` |
83+| `add_observations` | `{observations:[{entityName,contents[]}]}` | one unknown entity fails the whole call; repeats inside the call and against the graph are dropped |
84+| `delete_entities` | `{entityNames[]}` | cascades every relation touching them; reports `Deleted N of M entities. Not found: …` |
85+| `create_relations` | `{relations:[{from,to,relationType}]}` | both ends must exist (`Entity with name X not found`); the exact triple is never stored twice |
86+| `delete_relations` | `{relations:[{from,to,relationType}]}` | exact-triple match; entities are kept |
87+| `delete_observations` | `{deletions:[{entityName,observations[]}]}` | exact-text match |
88+| `read_graph` | `{entityTypes?, observationLimit?}` | `observationLimit: 0` returns counts only (`observationCount`) — *absent* returns full text |
89+| `search_nodes` | `{query, limit?, observationLimit?}` | case-insensitive substring over name, type **and** observations, first-N in stored order |
90+| `open_nodes` | `{names[], observationLimit?}` | exact names; relations kept when **either** endpoint is in the set |
91+
92+A tool failure is a `tools/call` **result** with `isError:true` and the human
93+sentence in `content[0].text` — never a JSON-RPC error — so an agent reading the
94+text can correct itself. Mutations also carry `structuredContent`, and
95+`create_entities` adds a second plain-text block naming what was skipped.
96+
97+## HTTP actions
98+
99+Every action maps onto one of the nine tools, so the page can never drift away
100+from what an agent sees.
101+
102+| Action | Call | Returns |
103+|---|---|---|
104+| `graph` | `GET ?action=graph` | `{"ok":true,"entities":[…],"relations":[…]}` |
105+| `search` | `GET ?action=search&q=<text>&limit=` | same shape, name / type / observation matched |
106+| `entity` | `GET ?action=entity&name=<name>` | `{"ok":true,"entities":[e],"relations":[…]}` — both directions |
107+| `stats` | `GET ?action=stats` | `{"ok":true,"entities":N,"relations":N,"observations":N,"unreadable_lines":N,"types":[…]}` |
108+| `add_entity` | `POST ?action=add_entity` `{"name","entityType","observations?":[]}` | `{"ok":true,…}` |
109+| `add_relation` | `POST ?action=add_relation` `{"from","to","relationType"}` | `{"ok":true,…}` |
110+| `add_obs` | `POST ?action=add_obs` `{"name","contents":[]}` | `{"ok":true,"results":[…]}` |
111+| `delete_entity` | `POST ?action=delete_entity&name=` | `{"ok":true,"message":"…"}` |
112+| `delete_obs` | `POST ?action=delete_obs` `{"name","observations":[]}` | `{"ok":true,"message":"…"}` |
113+| `delete_relation` | `POST ?action=delete_relation` `{"from","to","relationType"}` | `{"ok":true,"message":"…"}` |
114+| `tools` | `GET ?action=tools` | the nine MCP tool schemas + `kind:"mcp"` |
115+| `export` | `GET ?action=export` | the raw JSONL as `text/plain` download |
116+
117+`?action=` and a JSON body are both accepted, so the page can POST an array
118+(`contents`, `observations`) without stuffing it into a query string.
119+
120+```sh
121+P="pwd=$BOT_PASSWORD"
122+curl -s "http://127.0.0.1:8150/plugin_memory?action=stats&$P"
123+
124+curl -s -X POST -H "Content-Type: application/json" \
125+ "http://127.0.0.1:8150/plugin_memory?action=add_entity&$P" \
126+ -d '{"name":"Earl Grey","entityType":"tea","observations":["black tea","bergamot"]}'
127+
128+curl -s -X POST -H "Content-Type: application/json" \
129+ "http://127.0.0.1:8150/plugin_memory?action=add_relation&$P" \
130+ -d '{"from":"Earl Grey","to":"Cup","relationType":"is served in"}'
131+
132+curl -s "http://127.0.0.1:8150/plugin_memory?action=search&q=bergamot&$P"
133+```
134+
135+## Storage
136+
137+| Platform | Location |
138+|---|---|
139+| Linux / macOS | `~/.scorpiox/connectors/plugin_memory/memory.jsonl` |
140+| BotCloud container | `/workspace/.scorpiox/connectors/plugin_memory/memory.jsonl` (preferred when `/workspace` exists — the rootfs does not survive stop → start) |
141+| Windows | `%LOCALAPPDATA%\scorpiox\connectors\plugin_memory\memory.jsonl` |
142+| Override | `$MEMORY_FILE_PATH` (absolute, or relative to the connector directory) |
143+
144+One JSON object per line, exactly the upstream record shape:
145+
146+```
147+{"type":"entity","name":"Earl Grey","entityType":"tea","observations":["black tea","bergamot"]}
148+{"type":"relation","from":"Earl Grey","to":"Cup","relationType":"is served in"}
149+```
150+
151+* Entities are written first, then relations, then anything the loader could not
152+ parse — **verbatim**. A malformed line is never silently deleted by an unrelated
153+ write; it is carried through and written back byte for byte, and counted in
154+ `unreadable_lines`.
155+* Every save goes to `<path>.tmp.<pid>`, `fflush` + `fsync`, `chmod` to the
156+ existing mode, then `rename()`. A process killed mid-write leaves the previous
157+ graph intact rather than a half file, and the temp file is unlinked on failure.
158+* Parent directories are created `0700` — the graph holds the operator's notes
159+ about their own projects, so it is never world-readable.
160+
161+## Security model
162+
163+* **Authentication** — every HTTP action requires the node password (three forms
164+ above); `--meta` alone stays open so discovery works.
165+* **Write scope** — exactly one file, inside the connector directory above.
166+ `MEMORY_FILE_PATH` may not contain `..`.
167+* **No process spawn, no network** — no `popen`, `system`, `exec*`, `socket()` or
168+ `curl` anywhere in `src/`; `tests/run.sh` asserts it against the source.
169+ `plugin.json` declares `capabilities: ["fs_read_connector_dir","fs_write_connector_dir"]`
170+ and nothing else.
171+* **Input limits** — a request body is capped at 8 MiB and a single `--mcp` line
172+ at 8 MiB; entity names and relation ends at 1024 characters, a relation type at
173+ 1024, an observation at 8000. The graph itself is bounded (`MEMORY_MAX_ENTITIES`
174+ 20000, `MEMORY_MAX_RELATIONS` 40000, `MEMORY_MAX_OBS` 2000 per entity,
175+ `MEMORY_MAX_BAD` 5000 preserved lines) and a file over 24 MiB is refused rather
176+ than loaded. Every limit is an error naming the limit, never a crash.
177+* **XSS** — every byte of graph content is HTML-escaped before any tag is emitted,
178+ so a node named `<script>alert(1)</script>` renders as inert text.
179+* **CSP** — `default-src 'none'; script-src 'unsafe-inline'; style-src
180+ 'unsafe-inline'; connect-src 'self'; form-action 'none'; base-uri 'none'`, so a
181+ future regression still cannot fetch a remote script.
182+* **Robustness** — the whole suite also runs under ASan + UBSan +
183+ `_FORTIFY_SOURCE=2`, including a garbage-stdin pass and the CGI path.
184+
185+## UI
186+
187+One page, two panes: the entity list with search and type chips on the left,
188+the inspector on the right. Under 700 px it collapses to a single pane with a
189+back button, so the same page is usable at 390 px and inside the Chat floating
190+window.
191+
192+* live search over name, type and observations; type chips filter in one click
193+* entity inspector: observations with per-row remove, relations in **and** out,
194+ a "new relation from here" picker (both ends must already exist, exact
195+ duplicates are skipped)
196+* add observation, add relation, delete entity / observation / relation, all
197+ round-tripping into the JSONL immediately
198+* `stats` tally in the header, status line for every action, `export` as a file
199+* dark and light from the SCORPIOX BOT theme tokens — `?theme=`,
200+ `localStorage.bot_theme`, `prefers-color-scheme`, and the `sx-theme`
201+ postMessage handoff; the plugin's own toggle hides under `?embed=1`
202+* no `<script src=>`, no CDN, no framework, zero emoji — inline SVG only
203+
204+![1440 dark](docs/ui-1440-dark.png)
205+![390 dark](docs/ui-390-dark.png)
206+
207+## API routes the page uses
208+
209+The single most common plugin bug is calling the wrong route. This page branches
210+exactly once:
211+
212+* served through the hub (`/plugins?plugin=plugin_memory&node=...`) → call the hub
213+ proxy back: `/plugins?plugin=plugin_memory&action=...`
214+* opened directly on the node (`/plugin_memory`) → the plugin **is** the route:
215+ `/plugin_memory?action=...`
216+
217+Calling `/plugins?plugin=` on the node itself returns the discovery list, not the
218+plugin.
219+
220+## Test
221+
222+```sh
223+make test # 180+ offline assertions, 0 fail, no network, no Playwright
224+make e2e # Playwright: 6 viewports × theme, console/overflow/CRUD round trip
225+```
226+
227+The offline suite proves the contract: `--meta` field for field, `--mcp` as a real
228+JSON-RPC session (all nine tools, notifications, bad JSON, unknown method,
229+`ping`, resources), the skip / dedupe / not-found semantics, `observationLimit 0`
230+versus absent, the either-endpoint relation rule, cross-process persistence,
231+verbatim survival of a malformed line, no `.tmp` left behind, every HTTP action's
232+JSON shape, the auth matrix, the source guards, and the ASan/UBSan run. It also
233+cross-builds musl, aarch64 and MinGW where the toolchain is installed, and audits
234+git history for LAN IPs and tokens.
235+
236+## License
237+
238+MIT — see [LICENSE](LICENSE). Vendored: [yyjson](https://github.com/ibireme/yyjson)
239+0.12.0 (MIT, `vendor/`, compiled in — no runtime dependency on any target).
build.ps1+66−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ff6dfc2index 0000000..ff6dfc2
--- /dev/null--- /dev/null
+++ b/build.ps1+++ b/build.ps1
@@ -0,0 +1,66 @@@@ -0,0 +1,66 @@
1+# build.ps1 - Windows static build for plugin_memory
2+#
3+# Usage (from the repo root, PowerShell):
4+# powershell -ExecutionPolicy Bypass -File build.ps1
5+#
6+# Produces .\plugin_memory.exe (static PE, runs on any Windows 10/11 x64 node).
7+# Requires x86_64-w64-mingw32-gcc or a WinLibs/MSYS2 UCRT gcc on PATH
8+# (or C:\gcc16\bin\gcc.exe).
9+#
10+# The binary is four translation units plus the vendored yyjson amalgamation -
11+# no DLLs, no libcurl, no sqlite, nothing to install on the node.
12+
13+$ErrorActionPreference = "Stop"
14+$ScriptDir = $PSScriptRoot
15+Push-Location $ScriptDir
16+try {
17+ $Srcs = @(
18+ "src\plugin_memory.c",
19+ "src\graph.c",
20+ "src\tools.c",
21+ "src\api.c",
22+ "vendor\yyjson.c"
23+ )
24+ $Out = Join-Path $ScriptDir "plugin_memory.exe"
25+ $Cc = "x86_64-w64-mingw32-gcc"
26+
27+ foreach ($s in $Srcs) {
28+ $p = Join-Path $ScriptDir $s
29+ if (-not (Test-Path $p)) { throw "source not found: $p" }
30+ }
31+
32+ # Prefer MinGW-w64, fall back to a plain gcc (WinLibs / MSYS2 UCRT) if present.
33+ if (-not (Get-Command $Cc -ErrorAction SilentlyContinue)) {
34+ if (Test-Path "C:\gcc16\bin\gcc.exe") {
35+ $Cc = "C:\gcc16\bin\gcc.exe"
36+ } elseif (Get-Command gcc -ErrorAction SilentlyContinue) {
37+ $Cc = "gcc"
38+ } else {
39+ throw "no C compiler found (need x86_64-w64-mingw32-gcc or gcc)"
40+ }
41+ }
42+
43+ # Regenerate the page header so the binary always matches src/ui.html.
44+ if (Get-Command python -ErrorAction SilentlyContinue) {
45+ python tools\gen_ui.py
46+ }
47+
48+ Write-Host "==> building plugin_memory.exe with $Cc"
49+ & $Cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor `
50+ -static -o $Out $Srcs
51+ if ($LASTEXITCODE -ne 0) { throw "compile failed (exit $LASTEXITCODE)" }
52+
53+ if (-not (Test-Path $Out)) { throw "build produced no output" }
54+
55+ # Sanity: a real PE starts with 'MZ'. An HTML error page saved as .exe does not.
56+ $bytes = [System.IO.File]::ReadAllBytes($Out)
57+ if ($bytes.Length -lt 2 -or $bytes[0] -ne 0x4D -or $bytes[1] -ne 0x5A) {
58+ throw "output is not a PE executable (missing MZ header)"
59+ }
60+
61+ Write-Host "==> ok: $Out ($($bytes.Length) bytes)"
62+ Write-Host " smoke test: .\plugin_memory.exe --meta"
63+ Write-Host " .\plugin_memory.exe --mcp (then paste a JSON-RPC line)"
64+} finally {
65+ Pop-Location
66+}
docs/ui-1024-dark.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..6ddb6adindex 0000000..6ddb6ad
binary image
Binary image file
docs/ui-1024-light.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..0b624ecindex 0000000..0b624ec
binary image
Binary image file
docs/ui-1440-dark.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..54f9e3bindex 0000000..54f9e3b
binary image
Binary image file
docs/ui-1440-light.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..056f181index 0000000..056f181
binary image
Binary image file
docs/ui-390-dark.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..91fd07cindex 0000000..91fd07c
binary image
Binary image file
docs/ui-390-light.png+0−0■
1new file mode 1006441new file mode 100644
index 0000000..f4b1271index 0000000..f4b1271
binary image
Binary image file
docs/usage.md+123−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..e486137index 0000000..e486137
--- /dev/null--- /dev/null
+++ b/docs/usage.md+++ b/docs/usage.md
@@ -0,0 +1,123 @@@@ -0,0 +1,123 @@
1+# Using the memory connector
2+
3+## Registering it for agents
4+
5+`plugin_memory` is an **MCP connector**, not a standalone MCP server. Installed
6+through `plugin_manage` (or **Settings → Plugins**), it announces
7+`kind:"mcp"`, `mcp:true`, `menus:false`, and `scorpiox-bot-api` records it in
8+`<connectors_dir>/mcp_plugins.json`:
9+
10+```json
11+{
12+ "mcpServers": {
13+ "memory": { "command": "/root/.scorpiox/plugins/plugin_memory", "args": ["--mcp"] }
14+ }
15+}
16+```
17+
18+`clang` never sees that file. `scorpiox-bot-api` ships one stdio router,
19+`sx-connector-mcp`, registered as a **single** MCP server; it reads
20+`mcp_plugins.json` and exposes four compact meta-tools — `connector_list`,
21+`connector_search`, `connector_tools`, `connector_call`. That is why a node can
22+carry hundreds of connectors without touching `MAX_SERVERS 16` or bloating the
23+prompt: only the router's four tools are ever in context, and the nine memory
24+tools are fetched on demand.
25+
26+## Talking to it by hand
27+
28+```sh
29+# discovery (no password)
30+./plugin_memory --meta
31+
32+# the nine tool schemas
33+./plugin_memory --schema | python3 -m json.tool
34+
35+# a real JSON-RPC session: one request per line, one response per line
36+printf '%s\n' \
37+ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \
38+ '{"jsonrpc":"2.0","method":"notifications/initialized"}' \
39+ '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' \
40+ '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"create_entities","arguments":{"entities":[{"name":"Earl Grey","entityType":"tea","observations":["black tea","bergamot"]}]}}}' \
41+ '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"read_graph","arguments":{}}}' \
42+ | ./plugin_memory --mcp
43+```
44+
45+Through the router, which is how an agent reaches it:
46+
47+```sh
48+sx-connector-mcp --list
49+sx-connector-mcp --tools memory
50+sx-connector-mcp --call memory create_entities \
51+ '{"entities":[{"name":"Earl Grey","entityType":"tea","observations":["black tea"]}]}'
52+sx-connector-mcp --call memory read_graph '{}'
53+```
54+
55+## Prompt recipes that work
56+
57+The tool names, schemas and error sentences match the upstream reference memory
58+server, so existing prompts transfer unchanged. Two that earn their keep:
59+
60+**Orient first, read second.** On a graph you did not build, do not open the
61+whole thing. Ask for the cheap overview, then open only what matters:
62+
63+> Read the graph with `observationLimit: 0` to see every entity name, type and
64+> observation **count**. Then `open_nodes` on the two or three names you
65+> actually need, without the limit, to read their full observations.
66+
67+**Facts, not prose.** An observation is one atomic claim an agent can match on
68+exactly (`delete_observations` matches exact text). "deploy runs on .100 via
69+tmux" is a fact; "notes about deploying" is not.
70+
71+## Session memory pattern
72+
73+A common shape for a long-running assistant:
74+
75+1. At the start of a session: `read_graph` with `observationLimit: 0` — one
76+ cheap call that tells the agent what it already knows.
77+2. When the user states something worth keeping: `create_entities` for the
78+ thing, then `create_relations` to hang it on something already in the graph.
79+ The relation is the memory; two unlinked entities are two facts nobody can
80+ find.
81+3. Before correcting: `delete_observations` on the exact stale text, then
82+ `add_observations` with the new one. Never delete and recreate the entity —
83+ that silently drops its relations.
84+
85+## Where the data lives, and how to move it
86+
87+| Situation | Do this |
88+|---|---|
89+| Default | `~/.scorpiox/connectors/plugin_memory/memory.jsonl` |
90+| BotCloud container (rootfs does not survive stop → start) | `/workspace/.scorpiox/connectors/plugin_memory/memory.jsonl` — used automatically when `/workspace` exists |
91+| Windows node | `%LOCALAPPDATA%\scorpiox\connectors\plugin_memory\memory.jsonl` |
92+| Put it somewhere else | `MEMORY_FILE_PATH=/srv/memory/graph.jsonl` (absolute, or relative to the connector dir; `..` is refused) |
93+
94+The file is plain JSONL — one `{"type":"entity",...}` or `{"type":"relation",...}`
95+per line. Back it up by copying it, edit it in any editor, `git` it, or move it
96+between nodes. Lines the loader cannot parse are preserved byte for byte and
97+reported as `unreadable_lines` in `?action=stats`, so a hand-edit that breaks one
98+line cannot lose the graph.
99+
100+`?action=export` downloads the file as-is; `GET /plugin_memory?action=export` with
101+the node password is the whole backup path.
102+
103+## Limits
104+
105+| Knob | Default | Effect |
106+|---|---|---|
107+| `MEMORY_MAX_ENTITIES` | 20000 | creating past this is refused with an instruction to delete |
108+| `MEMORY_MAX_RELATIONS` | 40000 | same |
109+| `MEMORY_MAX_OBS` | 2000 per entity | extra observations in a call are dropped, the call still succeeds |
110+| `MEMORY_MAX_BAD` | 5000 | how many unparseable lines are carried forward verbatim |
111+| `MEMORY_LOCK_STALE_MS` | 10000 | a `.lock` older than this is treated as abandoned and broken |
112+| `MEMORY_LOCK_TIMEOUT_MS` | 2000 | how long a second writer waits for the lock before proceeding best-effort |
113+
114+## Troubleshooting
115+
116+| Symptom | Cause |
117+|---|---|
118+| `--meta` fine, tools missing in the agent | the router has not re-read `mcp_plugins.json` — reinstall through `plugin_manage`, or restart the session so `scorpiox-mcp` respawns |
119+| `{"error":{"code":-32601}}` | method not supported by design (`prompts/*`, `tools/*` typos). Only `initialize`, `ping`, `notifications/*`, `tools/list`, `tools/call`, `resources/list`, `resources/read` answer |
120+| A tool "failed" but there is no JSON-RPC error | intentional: tool failures are results with `isError:true` and the reason in `content[0].text`, so the agent can read and correct |
121+| `create_entities` created nothing | the name already exists (check `skipped`) — use `add_observations`, which is the tool for that |
122+| `Entity with name X not found` on `create_relations` | both ends must exist first; create the entities, then link |
123+| Two processes writing at once | the second takes a `.lock` and waits; if it times out, a stale `.lock` older than `MEMORY_LOCK_STALE_MS` is broken automatically |
plugin.json+20−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..fcd7ab5index 0000000..fcd7ab5
--- /dev/null--- /dev/null
+++ b/plugin.json+++ b/plugin.json
@@ -0,0 +1,20 @@@@ -0,0 +1,20 @@
1+{
2+ "slug": "memory",
3+ "id": "plugin_memory",
4+ "title": "Knowledge Graph Memory",
5+ "summary": "A persistent knowledge graph your agents can write to and read back: entities with observations, typed relations between them, and the nine standard MCP memory tools (create_entities, create_relations, add_observations, delete_entities, delete_observations, delete_relations, read_graph, search_nodes, open_nodes) served over stdio by this one binary. The same nine operations back a browser UI for searching, inspecting and editing the graph. The graph is a single JSONL file in this connector's own data directory, written through a staged temp file and renamed into place, so a crash mid-save cannot truncate it; lines the loader cannot parse are preserved byte for byte rather than dropped. Zero dependencies, zero network requests.",
6+ "category": "devtools",
7+ "license": "MIT",
8+ "kind": "mcp",
9+ "mcp": true,
10+ "daemon": false,
11+ "menus": false,
12+ "verified": "live",
13+ "capabilities": [
14+ "fs_read_connector_dir",
15+ "fs_write_connector_dir"
16+ ],
17+ "trust_notice": "Executes native C code on your node. Reads and writes exactly one file: memory.jsonl inside its own connector directory (~/.scorpiox/connectors/plugin_memory, or /workspace/.scorpiox/connectors/plugin_memory when /workspace exists, or $MEMORY_FILE_PATH when you set it). It opens no network connection, never runs another program, and reads nothing outside that directory.",
18+ "author": "SCORPIOX INC",
19+ "homepage": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-memory"
20+}
release-dist.sh+383−0■■■■■
1new file mode 1007551new file mode 100755
index 0000000..8084327index 0000000..8084327
--- /dev/null--- /dev/null
+++ b/release-dist.sh+++ b/release-dist.sh
@@ -0,0 +1,383 @@@@ -0,0 +1,383 @@
1+#!/usr/bin/env bash
2+# release-dist.sh - build, scan and publish plugin_memory to the plugin registry.
3+#
4+# Two paths:
5+# A. Preferred: if `scorpiox-cli-botplugin` is installed, hand the whole job to it
6+# (`scorpiox-cli-botplugin publish .`), which does the same work with a richer
7+# CLI and is what publishes the connector fields (kind/mcp/daemon/menus/
8+# verified) into all four dist documents.
9+# B. Standalone (this script): secret scan -> multi-target build ->
10+# source.tar.gz -> manifest.json + SHA256SUMS -> upload -> latest.json /
11+# index.json -> plugingit mirror.
12+#
13+# Nothing here contains a host address or a credential. Everything environment-specific
14+# comes from the environment, so this file stays safe to publish:
15+#
16+# DIST_HOST ssh target for the dist server (required for upload)
17+# DIST_PASS ssh password for DIST_HOST (optional, defaults to ssh-agent/key)
18+# DIST_PATH remote web root of the dist server (default /data/dist)
19+# MAC_HOST ssh target for a macOS builder (optional: macos-arm64/x86_64)
20+# MAC_USER / MAC_PASS (optional)
21+# PLUGINGIT_TOKEN_FILE file holding the plugingit write token (default /etc/scorpiox-plugingit.token)
22+# PLUGINGIT_REMOTE public mirror URL to push into
23+#
24+# Usage:
25+# ./release-dist.sh # full release
26+# ./release-dist.sh --dry-run # build + stage in /tmp, no upload
27+# ./release-dist.sh --no-macos # skip the macOS legs
28+# ./release-dist.sh --no-mirror # skip the plugingit mirror
29+# ./release-dist.sh --standalone # use this script even if the CLI is installed
30+
31+set -euo pipefail
32+
33+SLUG="memory"
34+ID="plugin_memory"
35+VERSION="1.0.0"
36+DIST_BASE_URL="https://dist.scorpiox.net/bot-plugins"
37+
38+ROOT="$(cd "$(dirname "$0")" && pwd)"
39+cd "$ROOT"
40+
41+DRY_RUN=0
42+DO_MACOS=1
43+DO_MIRROR=1
44+STANDALONE=0
45+for arg in "$@"; do
46+ case "$arg" in
47+ --standalone) STANDALONE=1 ;;
48+ --dry-run) DRY_RUN=1 ;;
49+ --no-macos) DO_MACOS=0 ;;
50+ --no-mirror) DO_MIRROR=0 ;;
51+ -h|--help) sed -n '2,30p' "$0"; exit 0 ;;
52+ *) echo "unknown argument: $arg" >&2; exit 2 ;;
53+ esac
54+done
55+
56+DIST_HOST="${DIST_HOST:-}"
57+DIST_PASS="${DIST_PASS:-}"
58+DIST_PATH="${DIST_PATH:-/data/dist}"
59+PLUGINGIT_TOKEN_FILE="${PLUGINGIT_TOKEN_FILE:-/etc/scorpiox-plugingit.token}"
60+PLUGINGIT_REMOTE="${PLUGINGIT_REMOTE:-https://plugingit.scorpiox.net/scorpiox-bot-plugin-${SLUG}.git}"
61+
62+STAGE="/tmp/${SLUG}-dist-${VERSION}-$$"
63+mkdir -p "$STAGE"
64+trap 'rm -rf "$STAGE"' EXIT
65+
66+say() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
67+die() { printf '\033[31mERROR:\033[0m %s\n' "$1" >&2; exit 1; }
68+
69+# ---------------------------------------------------------------- 0. preflight
70+say "0/7 preflight"
71+
72+if [ "$STANDALONE" -eq 0 ] && command -v scorpiox-cli-botplugin >/dev/null 2>&1; then
73+ say "using scorpiox-cli-botplugin publish"
74+ exec scorpiox-cli-botplugin publish "$ROOT"
75+fi
76+echo " running the standalone pipeline (dist + plugingit mirror)"
77+
78+if [ -n "$(git status --porcelain 2>/dev/null)" ]; then
79+ echo " note: working tree is dirty; source.tar.gz comes from the last commit"
80+fi
81+COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
82+echo " version $VERSION"
83+echo " commit $COMMIT"
84+
85+# ---------------------------------------------------------------- 1. secret scan
86+say "1/7 secret & LAN scan (full history)"
87+
88+SCAN_TMP="$STAGE/history.txt"
89+# Scan every added/removed line of every commit. Two exclusions, both about the
90+# audit rather than the code: the committer identity line, and any line that is
91+# itself a scan definition - otherwise this file's own detector patterns (and the
92+# identical checks in tests/run.sh) read as findings in every historical revision
93+# of them. A real secret on any other line still hits.
94+git log -p --all 2>/dev/null \
95+ | grep -v '^Author: ' \
96+ | grep -vE 'scan "|HITS=|grep -E|P_ROOT=|P_WT=|\$ALL' \
97+ > "$SCAN_TMP" || : > "$SCAN_TMP"
98+HITS=0
99+scan() { # scan <label> <regex>
100+ local out
101+ out=$(grep -Eo "$2" "$SCAN_TMP" 2>/dev/null | sort -u | head -5 || true)
102+ if [ -n "$out" ]; then
103+ printf ' \033[31mHIT\033[0m %s\n' "$1"
104+ printf '%s\n' "$out" | sed 's/^/ /'
105+ HITS=$((HITS + 1))
106+ else
107+ printf ' ok %s\n' "$1"
108+ fi
109+}
110+scan "LAN IPs 192.168.x.x" '192\.168\.[0-9]+\.[0-9]+'
111+scan "private 10.x.x.x" '\b10\.[0-9]+\.[0-9]+\.[0-9]+'
112+scan "private 172.16-31.x.x" '172\.(1[6-9]|2[0-9]|3[01])\.[0-9]+\.[0-9]+'
113+scan "GitHub PAT" 'ghp_[A-Za-z0-9]{36}'
114+scan "HuggingFace token" 'hf_[A-Za-z0-9]{30,}'
115+scan "embedded git credentials" 'scorpioxinc:[A-Za-z0-9]{20,}'
116+scan "hard-coded ssh password" 'sshpass -p [^"$]'
117+P_ROOT="/codebases"
118+P_PICOBOT="${P_ROOT}/pico""bot"
119+P_WT=".work""trees"
120+scan "internal fleet paths" "/root/tools|${P_PICOBOT}|${P_WT}"
121+scan "run-token env assignment" 'RUNNER_'"PASS="
122+if [ "$HITS" -ne 0 ]; then
123+ die "secret scan found $HITS problem(s) - refusing to publish"
124+fi
125+echo " clean: 0 hits"
126+
127+# ---------------------------------------------------------------- 2. build
128+say "2/7 build targets"
129+
130+# Every target is the Makefile's own command line, so what ships is what the
131+# suite was tested against. yyjson is compiled in; no target needs any library.
132+make native >/dev/null || die "native build failed"
133+cp -f "$ID" "$STAGE/$ID"
134+echo " built linux-x86_64 (glibc) $(wc -c < "$STAGE/$ID" | tr -d ' ') bytes"
135+
136+if command -v musl-gcc >/dev/null 2>&1; then
137+ make musl >/dev/null || die "musl build failed"
138+ cp -f "$ID.musl" "$STAGE/$ID.musl"
139+ echo " built linux-x86_64-musl $(wc -c < "$STAGE/$ID.musl" | tr -d ' ') bytes"
140+else
141+ echo " skip linux-x86_64-musl (no musl-gcc)"
142+fi
143+
144+if command -v aarch64-linux-musl-gcc >/dev/null 2>&1; then
145+ ARM64_CC=aarch64-linux-musl-gcc make arm64 >/dev/null || die "arm64 musl build failed"
146+ cp -f "$ID.arm64" "$STAGE/$ID.arm64"
147+ echo " built linux-arm64-musl $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
148+elif command -v aarch64-linux-gnu-gcc >/dev/null 2>&1; then
149+ ARM_CC=aarch64-linux-gnu-gcc make arm64 >/dev/null || die "arm64 build failed"
150+ cp -f "$ID.arm64" "$STAGE/$ID.arm64"
151+ echo " built linux-arm64-static $(wc -c < "$STAGE/$ID.arm64" | tr -d ' ') bytes"
152+else
153+ echo " skip linux-arm64-musl (no aarch64 cross compiler)"
154+fi
155+
156+if command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then
157+ make win64 >/dev/null || die "MinGW build failed"
158+ cp -f "$ID.exe" "$STAGE/$ID.exe"
159+ [ "$(head -c 2 "$STAGE/$ID.exe")" = "MZ" ] || die "windows artifact is not a PE"
160+ echo " built windows-x86_64 $(wc -c < "$STAGE/$ID.exe" | tr -d ' ') bytes"
161+else
162+ echo " skip windows-x86_64 (no MinGW cross compiler)"
163+fi
164+
165+# macOS legs - Mach-O must be produced by Apple clang on a real Mac. The repo
166+# layout is preserved on the builder because api.c includes "ui_html.h" from
167+# next to the .c and yyjson.h from ../vendor.
168+if [ "$DO_MACOS" -eq 1 ] && [ -n "${MAC_HOST:-}" ]; then
169+ MAC_USER="${MAC_USER:-$(whoami)}"
170+ MAC_DIR="/tmp/${ID}-mac-$$"
171+ echo " building macOS legs on $MAC_HOST"
172+ SSH_MAC=(ssh -o StrictHostKeyChecking=no)
173+ SCP_MAC=(scp -o StrictHostKeyChecking=no)
174+ if [ -n "${MAC_PASS:-}" ]; then
175+ SSH_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SSH_MAC[@]}")
176+ SCP_MAC=(scorpiox-sshpass -p "$MAC_PASS" "${SCP_MAC[@]}")
177+ fi
178+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
179+ "rm -rf '$MAC_DIR' && mkdir -p '$MAC_DIR/src' '$MAC_DIR/vendor' '$MAC_DIR/tools'"; then
180+ if "${SCP_MAC[@]}" -q src/*.c src/*.h "$MAC_USER@$MAC_HOST:$MAC_DIR/src/" &&
181+ "${SCP_MAC[@]}" -q vendor/yyjson.c vendor/yyjson.h "$MAC_USER@$MAC_HOST:$MAC_DIR/vendor/" &&
182+ "${SCP_MAC[@]}" -q tools/gen_ui.py "$MAC_USER@$MAC_HOST:$MAC_DIR/tools/" &&
183+ "${SCP_MAC[@]}" -q src/ui.html Makefile "$MAC_USER@$MAC_HOST:$MAC_DIR/"; then
184+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "cd '$MAC_DIR' && python3 tools/gen_ui.py" 2>/dev/null; then
185+ for slice in arm64 x86_64; do
186+ if "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" \
187+ "cd '$MAC_DIR' && clang -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings -I src -I vendor -arch $slice -o $ID.$slice src/plugin_memory.c src/graph.c src/tools.c src/api.c vendor/yyjson.c" \
188+ 2>/dev/null; then
189+ "${SCP_MAC[@]}" -q "$MAC_USER@$MAC_HOST:$MAC_DIR/$ID.$slice" "$STAGE/$ID.macos-$slice" \
190+ && echo " built macos-$slice ($(wc -c < "$STAGE/$ID.macos-$slice" | tr -d ' ') bytes)"
191+ else
192+ echo " warn: macos-$slice build failed on $MAC_HOST"
193+ fi
194+ done
195+ else
196+ echo " warn: gen_ui.py failed on $MAC_HOST (python3 missing?)"
197+ fi
198+ else
199+ echo " warn: mac scp failed"
200+ fi
201+ "${SSH_MAC[@]}" "$MAC_USER@$MAC_HOST" "rm -rf '$MAC_DIR'" 2>/dev/null || true
202+ else
203+ echo " warn: mac host unreachable"
204+ fi
205+else
206+ echo " skip macOS legs (set MAC_HOST/MAC_USER/MAC_PASS to include them)"
207+fi
208+
209+# ---------------------------------------------------------------- 3. package
210+say "3/7 package"
211+
212+git archive --format=tar.gz --prefix="${ID}-${VERSION}/" \
213+ -o "$STAGE/source.tar.gz" HEAD 2>/dev/null \
214+ || tar -czf "$STAGE/source.tar.gz" --exclude=.git .
215+echo " source.tar.gz $(wc -c < "$STAGE/source.tar.gz" | tr -d ' ') bytes"
216+
217+target_meta() { # target_meta <key> <file> <format> <relpath>
218+ local key="$1" file="$2" fmt="$3" rel="$4"
219+ [ -f "$file" ] || return 0
220+ local sha size
221+ sha=$(sha256sum "$file" | awk '{print $1}')
222+ size=$(wc -c < "$file" | tr -d ' ')
223+ printf ' "%s": {"url": "%s/%s/%s/%s", "sha256": "%s", "size_bytes": %s, "format": "%s"}' \
224+ "$key" "$DIST_BASE_URL" "$SLUG" "$VERSION" "$rel" "$sha" "$size" "$fmt"
225+}
226+
227+# summary / title / trust_notice are taken from plugin.json so there is exactly
228+# one place that says what this plugin does.
229+
230+{
231+ printf '{\n'
232+ printf ' "slug": "%s",\n' "$SLUG"
233+ printf ' "id": "%s",\n' "$ID"
234+ printf ' "name": "%s",\n' "$SLUG"
235+ printf ' "desc": "Knowledge graph",\n'
236+ printf ' "title": %s,\n' "$(python3 -c "import json;print(json.dumps(json.load(open('plugin.json'))['title']))")"
237+ printf ' "summary": %s,\n' "$(python3 -c "import json;print(json.dumps(json.load(open('plugin.json'))['summary']))")"
238+ printf ' "category": "devtools",\n'
239+ printf ' "version": "%s",\n' "$VERSION"
240+ printf ' "license": "MIT",\n'
241+ printf ' "kind": "mcp",\n'
242+ printf ' "mcp": true,\n'
243+ printf ' "daemon": false,\n'
244+ printf ' "menus": false,\n'
245+ printf ' "verified": "live",\n'
246+ printf ' "trust_notice": %s,\n' "$(python3 -c "import json;print(json.dumps(json.load(open('plugin.json'))['trust_notice']))")"
247+ printf ' "capabilities": ["fs_read_connector_dir", "fs_write_connector_dir"],\n'
248+ printf ' "git_repo_url": "https://plugingit.scorpiox.net/scorpiox-bot-plugin-%s.git",\n' "$SLUG"
249+ printf ' "git_web_url": "https://plugingit.scorpiox.net/repo?name=scorpiox-bot-plugin-%s",\n' "$SLUG"
250+ printf ' "git_commit": "%s",\n' "$COMMIT"
251+ printf ' "source_tarball_url": "%s/%s/%s/source.tar.gz",\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
252+ printf ' "source_tarball_sha256": "%s",\n' "$(sha256sum "$STAGE/source.tar.gz" | awk '{print $1}')"
253+ printf ' "build_cmd_posix": "make",\n'
254+ printf ' "build_cmd_win64": "make win64",\n'
255+ printf ' "published_at": "%s",\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
256+ printf ' "targets": {\n'
257+ first=1
258+ emit() { if [ -f "$2" ]; then [ $first -eq 1 ] || printf ',\n'; first=0; target_meta "$@"; fi; }
259+ emit "linux-x86_64" "$STAGE/$ID" "elf-x86_64" "linux-x86_64/$ID"
260+ emit "linux-x86_64-musl" "$STAGE/$ID.musl" "elf-x86_64-static" "linux-x86_64-musl/$ID"
261+ emit "linux-arm64-musl" "$STAGE/$ID.arm64" "elf-arm64-static" "linux-arm64-musl/$ID"
262+ emit "macos-arm64" "$STAGE/$ID.macos-arm64" "macho-arm64" "macos-arm64/$ID"
263+ emit "macos-x86_64" "$STAGE/$ID.macos-x86_64" "macho-x86_64" "macos-x86_64/$ID"
264+ emit "windows-x86_64" "$STAGE/$ID.exe" "pe-x86_64" "windows-x86_64/$ID.exe"
265+ printf '\n }\n}\n'
266+} > "$STAGE/manifest.json"
267+
268+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$STAGE/manifest.json" \
269+ || die "generated manifest.json is not valid JSON"
270+echo " manifest.json ok"
271+
272+# SHA256SUMS - relative paths, exactly as published
273+( cd "$STAGE"
274+ for f in source.tar.gz; do [ -f "$f" ] && sha256sum "$f"; done
275+ [ -f "$ID" ] && sha256sum "$ID" | sed "s| $ID\$| linux-x86_64/$ID|"
276+ [ -f "$ID.musl" ] && sha256sum "$ID.musl" | sed "s| $ID.musl\$| linux-x86_64-musl/$ID|"
277+ [ -f "$ID.arm64" ] && sha256sum "$ID.arm64" | sed "s| $ID.arm64\$| linux-arm64-musl/$ID|"
278+ [ -f "$ID.macos-arm64" ] && sha256sum "$ID.macos-arm64" | sed "s| $ID.macos-arm64\$| macos-arm64/$ID|"
279+ [ -f "$ID.macos-x86_64" ]&& sha256sum "$ID.macos-x86_64" | sed "s| $ID.macos-x86_64\$| macos-x86_64/$ID|"
280+ [ -f "$ID.exe" ] && sha256sum "$ID.exe" | sed "s| $ID.exe\$| windows-x86_64/$ID.exe|"
281+ true ) > "$STAGE/SHA256SUMS"
282+echo " SHA256SUMS $(wc -l < "$STAGE/SHA256SUMS" | tr -d ' ') entries"
283+
284+# ---------------------------------------------------------------- 4. stage
285+say "4/7 stage tree"
286+PKG="$STAGE/pkg"
287+mkdir -p "$PKG/linux-x86_64" "$PKG/linux-x86_64-musl" "$PKG/linux-arm64-musl" \
288+ "$PKG/macos-arm64" "$PKG/macos-x86_64" "$PKG/windows-x86_64"
289+cp -f "$STAGE/$ID" "$PKG/linux-x86_64/$ID"
290+[ -f "$STAGE/$ID.musl" ] && cp -f "$STAGE/$ID.musl" "$PKG/linux-x86_64-musl/$ID"
291+[ -f "$STAGE/$ID.arm64" ] && cp -f "$STAGE/$ID.arm64" "$PKG/linux-arm64-musl/$ID"
292+[ -f "$STAGE/$ID.macos-arm64" ] && cp -f "$STAGE/$ID.macos-arm64" "$PKG/macos-arm64/$ID"
293+[ -f "$STAGE/$ID.macos-x86_64" ]&& cp -f "$STAGE/$ID.macos-x86_64" "$PKG/macos-x86_64/$ID"
294+[ -f "$STAGE/$ID.exe" ] && cp -f "$STAGE/$ID.exe" "$PKG/windows-x86_64/$ID.exe"
295+cp -f "$STAGE/manifest.json" "$STAGE/SHA256SUMS" "$STAGE/source.tar.gz" "$PKG/"
296+chmod +x "$PKG"/*/"$ID" 2>/dev/null || true
297+find "$PKG" -type f | sed 's/^/ /'
298+
299+if [ "$DRY_RUN" -eq 1 ]; then
300+ say "dry run - staged at $STAGE/pkg (kept for inspection)"
301+ trap - EXIT
302+ exit 0
303+fi
304+
305+# ---------------------------------------------------------------- 5. upload
306+say "5/7 upload"
307+
308+[ -n "$DIST_HOST" ] || die "DIST_HOST is not set - cannot upload"
309+SSH=(ssh -o StrictHostKeyChecking=no)
310+SCP=(scp -o StrictHostKeyChecking=no)
311+if [ -n "$DIST_PASS" ]; then
312+ SSH=(scorpiox-sshpass -p "$DIST_PASS" "${SSH[@]}")
313+ SCP=(scorpiox-sshpass -p "$DIST_PASS" "${SCP[@]}")
314+fi
315+REMOTE_DIR="$DIST_PATH/bot-plugins/$SLUG/$VERSION"
316+
317+"${SSH[@]}" "$DIST_HOST" "mkdir -p '$REMOTE_DIR' '$DIST_PATH/bot-plugins/$SLUG'" \
318+ || die "cannot create $REMOTE_DIR on $DIST_HOST"
319+# Stage to one tarball, transfer it, extract remotely. Streaming tar through
320+# ssh corrupts on some OpenSSH builds (remote gzip dies with SIGPIPE), and
321+# OpenSSH 9 refuses to scp a bare "." source.
322+tar -czf "$STAGE/pkg.tar.gz" -C "$PKG" . || die "packaging failed"
323+"${SCP[@]}" -q "$STAGE/pkg.tar.gz" "$DIST_HOST:$REMOTE_DIR/pkg.tar.gz" || die "upload failed"
324+"${SSH[@]}" "$DIST_HOST" "cd '$REMOTE_DIR' && tar -xzf pkg.tar.gz && rm -f pkg.tar.gz" \
325+ || die "remote extract failed"
326+echo " uploaded to $DIST_HOST:$REMOTE_DIR"
327+
328+# latest.json = copy of this version's manifest
329+"${SSH[@]}" "$DIST_HOST" "cp -f '$REMOTE_DIR/manifest.json' '$DIST_PATH/bot-plugins/$SLUG/latest.json'" \
330+ || die "latest.json update failed"
331+echo " updated bot-plugins/$SLUG/latest.json"
332+
333+# index.json - merge, preserving every sibling <slug>/latest.json
334+say "index.json merge"
335+"${SSH[@]}" "$DIST_HOST" "cd '$DIST_PATH/bot-plugins' && python3 - '$SLUG' <<'PY'
336+import json, os, sys, glob
337+slug = sys.argv[1]
338+entries = {}
339+for p in sorted(glob.glob('*/latest.json')):
340+ s = os.path.dirname(p)
341+ try:
342+ entries[s] = json.load(open(p))
343+ except Exception:
344+ pass
345+index = {
346+ 'ok': True,
347+ 'service': 'bot-plugins-dist',
348+ 'dist_base_url': 'https://dist.scorpiox.net/bot-plugins',
349+ 'count': len(entries),
350+ 'slugs': sorted(entries),
351+ 'plugins': [entries[k] for k in sorted(entries)],
352+}
353+open('index.json.tmp', 'w').write(json.dumps(index, indent=2) + chr(10))
354+os.replace('index.json.tmp', 'index.json')
355+print(' index.json now has %d plugin(s): %s' % (len(entries), ', '.join(sorted(entries))))
356+PY" || die "index.json merge failed"
357+
358+# ---------------------------------------------------------------- 6. mirror
359+say "6/7 plugingit mirror"
360+if [ "$DO_MIRROR" -eq 1 ] && [ -f "$PLUGINGIT_TOKEN_FILE" ]; then
361+ TOKEN=$(tr -d ' \r\n' < "$PLUGINGIT_TOKEN_FILE")
362+ AUTH_REMOTE=$(printf '%s' "$PLUGINGIT_REMOTE" | sed "s|https://|https://x-access-token:${TOKEN}@|")
363+ git push --all "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || die "mirror push failed"
364+ git push --tags "$AUTH_REMOTE" 2>&1 | sed 's/^/ /' || true
365+ echo " mirrored to $PLUGINGIT_REMOTE"
366+else
367+ echo " skip (no $PLUGINGIT_TOKEN_FILE or --no-mirror)"
368+fi
369+
370+# ---------------------------------------------------------------- 7. verify
371+say "7/7 verify"
372+CODE=$(curl -fsS -o "$STAGE/latest.check" -w '%{http_code}' \
373+ "$DIST_BASE_URL/$SLUG/latest.json" || echo 000)
374+if [ "$CODE" = "200" ]; then
375+ python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print(" latest.json OK - %s v%s, %d target(s), kind=%s mcp=%s menus=%s verified=%s" % (d["slug"], d["version"], len(d["targets"]), d.get("kind"), d.get("mcp"), d.get("menus"), d.get("verified")))' \
376+ "$STAGE/latest.check" || echo " warn: latest.json is not valid JSON"
377+else
378+ echo " warn: $DIST_BASE_URL/$SLUG/latest.json returned HTTP $CODE"
379+fi
380+
381+printf '\n\033[1mrelease complete\033[0m\n'
382+printf ' registry %s/%s/%s/\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
383+printf ' manifest %s/%s/%s/manifest.json\n' "$DIST_BASE_URL" "$SLUG" "$VERSION"
src/api.c+844−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..d50451cindex 0000000..d50451c
--- /dev/null--- /dev/null
+++ b/src/api.c+++ b/src/api.c
@@ -0,0 +1,844 @@@@ -0,0 +1,844 @@
1+/*
2+ * api.c - the CGI front end for plugin_memory: the browser page and the JSON
3+ * actions it talks to.
4+ *
5+ * There is deliberately no second implementation of the graph operations here.
6+ * Every action maps onto one of the nine tools in tools.c, so the page and an
7+ * agent going through --mcp see exactly the same thing - the same skips, the
8+ * same not-found messages, the same relation rules. When the two are separate
9+ * they drift, and the drift only ever shows up in production.
10+ *
11+ * Parameters are read from the QUERY_STRING *and* from a JSON body, because
12+ * the UI posts JSON (it must: an observation can be any text) while a person
13+ * debugging with curl expects a query string. `action` and `format` are kept
14+ * in separate buffers on purpose - reading one into the other's variable
15+ * silently degrades an action request to the default action.
16+ *
17+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
18+ */
19+
20+#if defined(_WIN32) && !defined(_WIN32_WINNT)
21+# define _WIN32_WINNT 0x0601
22+#endif
23+
24+#if !defined(_WIN32)
25+# define _POSIX_C_SOURCE 200809L
26+# define _DEFAULT_SOURCE 1
27+# if defined(__APPLE__)
28+# define _DARWIN_C_SOURCE 1
29+# endif
30+#endif
31+
32+#include <stdio.h>
33+#include <stdlib.h>
34+#include <string.h>
35+#include <ctype.h>
36+#include <time.h>
37+
38+#if defined(_WIN32)
39+# define WIN32_LEAN_AND_MEAN
40+# include <windows.h>
41+#else
42+# include <unistd.h>
43+#endif
44+
45+#include "memory.h"
46+#include "bot_theme_plugin.h"
47+#include "ui_html.h"
48+
49+/* ------------------------------------------------------------------ */
50+/* Query string */
51+/* ------------------------------------------------------------------ */
52+
53+static void url_decode(char *s)
54+{
55+ char *o = s;
56+ if (!s) return;
57+ while (*s) {
58+ if (*s == '%' && isxdigit((unsigned char)s[1]) &&
59+ isxdigit((unsigned char)s[2])) {
60+ int hi = (s[1] <= '9') ? s[1] - '0'
61+ : (tolower((unsigned char)s[1]) - 'a' + 10);
62+ int lo = (s[2] <= '9') ? s[2] - '0'
63+ : (tolower((unsigned char)s[2]) - 'a' + 10);
64+ *o++ = (char)((hi << 4) | lo);
65+ s += 3;
66+ } else if (*s == '+') {
67+ *o++ = ' ';
68+ s++;
69+ } else {
70+ *o++ = *s++;
71+ }
72+ }
73+ *o = '\0';
74+}
75+
76+static int get_query_val(const char *qs, const char *key, char *out, size_t outsz)
77+{
78+ size_t klen;
79+ const char *p = qs;
80+
81+ if (out && outsz) out[0] = '\0';
82+ if (!qs || !*qs || !key || !out || outsz == 0) return 0;
83+ klen = strlen(key);
84+
85+ while (p && *p) {
86+ const char *eq = strchr(p, '=');
87+ const char *amp = strchr(p, '&');
88+ if (!eq || (amp && eq > amp)) {
89+ p = amp ? amp + 1 : NULL;
90+ continue;
91+ }
92+ if ((size_t)(eq - p) == klen && strncmp(p, key, klen) == 0) {
93+ const char *vs = eq + 1;
94+ size_t n = amp ? (size_t)(amp - vs) : strlen(vs);
95+ if (n >= outsz) n = outsz - 1;
96+ memcpy(out, vs, n);
97+ out[n] = '\0';
98+ url_decode(out);
99+ return 1;
100+ }
101+ p = amp ? amp + 1 : NULL;
102+ }
103+ return 0;
104+}
105+
106+/* ------------------------------------------------------------------ */
107+/* Request body */
108+/* ------------------------------------------------------------------ */
109+
110+static char g_body[REQ_BODY_MAX];
111+
112+/* Read the body only when CONTENT_LENGTH says there is one: a CGI handler
113+ * that reads stdin unconditionally hangs on an inherited empty stdin. */
114+static int read_request_body(void)
115+{
116+ const char *cl = getenv("CONTENT_LENGTH");
117+ long len;
118+ size_t got;
119+
120+ g_body[0] = '\0';
121+ if (!cl || !*cl) return 0;
122+ len = strtol(cl, NULL, 10);
123+ if (len <= 0) return 0;
124+ if ((size_t)len >= sizeof g_body) return -1;
125+ got = fread(g_body, 1, (size_t)len, stdin);
126+ g_body[got] = '\0';
127+ return (int)got;
128+}
129+
130+static yyjson_doc *g_body_doc = NULL;
131+
132+static yyjson_val *body_root(void)
133+{
134+ return g_body_doc ? yyjson_doc_get_root(g_body_doc) : NULL;
135+}
136+
137+/* One parameter: query string first, then the JSON body. Strings are
138+ * returned in `out`; `has` says whether either source had it. */
139+static int param_str(const char *qs, const char *key, char *out, size_t outsz)
140+{
141+ if (out && outsz) out[0] = '\0';
142+ if (qs && get_query_val(qs, key, out, outsz) && out[0]) return 1;
143+ {
144+ yyjson_val *root = body_root();
145+ yyjson_val *v = root ? yyjson_obj_get(root, key) : NULL;
146+ if (v && yyjson_is_str(v)) {
147+ str_copy(out, outsz, yyjson_get_str(v));
148+ return 1;
149+ }
150+ }
151+ return 0;
152+}
153+
154+/* An array parameter (e.g. names[], observations[]) from either source. A
155+ * query string accepts a JSON array value or a |-separated list. */
156+static yyjson_val *body_arr(const char *key)
157+{
158+ yyjson_val *root = body_root();
159+ yyjson_val *v = root ? yyjson_obj_get(root, key) : NULL;
160+ return (v && yyjson_is_arr(v)) ? v : NULL;
161+}
162+
163+/* ------------------------------------------------------------------ */
164+/* Node authentication */
165+/* */
166+/* The node's :8150 is LAN-reachable, and this plugin can read and write the
167+ * operator's knowledge graph, so it must not answer a bare curl. Three
168+ * credential forms are accepted because the three callers differ: bot-web
169+ * proxies with a header, the plugin iframe appends ?pwd=, and a script may
170+ * send a bearer token. --meta stays open so /plugins can still discover us. */
171+/* ------------------------------------------------------------------ */
172+
173+static void require_node_auth(void)
174+{
175+ const char *np = getenv("BOT_PASSWORD");
176+ const char *xp, *auth, *qs;
177+ char qpwd[256];
178+
179+ if (!np || !*np) return; /* node has no password set */
180+
181+ xp = getenv("HTTP_X_BOT_PASSWORD");
182+ if (xp && strcmp(xp, np) == 0) return;
183+
184+ auth = getenv("HTTP_AUTHORIZATION");
185+ if (auth) {
186+ while (*auth == ' ') auth++;
187+ if (strncmp(auth, "Bearer ", 7) == 0) {
188+ auth += 7;
189+ while (*auth == ' ') auth++;
190+ if (strcmp(auth, np) == 0) return;
191+ }
192+ }
193+
194+ qs = getenv("QUERY_STRING");
195+ if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) &&
196+ strcmp(qpwd, np) == 0) return;
197+
198+ fputs("Status: 401 Unauthorized\r\n"
199+ "Content-Type: application/json; charset=utf-8\r\n"
200+ "Cache-Control: no-store\r\n"
201+ "X-Content-Type-Options: nosniff\r\n\r\n"
202+ "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout);
203+ exit(0);
204+}
205+
206+/* ------------------------------------------------------------------ */
207+/* Responses */
208+/* ------------------------------------------------------------------ */
209+
210+static void json_header(void)
211+{
212+ fputs("Content-Type: application/json; charset=utf-8\r\n"
213+ "Cache-Control: no-store\r\n"
214+ "X-Content-Type-Options: nosniff\r\n\r\n", stdout);
215+}
216+
217+static void json_raw(const char *json)
218+{
219+ json_header();
220+ fputs(json ? json : "{\"ok\":true}", stdout);
221+ fputc('\n', stdout);
222+ fflush(stdout);
223+}
224+
225+static void json_err(int code, const char *msg)
226+{
227+ buf_t b;
228+ const char *status = NULL;
229+
230+ if (code == 400) status = "Status: 400 Bad Request\r\n";
231+ else if (code == 404) status = "Status: 404 Not Found\r\n";
232+ else if (code == 413) status = "Status: 413 Payload Too Large\r\n";
233+ else status = "Status: 500 Internal Server Error\r\n";
234+
235+ buf_init(&b);
236+ buf_puts(&b, status);
237+ buf_puts(&b, "Content-Type: application/json; charset=utf-8\r\n"
238+ "Cache-Control: no-store\r\n"
239+ "X-Content-Type-Options: nosniff\r\n\r\n"
240+ "{\"ok\":false,\"status\":");
241+ { char t[8]; snprintf(t, sizeof t, "%d", code); buf_puts(&b, t); }
242+ buf_puts(&b, ",\"error\":");
243+ json_str(&b, msg ? msg : "error");
244+ buf_puts(&b, "}");
245+ fputs(buf_str(&b), stdout);
246+ fputc('\n', stdout);
247+ fflush(stdout);
248+ buf_free(&b);
249+}
250+
251+/* Run a tool and answer with its result, mapping the tool's own error to a
252+ * 200 + ok:false so the UI can show the message the reference server gives
253+ * rather than a bare HTTP status. */
254+/* Run one tool for an HTTP action. The UI's arguments were assembled into a
255+ * mutable document, so serialize it and re-parse: the tools read the
256+ * immutable yyjson_val API, and a cast between the two types would be a
257+ * silent type-lie that only yyjson's internals could expose. At these sizes
258+ * one round trip costs nothing, and both types stay exactly what they are. */
259+static void run_tool(const char *name, yyjson_mut_doc *md,
260+ yyjson_mut_val *root)
261+{
262+ tool_out_t t;
263+ char *s;
264+ char *packed = NULL;
265+ yyjson_doc *parsed = NULL;
266+ yyjson_val *args = NULL;
267+
268+ if (md && root) {
269+ packed = yyjson_mut_write(md, 0, NULL);
270+ if (packed) {
271+ parsed = yyjson_read(packed, strlen(packed), 0);
272+ if (parsed) args = yyjson_doc_get_root(parsed);
273+ }
274+ }
275+
276+ tool_out_init(&t);
277+ if (tool_dispatch(name, args, &t) != 0) {
278+ tool_free(&t);
279+ free(packed);
280+ if (parsed) yyjson_doc_free(parsed);
281+ json_err(400, "unknown action");
282+ return;
283+ }
284+ s = tool_api_result(&t);
285+ json_raw(s);
286+ free(s);
287+ tool_free(&t);
288+ free(packed);
289+ if (parsed) yyjson_doc_free(parsed);
290+}
291+
292+/* ------------------------------------------------------------------ */
293+/* Args assembled from the request */
294+/* ------------------------------------------------------------------ */
295+
296+/* Build a mutable doc so we can graft arrays taken from the body together
297+ * with scalars from the query string, and hand the tools one object either
298+ * way. The doc owns the memory the tools read during dispatch. */
299+typedef struct {
300+ yyjson_mut_doc *md;
301+ yyjson_mut_val *root;
302+} args_t;
303+
304+static void args_init(args_t *a)
305+{
306+ memset(a, 0, sizeof *a);
307+ a->md = yyjson_mut_doc_new(NULL);
308+ if (!a->md) return;
309+ a->root = yyjson_mut_obj(a->md);
310+ if (a->root) yyjson_mut_doc_set_root(a->md, a->root);
311+}
312+
313+static void args_free(args_t *a)
314+{
315+ if (a && a->md) yyjson_mut_doc_free(a->md);
316+ memset(a, 0, sizeof *a);
317+}
318+
319+static void args_add_str(args_t *a, const char *k, const char *v)
320+{
321+ if (a->root) yyjson_mut_obj_add_str(a->md, a->root, k, v ? v : "");
322+}
323+
324+static void args_add_int(args_t *a, const char *k, long v)
325+{
326+ if (a->root) yyjson_mut_obj_add_sint(a->md, a->root, k, (int64_t)v);
327+}
328+
329+/* A string array: from the body when present, else a |-separated query value,
330+ * else a repeated single value. */
331+static void args_add_arr(args_t *a, const char *k, const char *qval)
332+{
333+ yyjson_val *src = body_arr(k);
334+ (void)qval;
335+ yyjson_mut_val *arr = a->root ? yyjson_mut_arr(a->md) : NULL;
336+ if (!arr) return;
337+
338+ if (src) {
339+ size_t i, n = yyjson_arr_size(src);
340+ for (i = 0; i < n; i++) {
341+ yyjson_val *v = yyjson_arr_get(src, i);
342+ if (v && yyjson_is_str(v))
343+ yyjson_mut_arr_add_str(a->md, arr, yyjson_get_str(v));
344+ }
345+ } else if (qval && *qval) {
346+ /* '|' separated, with \%7C available for a literal pipe. */
347+ const char *p = qval;
348+ while (*p) {
349+ const char *s = strchr(p, '|');
350+ size_t len = s ? (size_t)(s - p) : strlen(p);
351+ char tmp[OBS_TEXT_MAX];
352+ if (len >= sizeof tmp) len = sizeof tmp - 1;
353+ memcpy(tmp, p, len);
354+ tmp[len] = '\0';
355+ yyjson_mut_arr_add_str(a->md, arr, tmp);
356+ if (!s) break;
357+ p = s + 1;
358+ }
359+ }
360+ if (a->root) yyjson_mut_obj_add_val(a->md, a->root, k, arr);
361+}
362+
363+/* ------------------------------------------------------------------ */
364+/* Actions */
365+/* ------------------------------------------------------------------ */
366+
367+static void do_stats(const char *qs)
368+{
369+ long long size = 0;
370+ int exists = 0;
371+ size_t i, n_obs = 0, types_seen = 0;
372+ const char **types = NULL;
373+ buf_t b;
374+
375+ (void)qs;
376+ if (graph_load() != 0) { json_err(500, g_data_err); return; }
377+ graph_path_info(&size, &exists);
378+ for (i = 0; i < G.n_ent; i++) n_obs += G.ent[i].n_obs;
379+
380+ /* distinct types, for the filter chips */
381+ types = (const char **)calloc(G.n_ent ? G.n_ent : 1, sizeof *types);
382+ buf_init(&b);
383+ buf_puts(&b, "{\"ok\":true,\"entities\":");
384+ { char t[32]; snprintf(t, sizeof t, "%zu", G.n_ent); buf_puts(&b, t); }
385+ buf_puts(&b, ",\"relations\":");
386+ { char t[32]; snprintf(t, sizeof t, "%zu", G.n_rel); buf_puts(&b, t); }
387+ buf_puts(&b, ",\"observations\":");
388+ { char t[32]; snprintf(t, sizeof t, "%zu", n_obs); buf_puts(&b, t); }
389+ buf_puts(&b, ",\"unreadable_lines\":");
390+ { char t[32]; snprintf(t, sizeof t, "%zu", G.n_bad); buf_puts(&b, t); }
391+ buf_puts(&b, ",\"file_exists\":");
392+ buf_puts(&b, exists ? "true" : "false");
393+ buf_puts(&b, ",\"file_bytes\":");
394+ { char t[32]; snprintf(t, sizeof t, "%lld", size); buf_puts(&b, t); }
395+ buf_puts(&b, ",\"types\":[");
396+ if (types) {
397+ for (i = 0; i < G.n_ent; i++) {
398+ size_t j;
399+ int seen = 0;
400+ for (j = 0; j < types_seen; j++)
401+ if (strcmp(types[j], G.ent[i].etype) == 0) { seen = 1; break; }
402+ if (seen) continue;
403+ if (types_seen >= 200) break;
404+ types[types_seen++] = G.ent[i].etype;
405+ if (types_seen > 1) buf_putc(&b, ',');
406+ json_str(&b, G.ent[i].etype);
407+ }
408+ }
409+ buf_puts(&b, "]}");
410+ json_raw(buf_str(&b));
411+ buf_free(&b);
412+ free((void *)types);
413+}
414+
415+static void do_graph(const char *qs)
416+{
417+ char types[4096], lim[32];
418+ args_t a;
419+
420+ args_init(&a);
421+ if (param_str(qs, "entityTypes", types, sizeof types))
422+ args_add_arr(&a, "entityTypes", types);
423+ if (param_str(qs, "limit", lim, sizeof lim))
424+ args_add_int(&a, "limit", strtol(lim, NULL, 10));
425+ run_tool("read_graph", a.md, a.root);
426+ args_free(&a);
427+}
428+
429+static void do_search(const char *qs)
430+{
431+ char q[512], lim[32], ol[32];
432+ args_t a;
433+
434+ if (!param_str(qs, "q", q, sizeof q) || !q[0]) {
435+ json_err(400, "missing q");
436+ return;
437+ }
438+ args_init(&a);
439+ args_add_str(&a, "query", q);
440+ if (param_str(qs, "limit", lim, sizeof lim))
441+ args_add_int(&a, "limit", strtol(lim, NULL, 10));
442+ if (param_str(qs, "observationLimit", ol, sizeof ol))
443+ args_add_int(&a, "observationLimit", strtol(ol, NULL, 10));
444+ run_tool("search_nodes", a.md, a.root);
445+ args_free(&a);
446+}
447+
448+static void do_entity(const char *qs)
449+{
450+ char name[SX_NAME_MAX * 2];
451+ args_t a;
452+
453+ if (!param_str(qs, "name", name, sizeof name) || !name[0]) {
454+ json_err(400, "missing name");
455+ return;
456+ }
457+ args_init(&a);
458+ {
459+ yyjson_mut_val *arr = yyjson_mut_arr(a.md);
460+ yyjson_mut_arr_add_strcpy(a.md, arr, name);
461+ yyjson_mut_obj_add_val(a.md, a.root, "names", arr);
462+ }
463+ run_tool("open_nodes", a.md, a.root);
464+ args_free(&a);
465+}
466+
467+static void do_add_entity(const char *qs)
468+{
469+ char name[SX_NAME_MAX * 2], type[SX_TYPE_MAX * 2];
470+ args_t a;
471+ yyjson_mut_val *ents, *ent;
472+ yyjson_val *bobs;
473+
474+ if (!param_str(qs, "name", name, sizeof name) || !name[0]) {
475+ json_err(400, "missing name"); return;
476+ }
477+ if (!param_str(qs, "entityType", type, sizeof type) || !type[0]) {
478+ json_err(400, "missing entityType"); return;
479+ }
480+ args_init(&a);
481+ ents = yyjson_mut_arr(a.md);
482+ ent = yyjson_mut_obj(a.md);
483+ yyjson_mut_obj_add_strcpy(a.md, ent, "name", name);
484+ yyjson_mut_obj_add_strcpy(a.md, ent, "entityType", type);
485+ bobs = body_arr("observations");
486+ if (!bobs) {
487+ char obs[OBS_TEXT_MAX * 4];
488+ if (param_str(qs, "observations", obs, sizeof obs)) {
489+ const char *p = obs;
490+ yyjson_mut_val *arr = yyjson_mut_arr(a.md);
491+ while (*p) {
492+ const char *s = strchr(p, '|');
493+ size_t len = s ? (size_t)(s - p) : strlen(p);
494+ char tmp[OBS_TEXT_MAX];
495+ if (len >= sizeof tmp) len = sizeof tmp - 1;
496+ memcpy(tmp, p, len);
497+ tmp[len] = '\0';
498+ if (*tmp) yyjson_mut_arr_add_strcpy(a.md, arr, tmp);
499+ if (!s) break;
500+ p = s + 1;
501+ }
502+ yyjson_mut_obj_add_val(a.md, ent, "observations", arr);
503+ } else {
504+ yyjson_mut_obj_add_val(a.md, ent, "observations",
505+ yyjson_mut_arr(a.md));
506+ }
507+ } else {
508+ yyjson_mut_val *arr = yyjson_mut_arr(a.md);
509+ size_t i, n = yyjson_arr_size(bobs);
510+ for (i = 0; i < n; i++) {
511+ yyjson_val *v = yyjson_arr_get(bobs, i);
512+ if (v && yyjson_is_str(v))
513+ yyjson_mut_arr_add_strcpy(a.md, arr, yyjson_get_str(v));
514+ }
515+ yyjson_mut_obj_add_val(a.md, ent, "observations", arr);
516+ }
517+ yyjson_mut_arr_add_val(ents, ent);
518+ yyjson_mut_obj_add_val(a.md, a.root, "entities", ents);
519+ run_tool("create_entities", a.md, a.root);
520+ args_free(&a);
521+}
522+
523+static void do_add_relation(const char *qs)
524+{
525+ char from[SX_NAME_MAX * 2], to[SX_NAME_MAX * 2], type[SX_TYPE_MAX * 2];
526+ args_t a;
527+ yyjson_mut_val *rels, *rel;
528+
529+ if (!param_str(qs, "from", from, sizeof from) || !from[0]) {
530+ json_err(400, "missing from"); return;
531+ }
532+ if (!param_str(qs, "to", to, sizeof to) || !to[0]) {
533+ json_err(400, "missing to"); return;
534+ }
535+ if (!param_str(qs, "relationType", type, sizeof type) || !type[0]) {
536+ json_err(400, "missing relationType"); return;
537+ }
538+ args_init(&a);
539+ rels = yyjson_mut_arr(a.md);
540+ rel = yyjson_mut_obj(a.md);
541+ yyjson_mut_obj_add_strcpy(a.md, rel, "from", from);
542+ yyjson_mut_obj_add_strcpy(a.md, rel, "to", to);
543+ yyjson_mut_obj_add_strcpy(a.md, rel, "relationType", type);
544+ yyjson_mut_arr_add_val(rels, rel);
545+ yyjson_mut_obj_add_val(a.md, a.root, "relations", rels);
546+ run_tool("create_relations", a.md, a.root);
547+ args_free(&a);
548+}
549+
550+static void do_add_obs(const char *qs)
551+{
552+ char name[SX_NAME_MAX * 2];
553+ args_t a;
554+ yyjson_mut_val *obs, *one, *arr;
555+ yyjson_val *bcontents;
556+
557+ if (!param_str(qs, "name", name, sizeof name) || !name[0]) {
558+ json_err(400, "missing name"); return;
559+ }
560+ args_init(&a);
561+ obs = yyjson_mut_arr(a.md);
562+ one = yyjson_mut_obj(a.md);
563+ arr = yyjson_mut_arr(a.md);
564+ yyjson_mut_obj_add_strcpy(a.md, one, "entityName", name);
565+
566+ bcontents = body_arr("contents");
567+ if (bcontents) {
568+ size_t i, n = yyjson_arr_size(bcontents);
569+ for (i = 0; i < n; i++) {
570+ yyjson_val *v = yyjson_arr_get(bcontents, i);
571+ if (v && yyjson_is_str(v))
572+ yyjson_mut_arr_add_strcpy(a.md, arr, yyjson_get_str(v));
573+ }
574+ } else {
575+ char contents[OBS_TEXT_MAX * 4];
576+ if (param_str(qs, "contents", contents, sizeof contents)) {
577+ const char *p = contents;
578+ while (*p) {
579+ const char *s = strchr(p, '|');
580+ size_t len = s ? (size_t)(s - p) : strlen(p);
581+ char tmp[OBS_TEXT_MAX];
582+ if (len >= sizeof tmp) len = sizeof tmp - 1;
583+ memcpy(tmp, p, len);
584+ tmp[len] = '\0';
585+ if (*tmp) yyjson_mut_arr_add_strcpy(a.md, arr, tmp);
586+ if (!s) break;
587+ p = s + 1;
588+ }
589+ }
590+ }
591+ yyjson_mut_obj_add_val(a.md, one, "contents", arr);
592+ yyjson_mut_arr_add_val(obs, one);
593+ yyjson_mut_obj_add_val(a.md, a.root, "observations", obs);
594+ run_tool("add_observations", a.md, a.root);
595+ args_free(&a);
596+}
597+
598+static void do_delete_entity(const char *qs)
599+{
600+ char name[SX_NAME_MAX * 2];
601+ args_t a;
602+ yyjson_mut_val *arr;
603+
604+ if (!param_str(qs, "name", name, sizeof name) || !name[0]) {
605+ json_err(400, "missing name"); return;
606+ }
607+ args_init(&a);
608+ arr = yyjson_mut_arr(a.md);
609+ yyjson_mut_arr_add_strcpy(a.md, arr, name);
610+ yyjson_mut_obj_add_val(a.md, a.root, "entityNames", arr);
611+ run_tool("delete_entities", a.md, a.root);
612+ args_free(&a);
613+}
614+
615+static void do_delete_relation(const char *qs)
616+{
617+ char from[SX_NAME_MAX * 2], to[SX_NAME_MAX * 2], type[SX_TYPE_MAX * 2];
618+ args_t a;
619+ yyjson_mut_val *rels, *rel;
620+
621+ if (!param_str(qs, "from", from, sizeof from) || !from[0] ||
622+ !param_str(qs, "to", to, sizeof to) || !to[0] ||
623+ !param_str(qs, "relationType", type, sizeof type) || !type[0]) {
624+ json_err(400, "from, to and relationType are all required");
625+ return;
626+ }
627+ args_init(&a);
628+ rels = yyjson_mut_arr(a.md);
629+ rel = yyjson_mut_obj(a.md);
630+ yyjson_mut_obj_add_strcpy(a.md, rel, "from", from);
631+ yyjson_mut_obj_add_strcpy(a.md, rel, "to", to);
632+ yyjson_mut_obj_add_strcpy(a.md, rel, "relationType", type);
633+ yyjson_mut_arr_add_val(rels, rel);
634+ yyjson_mut_obj_add_val(a.md, a.root, "relations", rels);
635+ run_tool("delete_relations", a.md, a.root);
636+ args_free(&a);
637+}
638+
639+static void do_delete_obs(const char *qs)
640+{
641+ char name[SX_NAME_MAX * 2];
642+ args_t a;
643+ yyjson_mut_val *deletions, *one, *arr;
644+ yyjson_val *bobs;
645+
646+ if (!param_str(qs, "name", name, sizeof name) || !name[0]) {
647+ json_err(400, "missing name"); return;
648+ }
649+ args_init(&a);
650+ deletions = yyjson_mut_arr(a.md);
651+ one = yyjson_mut_obj(a.md);
652+ arr = yyjson_mut_arr(a.md);
653+ yyjson_mut_obj_add_strcpy(a.md, one, "entityName", name);
654+
655+ bobs = body_arr("observations");
656+ if (bobs) {
657+ size_t i, n = yyjson_arr_size(bobs);
658+ for (i = 0; i < n; i++) {
659+ yyjson_val *v = yyjson_arr_get(bobs, i);
660+ if (v && yyjson_is_str(v))
661+ yyjson_mut_arr_add_strcpy(a.md, arr, yyjson_get_str(v));
662+ }
663+ } else {
664+ char obs[OBS_TEXT_MAX * 4];
665+ if (param_str(qs, "observations", obs, sizeof obs)) {
666+ const char *p = obs;
667+ while (*p) {
668+ const char *s = strchr(p, '|');
669+ size_t len = s ? (size_t)(s - p) : strlen(p);
670+ char tmp[OBS_TEXT_MAX];
671+ if (len >= sizeof tmp) len = sizeof tmp - 1;
672+ memcpy(tmp, p, len);
673+ tmp[len] = '\0';
674+ if (*tmp) yyjson_mut_arr_add_strcpy(a.md, arr, tmp);
675+ if (!s) break;
676+ p = s + 1;
677+ }
678+ }
679+ }
680+ yyjson_mut_obj_add_val(a.md, one, "observations", arr);
681+ yyjson_mut_arr_add_val(deletions, one);
682+ yyjson_mut_obj_add_val(a.md, a.root, "deletions", deletions);
683+ run_tool("delete_observations", a.md, a.root);
684+ args_free(&a);
685+}
686+
687+/* The raw JSONL, for an operator who wants to diff or back up the graph.
688+ * Served as text/plain with a filename so the browser offers a download. */
689+static void do_export(void)
690+{
691+ char *text;
692+ size_t len = 0;
693+ const char *p = graph_path();
694+
695+ if (graph_load() != 0) { json_err(500, g_data_err); return; }
696+ {
697+ FILE *f = (p && *p) ? fopen(p, "rb") : NULL;
698+ text = NULL;
699+ if (f) {
700+ long sz;
701+ fseek(f, 0, SEEK_END);
702+ sz = ftell(f);
703+ if (sz < 0) sz = 0;
704+ if ((size_t)sz > (size_t)FILE_MAX) sz = (long)FILE_MAX;
705+ if (sz > 0) fseek(f, 0, SEEK_SET);
706+ text = (char *)malloc((size_t)sz + 1);
707+ if (text) len = fread(text, 1, (size_t)sz, f);
708+ text[len] = '\0';
709+ fclose(f);
710+ }
711+ }
712+
713+ fputs("Content-Type: text/plain; charset=utf-8\r\n"
714+ "Cache-Control: no-store\r\n"
715+ "X-Content-Type-Options: nosniff\r\n"
716+ "Content-Disposition: attachment; filename=\"memory.jsonl\"\r\n\r\n",
717+ stdout);
718+ if (text && len) fwrite(text, 1, len, stdout);
719+ free(text);
720+ fflush(stdout);
721+}
722+
723+/* tools/list over HTTP - the same schemas an MCP host gets, so the Setup UI
724+ * and an agent can never disagree about what this connector offers. */
725+static void do_tools(void)
726+{
727+ char *t = tools_list_json();
728+ buf_t b;
729+ buf_init(&b);
730+ buf_puts(&b, "{\"ok\":true,\"connector\":\"" PLUGIN_ID
731+ "\",\"kind\":\"mcp\",\"protocol\":\"" MCP_PROTOCOL
732+ "\",\"tools\":");
733+ buf_puts(&b, t ? t : "[]");
734+ buf_puts(&b, "}");
735+ json_raw(buf_str(&b));
736+ buf_free(&b);
737+ free(t);
738+}
739+
740+/* ------------------------------------------------------------------ */
741+/* The page */
742+/* ------------------------------------------------------------------ */
743+
744+static void emit_ui(void)
745+{
746+ const char *p = UI_HTML;
747+
748+ while (*p) {
749+ if (*p == '\001') {
750+ fputs(SX_BOT_THEME_PREPAINT "<style>" SX_BOT_THEME_TOKENS
751+ "</style>", stdout);
752+ p++;
753+ } else if (*p == '\002') {
754+ fputs(SX_BOT_THEME_HANDOFF, stdout);
755+ p++;
756+ } else {
757+ putchar(*p++);
758+ }
759+ }
760+}
761+
762+static void mode_html(void)
763+{
764+ fputs("Content-Type: text/html; charset=utf-8\r\n"
765+ "Cache-Control: no-store\r\n"
766+ "X-Content-Type-Options: nosniff\r\n"
767+ "X-Frame-Options: SAMEORIGIN\r\n"
768+ "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; "
769+ "style-src 'unsafe-inline'; img-src data:; connect-src 'self'; "
770+ "form-action 'none'; base-uri 'none'\r\n\r\n", stdout);
771+ emit_ui();
772+}
773+
774+/* ------------------------------------------------------------------ */
775+/* Entry */
776+/* ------------------------------------------------------------------ */
777+
778+static const char *method(void)
779+{
780+ const char *m = getenv("REQUEST_METHOD");
781+ return (m && *m) ? m : "GET";
782+}
783+
784+int api_handle(void)
785+{
786+ const char *qs = getenv("QUERY_STRING");
787+ char action[64], act[64], fmt[32];
788+ int got;
789+
790+ if (!qs) qs = "";
791+ action[0] = '\0';
792+ act[0] = '\0';
793+ fmt[0] = '\0';
794+
795+ require_node_auth();
796+
797+ got = read_request_body();
798+ if (got < 0) { json_err(413, "the request body is too large"); return 0; }
799+ if (got > 0) {
800+ g_body_doc = yyjson_read(g_body, strlen(g_body), 0);
801+ if (!g_body_doc) {
802+ json_err(400, "the request body is not valid JSON");
803+ return 0;
804+ }
805+ }
806+
807+ /* Two buffers on purpose: parsing `format` into `action` would clobber the
808+ * action we just parsed and silently answer the default one. */
809+ if (!get_query_val(qs, "action", action, sizeof action)) {
810+ if (param_str(qs, "action", action, sizeof action)) { /* body action */ }
811+ }
812+ if (!action[0]) {
813+ if (get_query_val(qs, "format", fmt, sizeof fmt) &&
814+ strcmp(fmt, "json") == 0)
815+ str_copy(action, sizeof action, "graph");
816+ else if (strcmp(method(), "POST") == 0) {
817+ json_err(400, "missing action");
818+ return 0;
819+ }
820+ }
821+ str_copy(act, sizeof act, action);
822+
823+ if (act[0]) {
824+ if (strcmp(act, "stats") == 0) { do_stats(qs); }
825+ else if (strcmp(act, "graph") == 0) { do_graph(qs); }
826+ else if (strcmp(act, "search") == 0) { do_search(qs); }
827+ else if (strcmp(act, "entity") == 0) { do_entity(qs); }
828+ else if (strcmp(act, "add_entity") == 0) { do_add_entity(qs); }
829+ else if (strcmp(act, "add_relation") == 0){ do_add_relation(qs); }
830+ else if (strcmp(act, "add_obs") == 0) { do_add_obs(qs); }
831+ else if (strcmp(act, "delete_entity") == 0) { do_delete_entity(qs); }
832+ else if (strcmp(act, "delete_relation") == 0) { do_delete_relation(qs); }
833+ else if (strcmp(act, "delete_obs") == 0) { do_delete_obs(qs); }
834+ else if (strcmp(act, "tools") == 0) { do_tools(); }
835+ else if (strcmp(act, "export") == 0) { do_export(); }
836+ else json_err(400, "unknown action");
837+ if (g_body_doc) yyjson_doc_free(g_body_doc);
838+ return 0;
839+ }
840+
841+ mode_html();
842+ if (g_body_doc) yyjson_doc_free(g_body_doc);
843+ return 0;
844+}
src/bot_theme_plugin.h+129−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..0dd243bindex 0000000..0dd243b
--- /dev/null--- /dev/null
+++ b/src/bot_theme_plugin.h+++ b/src/bot_theme_plugin.h
@@ -0,0 +1,129 @@@@ -0,0 +1,129 @@
1+/*
2+ * bot_theme_plugin.h -- SCORPIOX BOT theme tokens for node plugins.
3+ *
4+ * A trimmed copy of scorpiox-bot-web/bot_theme.h (the bot's single source of
5+ * truth for its dual theme). A plugin runs inside the bot (Hub modal, Session
6+ * Card modal, Chat floating window) or in its own tab, and in every case it
7+ * must look like part of the bot: same tokens, same dark/light pair, same
8+ * localStorage key, same prepaint order.
9+ *
10+ * Three rules, and nothing else:
11+ *
12+ * 1. Colours come from these tokens only. No plugin-private palette.
13+ * 2. The theme is decided BEFORE first paint, in this order:
14+ * ?theme=light|dark -> localStorage.bot_theme -> prefers-color-scheme
15+ * so a plugin opened from the bot paints in the bot's theme from frame 0.
16+ * 3. When the bot's theme changes it posts {type:'sx-theme',theme:'...'} into
17+ * this window; the plugin follows without a reload. The plugin asks once
18+ * with {type:'sx-theme-request'} at startup, which covers the case where
19+ * it was already open when the bot changed theme.
20+ *
21+ * The bottom of :root carries aliases for the names older plugin CSS already
22+ * uses (--surface, --surface2, --muted, --accent, --accent2, --danger, --warn,
23+ * --ok), so adopting the bot palette is a swap, not a redesign. Because they
24+ * are var() references, one definition covers both themes.
25+ *
26+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
27+ */
28+#ifndef SX_BOT_THEME_PLUGIN_H
29+#define SX_BOT_THEME_PLUGIN_H
30+
31+/* Dark is the default; light is applied by html[data-theme=light] (chosen by
32+ * ?theme= or the bot) or by prefers-color-scheme when nothing chose. */
33+#define SX_BOT_THEME_TOKENS \
34+":root{color-scheme:dark;" \
35+ "--bg:#000000;--bg-2:#08080a;--bg-card:#1c1c1e;" \
36+ "--surface-2:rgba(255,255,255,.06);--surface-hover:rgba(255,255,255,.05);" \
37+ "--line:rgba(255,255,255,.08);--line-2:rgba(255,255,255,.16);--border:rgba(255,255,255,.08);" \
38+ "--text:#f5f5f7;--text-2:#86868b;--dim:#86868b;" \
39+ "--blue:#0a84ff;--green:#30d158;--orange:#ff9f0a;--red:#ff453a;--gray:#8e8e93;" \
40+ "--indigo:#5e5ce6;--teal:#64d2ff;--purple:#bf5af2;--yellow:#ffd60a;" \
41+ "--input-bg:rgba(255,255,255,.04);--modal-bg:#1c1c1e;--menu-bg:#1c1c1e;--code-bg:rgba(255,255,255,.06);" \
42+ "--mono:'SF Mono',ui-monospace,Menlo,Consolas,'DejaVu Sans Mono',monospace;" \
43+ "--font:-apple-system,BlinkMacSystemFont,'SF Pro Display','SF Pro Text','Inter','Segoe UI',Roboto,Helvetica,Arial,sans-serif;" \
44+ "--shadow:0 1px 2px rgba(0,0,0,.35);" \
45+ "--shadow-lg:0 30px 80px rgba(0,0,0,.65),0 0 0 1px rgba(255,255,255,.04);" \
46+ "--ease:cubic-bezier(.16,1,.3,1);" \
47+ "--surface:var(--bg-card);--surface2:var(--surface-2);--muted:var(--text-2);" \
48+ "--accent:var(--blue);--accent2:var(--green);--accent-dim:#0071e3;" \
49+ "--danger:var(--red);--err:var(--red);--warn:var(--orange);--ok:var(--green);" \
50+"}" \
51+"@media (prefers-color-scheme:light){html:not([data-theme=dark]){" \
52+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
53+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
54+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
55+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
56+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
57+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
58+ "--accent-dim:#0066d6;" \
59+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
60+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
61+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
62+ "color-scheme:light}}" \
63+"html[data-theme=light]{" \
64+ "--bg:#f5f5f7;--bg-2:#ffffff;--bg-card:#ffffff;" \
65+ "--surface-2:rgba(0,0,0,.04);--surface-hover:#ffffff;" \
66+ "--line:rgba(0,0,0,.06);--line-2:rgba(0,0,0,.12);--border:rgba(0,0,0,.06);" \
67+ "--text:#1d1d1f;--text-2:#6e6e73;--dim:#6e6e73;" \
68+ "--blue:#007aff;--green:#34c759;--orange:#ff9500;--red:#ff3b30;--gray:#8e8e93;" \
69+ "--indigo:#5856d6;--teal:#32ade6;--purple:#af52de;--yellow:#b8860b;" \
70+ "--accent-dim:#0066d6;" \
71+ "--input-bg:#f5f5f7;--modal-bg:#ffffff;--menu-bg:#ffffff;--code-bg:rgba(0,0,0,.05);" \
72+ "--shadow:0 2px 10px rgba(0,0,0,.03);" \
73+ "--shadow-lg:0 30px 80px rgba(0,0,0,.18),0 0 0 1px rgba(0,0,0,.04);" \
74+ "color-scheme:light}" \
75+"html{color-scheme:dark}html[data-theme=dark]{color-scheme:dark}" \
76+"*{box-sizing:border-box}" \
77+"body{margin:0;background:var(--bg);color:var(--text);font-family:var(--font);" \
78+ "-webkit-font-smoothing:antialiased}" \
79+"button{font-family:inherit;letter-spacing:inherit}" \
80+"button:active{transform:scale(.98)}" \
81+"select option{background:var(--menu-bg);color:var(--text)}" \
82+"a{color:var(--blue);text-decoration:none;font-weight:600}" \
83+"/* Embed mode (?embed=1): the host owns the title and the theme, so the plugin" \
84+" * hides its own back link and its own toggle. */" \
85+"html.embedded .embed-hide,html.embedded #themeToggle{display:none!important}" \
86+"@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}"
87+
88+/* Pre-paint: decide the theme before the first frame. Must be the first thing
89+ * in <head> so there is no flash of the wrong theme. Also flags embed mode as
90+ * html.embedded so the embed rules apply before first paint. */
91+#define SX_BOT_THEME_PREPAINT \
92+"<script>(function(){var t='';" \
93+"try{var m=/[?&]theme=(light|dark)/.exec(location.search);if(m)t=m[1];}catch(e){}" \
94+"if(!t){try{var s=localStorage.getItem('bot_theme');if(s==='light'||s==='dark')t=s;}catch(e){}}" \
95+"if(!t){try{t=(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches)?'light':'dark';}catch(e){t='dark';}}" \
96+"document.documentElement.setAttribute('data-theme',t);" \
97+"try{if(/[?&]embed=(1|true)(&|$)/.test(location.search))document.documentElement.classList.add('embedded');}catch(e){}" \
98+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
99+"})();</script>\n"
100+
101+/* Handoff: follow the bot. The host posts {type:'sx-theme',theme}; we ask once
102+ * at startup in case it changed while this page was already open. Fires the
103+ * same 'bot-theme' CustomEvent the bot pages use, so canvas surfaces can
104+ * re-skin themselves from one listener. */
105+#define SX_BOT_THEME_HANDOFF \
106+"<script>(function(){" \
107+"function apply(t){if(t!=='light'&&t!=='dark')return;" \
108+"if(document.documentElement.getAttribute('data-theme')===t)return;" \
109+"document.documentElement.setAttribute('data-theme',t);" \
110+"try{localStorage.setItem('bot_theme',t);}catch(e){}" \
111+"try{window.dispatchEvent(new CustomEvent('bot-theme',{detail:t}));}catch(e){}}" \
112+"window.sxApplyTheme=apply;" \
113+"window.sxTheme=function(){var t=document.documentElement.getAttribute('data-theme');return (t==='light'||t==='dark')?t:'dark';};" \
114+"window.addEventListener('message',function(e){var d=e&&e.data;if(d&&d.type==='sx-theme')apply(d.theme);});" \
115+"try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'sx-theme-request'},'*');}catch(e){}" \
116+"})();</script>\n"
117+
118+/* Standalone toggle (hidden in embed mode by the CSS above). Only useful when
119+ * the plugin is opened in its own tab; inside the bot the host owns the theme.
120+ * Give it class 'icon-btn'-free styling from the page, or use the helper JS. */
121+#define SX_BOT_THEME_TOGGLE_BTN \
122+"<button class='embed-hide' id='themeToggle' type='button' title='Toggle appearance'>Theme</button>"
123+
124+#define SX_BOT_THEME_TOGGLE_JS \
125+"<script>(function(){var b=document.getElementById('themeToggle');if(!b)return;" \
126+"b.onclick=function(){window.sxApplyTheme(window.sxTheme()==='dark'?'light':'dark');};" \
127+"})();</script>\n"
128+
129+#endif /* SX_BOT_THEME_PLUGIN_H */
src/graph.c+942−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..3e4e898index 0000000..3e4e898
--- /dev/null--- /dev/null
+++ b/src/graph.c+++ b/src/graph.c
@@ -0,0 +1,942 @@@@ -0,0 +1,942 @@
1+/*
2+ * graph.c - storage engine for plugin_memory.
3+ *
4+ * The graph is one JSONL file: one JSON object per line, tagged
5+ * {"type":"entity",...} or {"type":"relation",...}. This file owns the
6+ * location of that file, the loader, the atomic writer, the in-memory store
7+ * and the little utilities the other units share.
8+ *
9+ * Two properties are load-bearing:
10+ *
11+ * 1. A save stages a temp file in the SAME directory (so the rename stays
12+ * on one filesystem), fsyncs it, restores the target's permission bits
13+ * and renames it over the graph. A kill -9 halfway through leaves the
14+ * previous graph intact and a stray .tmp behind - never a truncated
15+ * graph. The temp file is removed on every failure path.
16+ *
17+ * 2. A line the loader cannot parse is not dropped. It is kept verbatim in
18+ * G.bad and written back unchanged, so a hand-edited or half-imported
19+ * graph survives a round trip. Silently losing someone's data would be
20+ * worse than reporting it, so the count is also reported in stats.
21+ *
22+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
23+ */
24+
25+#if defined(_WIN32) && !defined(_WIN32_WINNT)
26+# define _WIN32_WINNT 0x0601
27+#endif
28+
29+#if !defined(_WIN32)
30+# define _POSIX_C_SOURCE 200809L
31+# define _DEFAULT_SOURCE 1
32+# if defined(__APPLE__)
33+# define _DARWIN_C_SOURCE 1
34+# endif
35+#endif
36+
37+#include <stdio.h>
38+#include <stdlib.h>
39+#include <string.h>
40+#include <ctype.h>
41+#include <errno.h>
42+#include <time.h>
43+#include <stdarg.h>
44+
45+#if defined(_WIN32)
46+# define WIN32_LEAN_AND_MEAN
47+# include <windows.h>
48+# include <direct.h>
49+# include <io.h>
50+# include <sys/stat.h>
51+# include <sys/types.h>
52+#else
53+# include <unistd.h>
54+# include <fcntl.h>
55+# include <sys/stat.h>
56+# include <sys/types.h>
57+#endif
58+
59+#include "memory.h"
60+
61+/* ------------------------------------------------------------------ */
62+/* Growable byte buffer */
63+/* ------------------------------------------------------------------ */
64+
65+void buf_init(buf_t *b)
66+{
67+ b->p = NULL;
68+ b->n = 0;
69+ b->cap = 0;
70+}
71+
72+int buf_need(buf_t *b, size_t extra)
73+{
74+ size_t want = b->n + extra + 1;
75+ char *np;
76+ if (want <= b->cap) return 1;
77+ if (b->cap == 0) b->cap = 1024;
78+ while (b->cap < want) {
79+ if (b->cap > (size_t)128 * 1024 * 1024) return 0; /* hard ceiling */
80+ b->cap *= 2;
81+ }
82+ np = (char *)realloc(b->p, b->cap);
83+ if (!np) return 0;
84+ b->p = np;
85+ return 1;
86+}
87+
88+void buf_add(buf_t *b, const char *s, size_t n)
89+{
90+ if (!s || n == 0) return;
91+ if (!buf_need(b, n)) return;
92+ memcpy(b->p + b->n, s, n);
93+ b->n += n;
94+ b->p[b->n] = '\0';
95+}
96+
97+void buf_puts(buf_t *b, const char *s)
98+{
99+ if (s) buf_add(b, s, strlen(s));
100+}
101+
102+void buf_putc(buf_t *b, int c)
103+{
104+ char ch = (char)c;
105+ buf_add(b, &ch, 1);
106+}
107+
108+const char *buf_str(const buf_t *b)
109+{
110+ return b->p ? b->p : "";
111+}
112+
113+void buf_free(buf_t *b)
114+{
115+ free(b->p);
116+ b->p = NULL;
117+ b->n = b->cap = 0;
118+}
119+
120+/* ------------------------------------------------------------------ */
121+/* Small helpers */
122+/* ------------------------------------------------------------------ */
123+
124+void str_copy(char *dst, size_t dsz, const char *src)
125+{
126+ size_t i;
127+ if (!dst || dsz == 0) return;
128+ dst[0] = '\0';
129+ if (!src) return;
130+ for (i = 0; i + 1 < dsz && src[i]; i++) dst[i] = src[i];
131+ dst[i] = '\0';
132+}
133+
134+/* Case-insensitive substring: the reference search is a plain includes()
135+ * over lower-cased fields, so this is the whole matching rule. */
136+int str_icontains(const char *hay, const char *needle)
137+{
138+ if (!needle || !*needle) return 1;
139+ if (!hay) return 0;
140+ for (; *hay; hay++) {
141+ const char *h = hay, *n = needle;
142+ while (*h && *n &&
143+ tolower((unsigned char)*h) == tolower((unsigned char)*n)) {
144+ h++; n++;
145+ }
146+ if (!*n) return 1;
147+ }
148+ return 0;
149+}
150+
151+void json_str(buf_t *b, const char *s)
152+{
153+ buf_putc(b, '"');
154+ if (s) {
155+ for (; *s; s++) {
156+ unsigned char c = (unsigned char)*s;
157+ if (c == '"') buf_puts(b, "\\\"");
158+ else if (c == '\\') buf_puts(b, "\\\\");
159+ else if (c == '\n') buf_puts(b, "\\n");
160+ else if (c == '\r') buf_puts(b, "\\r");
161+ else if (c == '\t') buf_puts(b, "\\t");
162+ else if (c == '\b') buf_puts(b, "\\b");
163+ else if (c == '\f') buf_puts(b, "\\f");
164+ else if (c < 0x20) {
165+ char tmp[8];
166+ snprintf(tmp, sizeof tmp, "\\u%04x", (unsigned)c);
167+ buf_puts(b, tmp);
168+ } else buf_putc(b, (char)c);
169+ }
170+ }
171+ buf_putc(b, '"');
172+}
173+
174+char *dup_or_null(const char *s)
175+{
176+ char *p;
177+ size_t n;
178+ if (!s) return NULL;
179+ n = strlen(s);
180+ p = (char *)malloc(n + 1);
181+ if (!p) return NULL;
182+ memcpy(p, s, n + 1);
183+ return p;
184+}
185+
186+int env_int(const char *name, int dflt, int lo, int hi)
187+{
188+ const char *v = getenv(name);
189+ long n;
190+ char *end;
191+ if (!v || !*v) return dflt;
192+ errno = 0;
193+ n = strtol(v, &end, 10);
194+ if (end == v || errno != 0) return dflt;
195+ if (n < lo) n = lo;
196+ if (n > hi) n = hi;
197+ return (int)n;
198+}
199+
200+/* ------------------------------------------------------------------ */
201+/* Filesystem helpers */
202+/* ------------------------------------------------------------------ */
203+
204+static int file_exists_p(const char *p)
205+{
206+ struct stat st;
207+ return p && *p && stat(p, &st) == 0;
208+}
209+
210+static int is_dir_p(const char *p)
211+{
212+ struct stat st;
213+ return p && *p && stat(p, &st) == 0 && S_ISDIR(st.st_mode);
214+}
215+
216+static void path_join(char *out, size_t osz, const char *a, const char *b)
217+{
218+ size_t la;
219+ if (!a || !*a) { str_copy(out, osz, b ? b : ""); return; }
220+ la = strlen(a);
221+ if (a[la - 1] == '/' || a[la - 1] == '\\')
222+ snprintf(out, osz, "%s%s", a, b ? b : "");
223+ else
224+ snprintf(out, osz, "%s/%s", a, b ? b : "");
225+}
226+
227+/* mkdir -p with 0700 - the graph holds the operator's notes about their own
228+ * projects, so it is never world-readable. Returns 1 when it exists after. */
229+static int mkdirs(const char *path)
230+{
231+ char tmp[PATH_SZ];
232+ size_t i, n;
233+
234+ if (!path || !*path) return 0;
235+ if (is_dir_p(path)) return 1;
236+ str_copy(tmp, sizeof tmp, path);
237+ n = strlen(tmp);
238+ while (n > 1 && (tmp[n - 1] == '/' || tmp[n - 1] == '\\')) tmp[--n] = '\0';
239+
240+ for (i = 1; i < n; i++) {
241+ if (tmp[i] == '/' || tmp[i] == '\\') {
242+ char save = tmp[i];
243+ tmp[i] = '\0';
244+ if (!is_dir_p(tmp)) {
245+#if defined(_WIN32)
246+ (void)_mkdir(tmp);
247+#else
248+ (void)mkdir(tmp, 0700);
249+#endif
250+ }
251+ tmp[i] = save;
252+ }
253+ }
254+ if (!is_dir_p(tmp)) {
255+#if defined(_WIN32)
256+ (void)_mkdir(tmp);
257+#else
258+ (void)mkdir(tmp, 0700);
259+#endif
260+ }
261+ return is_dir_p(tmp);
262+}
263+
264+static char *read_file_all(const char *path, size_t *len_out)
265+{
266+ FILE *f;
267+ long sz;
268+ char *mem;
269+ size_t got;
270+
271+ if (len_out) *len_out = 0;
272+ if (!path || !*path) return NULL;
273+ f = fopen(path, "rb");
274+ if (!f) return NULL;
275+ if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
276+ sz = ftell(f);
277+ if (sz < 0) { fclose(f); return NULL; }
278+ if ((size_t)sz > (size_t)FILE_MAX) { fclose(f); return NULL; }
279+ if (fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
280+ mem = (char *)malloc((size_t)sz + 1);
281+ if (!mem) { fclose(f); return NULL; }
282+ got = fread(mem, 1, (size_t)sz, f);
283+ fclose(f);
284+ mem[got] = '\0';
285+ if (len_out) *len_out = got;
286+ return mem;
287+}
288+
289+/* ------------------------------------------------------------------ */
290+/* Where the graph lives */
291+/* ------------------------------------------------------------------ */
292+
293+static void connector_dir(char *out, size_t osz)
294+{
295+ const char *env;
296+ struct stat st;
297+
298+ env = getenv("MEMORY_CONNECTOR_DIR");
299+ if (env && *env) { str_copy(out, osz, env); return; }
300+
301+ /* BotCloud containers lose their rootfs on stop -> start, so /workspace
302+ * is the durable place and wins whenever it exists. */
303+ if (stat("/workspace", &st) == 0 && S_ISDIR(st.st_mode)) {
304+ str_copy(out, osz, "/workspace/.scorpiox/connectors/" PLUGIN_ID);
305+ return;
306+ }
307+#if defined(_WIN32)
308+ {
309+ const char *la = getenv("LOCALAPPDATA");
310+ if (la && *la) {
311+ snprintf(out, osz, "%s\\scorpiox\\connectors\\%s", la, PLUGIN_ID);
312+ return;
313+ }
314+ }
315+#endif
316+ env = getenv("HOME");
317+ if (!env || !*env) env = ".";
318+ snprintf(out, osz, "%s/.scorpiox/connectors/%s", env, PLUGIN_ID);
319+}
320+
321+static void expand_home(char *out, size_t osz, const char *in)
322+{
323+ const char *h;
324+ if (!in) { out[0] = '\0'; return; }
325+ h = getenv("HOME");
326+ if (strcmp(in, "~") == 0) { str_copy(out, osz, (h && *h) ? h : "."); return; }
327+ if (in[0] == '~' && (in[1] == '/' || in[1] == '\\')) {
328+ snprintf(out, osz, "%s%s", (h && *h) ? h : ".", in + 1);
329+ return;
330+ }
331+ str_copy(out, osz, in);
332+}
333+
334+static int path_is_abs(const char *p)
335+{
336+ if (!p || !*p) return 0;
337+ if (p[0] == '/') return 1;
338+#if defined(_WIN32)
339+ if (p[0] == '\\' || (isalpha((unsigned char)p[0]) && p[1] == ':')) return 1;
340+#endif
341+ return 0;
342+}
343+
344+static char g_path[PATH_SZ];
345+static int g_path_resolved;
346+
347+/* Resolve the graph path and create its parent. 1 on success. */
348+static int ensure_path(void)
349+{
350+ const char *env;
351+ char dir[PATH_SZ];
352+ char cand[PATH_SZ];
353+
354+ if (g_path_resolved) return 1;
355+
356+ connector_dir(dir, sizeof dir);
357+ env = getenv("MEMORY_FILE_PATH");
358+
359+ if (env && *env) {
360+ const char *slash;
361+ expand_home(cand, sizeof cand, env);
362+ if (path_is_abs(cand)) {
363+ char d[PATH_SZ];
364+ size_t dn;
365+ slash = strrchr(cand, '/');
366+#if defined(_WIN32)
367+ { const char *bs = strrchr(cand, '\\');
368+ if (!slash || (bs && bs > slash)) slash = bs; }
369+#endif
370+ if (!slash) {
371+ str_copy(g_data_err, sizeof g_data_err,
372+ "MEMORY_FILE_PATH must name a file, not a bare name");
373+ return 0;
374+ }
375+ dn = (size_t)(slash - cand);
376+ if (dn == 0) dn = 1; /* keep the root slash */
377+ if (dn >= sizeof d) dn = sizeof d - 1;
378+ memcpy(d, cand, dn);
379+ d[dn] = '\0';
380+ if (!mkdirs(d)) {
381+ str_copy(g_data_err, sizeof g_data_err,
382+ "cannot create the directory for MEMORY_FILE_PATH");
383+ return 0;
384+ }
385+ str_copy(g_path, sizeof g_path, cand);
386+ g_path_resolved = 1;
387+ return 1;
388+ }
389+ /* A relative MEMORY_FILE_PATH lands inside the connector dir, exactly
390+ * like the reference server resolving against its package dir. */
391+ if (strstr(cand, "..")) {
392+ str_copy(g_data_err, sizeof g_data_err,
393+ "MEMORY_FILE_PATH may not contain '..'");
394+ return 0;
395+ }
396+ if (!mkdirs(dir)) {
397+ str_copy(g_data_err, sizeof g_data_err,
398+ "cannot create the connector data directory");
399+ return 0;
400+ }
401+ path_join(g_path, sizeof g_path, dir, cand);
402+ g_path_resolved = 1;
403+ return 1;
404+ }
405+
406+ if (!mkdirs(dir)) {
407+ str_copy(g_data_err, sizeof g_data_err,
408+ "cannot create the connector data directory");
409+ return 0;
410+ }
411+ path_join(g_path, sizeof g_path, dir, "memory.jsonl");
412+ g_path_resolved = 1;
413+ return 1;
414+}
415+
416+const char *graph_path(void)
417+{
418+ if (!g_path_resolved && !ensure_path()) return "";
419+ return g_path;
420+}
421+
422+int graph_path_info(long long *size, int *exists)
423+{
424+ struct stat st;
425+ const char *p = graph_path();
426+ if (size) *size = 0;
427+ if (exists) *exists = 0;
428+ if (!p || !*p) return -1;
429+ if (stat(p, &st) != 0) return 0;
430+ if (exists) *exists = 1;
431+ if (size) *size = (long long)st.st_size;
432+ return 0;
433+}
434+
435+/* ------------------------------------------------------------------ */
436+/* A best-effort cross-process lock */
437+/* */
438+/* Every mutation is a read-modify-write of the whole file, so two */
439+/* concurrent agents could otherwise lose one of their writes. The */
440+/* reference server uses an O_EXCL lock file with a stale-break; this */
441+/* is the same idea in twenty lines. It is deliberately best-effort: */
442+/* if the lock cannot be taken we still serve the request, because */
443+/* losing a node's memory over a stuck lock file is the worse failure. */
444+/* ------------------------------------------------------------------ */
445+
446+static int g_lock_fd = -1;
447+static char g_lock_path[PATH_SZ + SUFFIX_SZ];
448+
449+static void lock_remove(void)
450+{
451+ if (g_lock_path[0]) {
452+#if defined(_WIN32)
453+ _unlink(g_lock_path);
454+#else
455+ unlink(g_lock_path);
456+#endif
457+ g_lock_path[0] = '\0';
458+ }
459+}
460+
461+static int lock_try_once(void)
462+{
463+ int fd;
464+ long stale_ms;
465+ struct stat st;
466+ time_t now;
467+
468+ snprintf(g_lock_path, sizeof g_lock_path, "%s.lock", graph_path());
469+
470+ /* Break a lock left behind by a killed process. */
471+ if (stat(g_lock_path, &st) == 0) {
472+ stale_ms = (long)env_int("MEMORY_LOCK_STALE_MS", 10000, 100, 600000);
473+ time(&now);
474+ if ((long)(now - st.st_mtime) * 1000 > stale_ms) lock_remove();
475+ }
476+
477+#if defined(_WIN32)
478+ fd = _open(g_lock_path, _O_CREAT | _O_EXCL | _O_WRONLY | _O_BINARY, _S_IREAD | _S_IWRITE);
479+#else
480+ fd = open(g_lock_path, O_CREAT | O_EXCL | O_WRONLY, 0600);
481+#endif
482+ if (fd < 0) return -1;
483+ {
484+ char pid[32];
485+ int n = snprintf(pid, sizeof pid, "%ld\n", (long)
486+#if defined(_WIN32)
487+ GetCurrentProcessId()
488+#else
489+ (long)getpid()
490+#endif
491+ );
492+ if (n > 0) {
493+#if defined(_WIN32)
494+ ssize_t w = _write(fd, pid, (unsigned)n);
495+#else
496+ ssize_t w = write(fd, pid, (size_t)n);
497+#endif
498+ (void)w;
499+ }
500+ }
501+#if defined(_WIN32)
502+ _close(fd);
503+#else
504+ close(fd);
505+#endif
506+ g_lock_fd = 0;
507+ return 0;
508+}
509+
510+void graph_lock(void)
511+{
512+ int tries, timeout_ms;
513+ if (!ensure_path()) return;
514+ timeout_ms = env_int("MEMORY_LOCK_TIMEOUT_MS", 2000, 0, 30000);
515+ tries = timeout_ms / 10 + 1;
516+ while (tries-- > 0) {
517+ if (lock_try_once() == 0) return;
518+#if defined(_WIN32)
519+ Sleep(10);
520+#else
521+ { struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 10 * 1000 * 1000L;
522+ nanosleep(&ts, NULL); }
523+#endif
524+ }
525+ /* Best effort: proceed unlocked rather than failing the user's write. */
526+ g_lock_path[0] = '\0';
527+}
528+
529+void graph_unlock(void)
530+{
531+ if (g_lock_fd == 0) lock_remove();
532+ g_lock_fd = -1;
533+}
534+
535+/* ------------------------------------------------------------------ */
536+/* The store */
537+/* ------------------------------------------------------------------ */
538+
539+graph_t G;
540+char g_data_err[256];
541+
542+static char *dup_or_empty(const char *s)
543+{
544+ return dup_or_null(s ? s : "");
545+}
546+
547+void graph_clear(graph_t *g)
548+{
549+ size_t i, j;
550+ for (i = 0; i < g->n_ent; i++) {
551+ free(g->ent[i].name);
552+ free(g->ent[i].etype);
553+ for (j = 0; j < g->ent[i].n_obs; j++) free(g->ent[i].obs[j]);
554+ free(g->ent[i].obs);
555+ }
556+ free(g->ent);
557+ for (i = 0; i < g->n_rel; i++) {
558+ free(g->rel[i].from);
559+ free(g->rel[i].to);
560+ free(g->rel[i].rtype);
561+ }
562+ free(g->rel);
563+ for (i = 0; i < g->n_bad; i++) free(g->bad[i]);
564+ free(g->bad);
565+ memset(g, 0, sizeof *g);
566+}
567+
568+entity_t *ent_find(graph_t *g, const char *name)
569+{
570+ size_t i;
571+ if (!name) return NULL;
572+ for (i = 0; i < g->n_ent; i++)
573+ if (strcmp(g->ent[i].name, name) == 0) return &g->ent[i];
574+ return NULL;
575+}
576+
577+int ent_add(graph_t *g, const char *name, const char *etype,
578+ char **obs, size_t n_obs, char *err, size_t errsz)
579+{
580+ entity_t *e;
581+ size_t i, cap_obs;
582+
583+ if (g->n_ent >= (size_t)env_int("MEMORY_MAX_ENTITIES",
584+ MAX_ENTITIES_DEFAULT, 1, 2000000)) {
585+ if (err) snprintf(err, errsz,
586+ "The graph is at its entity limit; delete entities "
587+ "before adding more.");
588+ return -1;
589+ }
590+ if (!name || !*name || strlen(name) > (size_t)SX_NAME_MAX ||
591+ !etype || !*etype || strlen(etype) > (size_t)SX_TYPE_MAX) {
592+ if (err) snprintf(err, errsz,
593+ "An entity needs a non-empty name and entityType "
594+ "(each at most %d characters).", SX_NAME_MAX);
595+ return -1;
596+ }
597+ if (n_obs > (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT,
598+ 1, 200000))
599+ n_obs = (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT,
600+ 1, 200000);
601+
602+ if (g->n_ent == g->cap_ent) {
603+ size_t nc = g->cap_ent ? g->cap_ent * 2 : 32;
604+ entity_t *nv = (entity_t *)realloc(g->ent, nc * sizeof *nv);
605+ if (!nv) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
606+ g->ent = nv;
607+ g->cap_ent = nc;
608+ }
609+ e = &g->ent[g->n_ent++];
610+ memset(e, 0, sizeof *e);
611+ e->name = dup_or_empty(name);
612+ e->etype = dup_or_empty(etype);
613+ if (!e->name || !e->etype) {
614+ if (err) snprintf(err, errsz, "out of memory");
615+ return -1;
616+ }
617+ cap_obs = n_obs;
618+ if (cap_obs) {
619+ e->obs = (char **)calloc(cap_obs, sizeof *e->obs);
620+ if (!e->obs) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
621+ for (i = 0; i < cap_obs; i++) {
622+ e->obs[i] = dup_or_empty(obs[i] ? obs[i] : "");
623+ if (!e->obs[i]) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
624+ }
625+ e->n_obs = cap_obs;
626+ }
627+ return 0;
628+}
629+
630+int rel_add(graph_t *g, const char *from, const char *to,
631+ const char *rtype, char *err, size_t errsz)
632+{
633+ relation_t *r;
634+
635+ if (g->n_rel >= (size_t)env_int("MEMORY_MAX_RELATIONS",
636+ MAX_RELATIONS_DEFAULT, 1, 4000000)) {
637+ if (err) snprintf(err, errsz,
638+ "The graph is at its relation limit; delete "
639+ "relations before adding more.");
640+ return -1;
641+ }
642+ if (!from || !*from || !to || !*to || !rtype || !*rtype ||
643+ strlen(from) > (size_t)SX_NAME_MAX || strlen(to) > (size_t)SX_NAME_MAX ||
644+ strlen(rtype) > (size_t)SX_TYPE_MAX) {
645+ if (err) snprintf(err, errsz,
646+ "A relation needs non-empty from, to and "
647+ "relationType fields.");
648+ return -1;
649+ }
650+ if (g->n_rel == g->cap_rel) {
651+ size_t nc = g->cap_rel ? g->cap_rel * 2 : 64;
652+ relation_t *nv = (relation_t *)realloc(g->rel, nc * sizeof *nv);
653+ if (!nv) { if (err) snprintf(err, errsz, "out of memory"); return -1; }
654+ g->rel = nv;
655+ g->cap_rel = nc;
656+ }
657+ r = &g->rel[g->n_rel++];
658+ memset(r, 0, sizeof *r);
659+ r->from = dup_or_empty(from);
660+ r->to = dup_or_empty(to);
661+ r->rtype = dup_or_empty(rtype);
662+ if (!r->from || !r->to || !r->rtype) {
663+ if (err) snprintf(err, errsz, "out of memory");
664+ return -1;
665+ }
666+ return 0;
667+}
668+
669+void bad_add(graph_t *g, const char *line)
670+{
671+ size_t cap = (size_t)env_int("MEMORY_MAX_BAD", 5000, 1, 200000);
672+ if (g->n_bad >= cap) { g->truncated = 1; return; }
673+ if (g->n_bad == g->cap_bad) {
674+ size_t nc = g->cap_bad ? g->cap_bad * 2 : 16;
675+ char **nv = (char **)realloc(g->bad, nc * sizeof *nv);
676+ if (!nv) return;
677+ g->bad = nv;
678+ g->cap_bad = nc;
679+ }
680+ g->bad[g->n_bad++] = dup_or_empty(line);
681+}
682+
683+int obs_push(entity_t *e, const char *text)
684+{
685+ char *d;
686+ char **nv;
687+ size_t cap = (size_t)env_int("MEMORY_MAX_OBS", MAX_OBS_PER_ENT_DEFAULT,
688+ 1, 200000);
689+ if (e->n_obs >= cap) return 0;
690+ d = dup_or_empty(text ? text : "");
691+ if (!d) return 0;
692+ nv = (char **)realloc(e->obs, (e->n_obs + 1) * sizeof *e->obs);
693+ if (!nv) { free(d); return 0; }
694+ e->obs = nv;
695+ e->obs[e->n_obs++] = d;
696+ return 1;
697+}
698+
699+int str_arr_from(yyjson_val *arr, char ***out, size_t *n_out, size_t cap)
700+{
701+ char **v = NULL;
702+ size_t n = 0, i, max;
703+
704+ *out = NULL;
705+ *n_out = 0;
706+ if (!arr || !yyjson_is_arr(arr)) return 0;
707+ max = yyjson_arr_size(arr);
708+ if (max > cap) max = cap;
709+ if (max == 0) return 0;
710+ v = (char **)calloc(max, sizeof *v);
711+ if (!v) return -1;
712+ for (i = 0; i < max; i++) {
713+ yyjson_val *it = yyjson_arr_get(arr, i);
714+ const char *s;
715+ if (!it || !yyjson_is_str(it)) continue;
716+ s = yyjson_get_str(it);
717+ if (!s || strlen(s) > (size_t)OBS_TEXT_MAX) continue;
718+ v[n] = dup_or_empty(s);
719+ if (v[n]) n++;
720+ }
721+ *out = v;
722+ *n_out = n;
723+ return 0;
724+}
725+
726+/* ------------------------------------------------------------------ */
727+/* Load */
728+/* ------------------------------------------------------------------ */
729+
730+/* One JSONL line into the graph. 0 = understood, -1 = keep verbatim. */
731+static int load_line(graph_t *g, const char *line)
732+{
733+ yyjson_doc *doc;
734+ yyjson_val *root, *type, *v;
735+ const char *ty;
736+ int rc = -1;
737+
738+ while (*line == ' ' || *line == '\t' || *line == '\r') line++;
739+ if (!*line) return 0; /* blank: not data */
740+
741+ doc = yyjson_read(line, strlen(line), 0);
742+ if (!doc) return -1;
743+ root = yyjson_doc_get_root(doc);
744+ if (!root || !yyjson_is_obj(root)) { yyjson_doc_free(doc); return -1; }
745+
746+ type = yyjson_obj_get(root, "type");
747+ ty = (type && yyjson_is_str(type)) ? yyjson_get_str(type) : NULL;
748+
749+ if (ty && strcmp(ty, "entity") == 0) {
750+ v = yyjson_obj_get(root, "name");
751+ if (yyjson_is_str(v)) {
752+ yyjson_val *nmv = v;
753+ yyjson_val *et = yyjson_obj_get(root, "entityType");
754+ yyjson_val *ob = yyjson_obj_get(root, "observations");
755+ if (yyjson_is_str(et) && yyjson_is_arr(ob)) {
756+ char **obs = NULL;
757+ size_t n_obs = 0, i;
758+ char err[128];
759+ if (str_arr_from(ob, &obs, &n_obs,
760+ (size_t)MAX_OBS_PER_ENT_DEFAULT) == 0) {
761+ if (ent_add(g, yyjson_get_str(nmv), yyjson_get_str(et),
762+ obs, n_obs, err, sizeof err) == 0)
763+ rc = 0;
764+ for (i = 0; i < n_obs; i++) free(obs[i]);
765+ free(obs);
766+ }
767+ }
768+ }
769+ } else if (ty && strcmp(ty, "relation") == 0) {
770+ yyjson_val *f = yyjson_obj_get(root, "from");
771+ yyjson_val *t = yyjson_obj_get(root, "to");
772+ yyjson_val *r = yyjson_obj_get(root, "relationType");
773+ if (yyjson_is_str(f) && yyjson_is_str(t) && yyjson_is_str(r)) {
774+ char err[128];
775+ if (rel_add(g, yyjson_get_str(f), yyjson_get_str(t),
776+ yyjson_get_str(r), err, sizeof err) == 0)
777+ rc = 0;
778+ }
779+ }
780+
781+ yyjson_doc_free(doc);
782+ return rc;
783+}
784+
785+int graph_load(void)
786+{
787+ char *text;
788+ size_t len, i, start;
789+ graph_t ng;
790+
791+ graph_clear(&G);
792+ g_data_err[0] = '\0';
793+ if (!ensure_path()) return -1;
794+
795+ memset(&ng, 0, sizeof ng);
796+ text = read_file_all(g_path, &len);
797+ if (!text) {
798+ if (file_exists_p(g_path)) {
799+ snprintf(g_data_err, sizeof g_data_err,
800+ "cannot read the graph file (permission, or larger "
801+ "than %d MB)", (int)(FILE_MAX / (1024 * 1024)));
802+ return -1;
803+ }
804+ G = ng; /* no file yet: empty */
805+ return 0;
806+ }
807+
808+ i = 0;
809+ while (i <= len) {
810+ start = i;
811+ while (i < len && text[i] != '\n') i++;
812+ text[i] = '\0';
813+ if (load_line(&ng, text + start) != 0) bad_add(&ng, text + start);
814+ i++;
815+ }
816+ free(text);
817+ G = ng;
818+ return 0;
819+}
820+
821+/* ------------------------------------------------------------------ */
822+/* Save */
823+/* ------------------------------------------------------------------ */
824+
825+static int write_over(const char *path, const char *data, size_t len,
826+ char *err, size_t errsz)
827+{
828+ char tmp[PATH_SZ + SUFFIX_SZ];
829+ FILE *f;
830+ int mode = -1;
831+ struct stat st;
832+
833+ if (err && errsz) err[0] = '\0';
834+ if (stat(path, &st) == 0 && S_ISREG(st.st_mode))
835+ mode = (int)(st.st_mode & 0777);
836+
837+ snprintf(tmp, sizeof tmp, "%s.tmp.%ld", path, (long)
838+#if defined(_WIN32)
839+ GetCurrentProcessId()
840+#else
841+ (long)getpid()
842+#endif
843+ );
844+
845+ f = fopen(tmp, "wb");
846+ if (!f) {
847+ if (err) snprintf(err, errsz, "cannot create a temp file beside %s", path);
848+ return -1;
849+ }
850+ if (len && fwrite(data, 1, len, f) != len) {
851+ fclose(f);
852+#if defined(_WIN32)
853+ _unlink(tmp);
854+#else
855+ unlink(tmp);
856+#endif
857+ if (err) snprintf(err, errsz, "the graph is too large to write");
858+ return -1;
859+ }
860+ if (fflush(f) != 0) {
861+ fclose(f);
862+#if defined(_WIN32)
863+ _unlink(tmp);
864+#else
865+ unlink(tmp);
866+#endif
867+ if (err) snprintf(err, errsz, "cannot flush the graph to disk");
868+ return -1;
869+ }
870+#if !defined(_WIN32)
871+ (void)fsync(fileno(f));
872+#endif
873+ fclose(f);
874+
875+ /* rename() gives the new file the process umask; restore the operator's
876+ * own bits so a 0600 graph does not come back world-readable. */
877+ if (mode >= 0) {
878+#if !defined(_WIN32)
879+ (void)chmod(tmp, (mode_t)mode);
880+#else
881+ (void)_chmod(tmp, (mode_t)mode);
882+#endif
883+ }
884+
885+#if defined(_WIN32)
886+ if (!MoveFileExA(tmp, path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
887+ _unlink(tmp);
888+ if (err) snprintf(err, errsz, "cannot replace the graph file");
889+ return -1;
890+ }
891+#else
892+ if (rename(tmp, path) != 0) {
893+ unlink(tmp);
894+ if (err) snprintf(err, errsz, "cannot replace the graph file");
895+ return -1;
896+ }
897+#endif
898+ return 0;
899+}
900+
901+int graph_save(char *err, size_t errsz)
902+{
903+ buf_t b;
904+ size_t i, j;
905+ int rc;
906+
907+ if (!ensure_path()) {
908+ snprintf(err, errsz, "%s", g_data_err[0] ? g_data_err
909+ : "the graph file is not reachable");
910+ return -1;
911+ }
912+ buf_init(&b);
913+ for (i = 0; i < G.n_ent; i++) {
914+ buf_puts(&b, "{\"type\":\"entity\",\"name\":");
915+ json_str(&b, G.ent[i].name);
916+ buf_puts(&b, ",\"entityType\":");
917+ json_str(&b, G.ent[i].etype);
918+ buf_puts(&b, ",\"observations\":[");
919+ for (j = 0; j < G.ent[i].n_obs; j++) {
920+ if (j) buf_putc(&b, ',');
921+ json_str(&b, G.ent[i].obs[j] ? G.ent[i].obs[j] : "");
922+ }
923+ buf_puts(&b, "]}\n");
924+ }
925+ for (i = 0; i < G.n_rel; i++) {
926+ buf_puts(&b, "{\"type\":\"relation\",\"from\":");
927+ json_str(&b, G.rel[i].from);
928+ buf_puts(&b, ",\"to\":");
929+ json_str(&b, G.rel[i].to);
930+ buf_puts(&b, ",\"relationType\":");
931+ json_str(&b, G.rel[i].rtype);
932+ buf_puts(&b, "}\n");
933+ }
934+ /* Unreadable lines last, byte for byte, so a round trip is lossless. */
935+ for (i = 0; i < G.n_bad; i++) {
936+ buf_puts(&b, G.bad[i] ? G.bad[i] : "");
937+ buf_putc(&b, '\n');
938+ }
939+ rc = write_over(g_path, buf_str(&b), b.n, err, errsz);
940+ buf_free(&b);
941+ return rc;
942+}
src/memory.h+185−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..52da038index 0000000..52da038
--- /dev/null--- /dev/null
+++ b/src/memory.h+++ b/src/memory.h
@@ -0,0 +1,185 @@@@ -0,0 +1,185 @@
1+/*
2+ * memory.h - shared declarations for plugin_memory.
3+ *
4+ * plugin_memory is a SCORPIOX BOT connector plugin that reimplements the
5+ * reference MCP "memory" knowledge graph in pure C99: entities with string
6+ * observations, relations between them, persisted as one JSONL file, exposed
7+ * both as nine MCP tools over stdio and as a JSON API behind a browser UI.
8+ *
9+ * The four translation units:
10+ * plugin_memory.c main(), --meta, --mcp loop, CGI dispatch, auth
11+ * graph.c storage: paths, load, atomic save, entity/relation store
12+ * tools.c the nine tools, shared by the MCP and the HTTP front end
13+ * api.c the CGI JSON actions and the HTML page
14+ *
15+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
16+ */
17+#ifndef SX_PLUGIN_MEMORY_H
18+#define SX_PLUGIN_MEMORY_H
19+
20+#include <stddef.h>
21+#include "yyjson.h"
22+
23+#define PLUGIN_SLUG "memory"
24+#define PLUGIN_ID "plugin_memory"
25+#define PLUGIN_VER "1.0.0"
26+#define PLUGIN_NAME "memory"
27+#define PLUGIN_DESC "Knowledge graph"
28+
29+#define MCP_PROTOCOL "2025-06-18"
30+#define RESOURCE_URI "memory://knowledge-graph"
31+#define SERVER_NAME "memory-server"
32+
33+/* ------------------------------------------------------------------ */
34+/* Limits */
35+/* */
36+/* Every cap is a deliberate, documented ceiling: a plugin runs inside */
37+/* the bot on someone's node, so a runaway agent must not be able to */
38+/* grow the graph until the node swaps. Each one has an env override so */
39+/* the tests can prove the truncation path on a tiny fixture. */
40+/* ------------------------------------------------------------------ */
41+
42+#define MAX_ENTITIES_DEFAULT 20000
43+#define MAX_RELATIONS_DEFAULT 40000
44+#define MAX_OBS_PER_ENT_DEFAULT 2000
45+#define SX_NAME_MAX 1024
46+#define SX_TYPE_MAX 1024
47+#define OBS_TEXT_MAX 8000
48+#define PATH_SZ 1024
49+/* Suffix room: "%s.lock" and "%s.tmp.<pid>" append to a full PATH_SZ path. */
50+#define SUFFIX_SZ 32
51+#define REQ_BODY_MAX (8 * 1024 * 1024)
52+#define FILE_MAX (24 * 1024 * 1024)
53+#define STDIN_LINE_MAX (8 * 1024 * 1024)
54+#define UI_LIMIT_DEFAULT 1000
55+
56+/* ------------------------------------------------------------------ */
57+/* Growable byte buffer (graph.c) */
58+/* ------------------------------------------------------------------ */
59+
60+typedef struct {
61+ char *p;
62+ size_t n;
63+ size_t cap;
64+} buf_t;
65+
66+void buf_init(buf_t *b);
67+int buf_need(buf_t *b, size_t extra);
68+void buf_add(buf_t *b, const char *s, size_t n);
69+void buf_puts(buf_t *b, const char *s);
70+void buf_putc(buf_t *b, int c);
71+const char *buf_str(const buf_t *b);
72+void buf_free(buf_t *b);
73+
74+/* ------------------------------------------------------------------ */
75+/* Small helpers (graph.c) */
76+/* ------------------------------------------------------------------ */
77+
78+void str_copy(char *dst, size_t dsz, const char *src);
79+int str_icontains(const char *hay, const char *needle);
80+void json_str(buf_t *b, const char *s);
81+int env_int(const char *name, int dflt, int lo, int hi);
82+char *dup_or_null(const char *s);
83+
84+/* ------------------------------------------------------------------ */
85+/* The graph (graph.c) */
86+/* ------------------------------------------------------------------ */
87+
88+typedef struct {
89+ char *name;
90+ char *etype;
91+ char **obs;
92+ size_t n_obs;
93+ int keep; /* scratch, used by the read tools */
94+} entity_t;
95+
96+typedef struct {
97+ char *from;
98+ char *to;
99+ char *rtype;
100+} relation_t;
101+
102+typedef struct {
103+ entity_t *ent; size_t n_ent, cap_ent;
104+ relation_t *rel; size_t n_rel, cap_rel;
105+ char **bad; size_t n_bad, cap_bad; /* lines kept verbatim */
106+ int truncated;
107+} graph_t;
108+
109+extern graph_t G;
110+extern char g_data_err[256];
111+
112+int graph_load(void); /* 0 ok, -1 + g_data_err */
113+int graph_save(char *err, size_t errsz);
114+void graph_lock(void);
115+void graph_unlock(void);
116+const char *graph_path(void);
117+int graph_path_info(long long *size, int *exists);
118+entity_t *ent_find(graph_t *g, const char *name);
119+int ent_add(graph_t *g, const char *name, const char *etype,
120+ char **obs, size_t n_obs, char *err, size_t errsz);
121+int rel_add(graph_t *g, const char *from, const char *to,
122+ const char *rtype, char *err, size_t errsz);
123+void bad_add(graph_t *g, const char *line);
124+int obs_push(entity_t *e, const char *text);
125+void graph_clear(graph_t *g);
126+int str_arr_from(yyjson_val *arr, char ***out, size_t *n_out, size_t cap);
127+
128+/* ------------------------------------------------------------------ */
129+/* Read options (tools.c) */
130+/* ------------------------------------------------------------------ */
131+
132+typedef struct {
133+ int has_limit; /* observationLimit present (0 is a real value) */
134+ int limit;
135+ int has_types; /* entityTypes present */
136+ char **types;
137+ size_t n_types;
138+ int has_count; /* emit observationCount (set with has_limit) */
139+ int max_entities;/* 0 = unlimited */
140+ int truncated;
141+} read_opt_t;
142+
143+void read_opt_init(read_opt_t *o);
144+
145+/* ------------------------------------------------------------------ */
146+/* Tool results (tools.c) */
147+/* ------------------------------------------------------------------ */
148+
149+typedef struct {
150+ yyjson_mut_doc *md; /* owns root */
151+ yyjson_mut_val *root; /* the result object */
152+ char *notice; /* optional second text block (skipped, etc.) */
153+ char *error; /* error text when is_error */
154+ int is_error;
155+} tool_out_t;
156+
157+void tool_out_init(tool_out_t *t);
158+void tool_err(tool_out_t *t, const char *fmt, ...);
159+void tool_free(tool_out_t *t);
160+
161+/* The nine tools. Each reads `args` (may be NULL) and fills `t`. */
162+void tool_create_entities(yyjson_val *args, tool_out_t *t);
163+void tool_create_relations(yyjson_val *args, tool_out_t *t);
164+void tool_add_observations(yyjson_val *args, tool_out_t *t);
165+void tool_delete_entities(yyjson_val *args, tool_out_t *t);
166+void tool_delete_observations(yyjson_val *args, tool_out_t *t);
167+void tool_delete_relations(yyjson_val *args, tool_out_t *t);
168+void tool_read_graph(yyjson_val *args, tool_out_t *t);
169+void tool_search_nodes(yyjson_val *args, tool_out_t *t);
170+void tool_open_nodes(yyjson_val *args, tool_out_t *t);
171+
172+/* The full tools/list array as JSON text (caller frees). */
173+char *tools_list_json(void);
174+/* Dispatch by name; returns 0 when the name is one of the nine. */
175+int tool_dispatch(const char *name, yyjson_val *args, tool_out_t *out);
176+
177+/* Build the MCP result object for a tool call: content[] + isError
178+ * (+ structuredContent when the reference server emits one). */
179+char *tool_mcp_result(tool_out_t *t);
180+
181+/* Serialize the tool result for the HTTP API: {"ok":true,...} or
182+ * {"ok":false,"error":"..."}. Caller frees. */
183+char *tool_api_result(tool_out_t *t);
184+
185+#endif /* SX_PLUGIN_MEMORY_H */
src/plugin_memory.c+402−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..f7235b6index 0000000..f7235b6
--- /dev/null--- /dev/null
+++ b/src/plugin_memory.c+++ b/src/plugin_memory.c
@@ -0,0 +1,402 @@@@ -0,0 +1,402 @@
1+/*
2+ * plugin_memory.c - entry point for the SCORPIOX BOT knowledge-graph memory
3+ * connector.
4+ *
5+ * One binary, five modes, exactly as the plugin_<name> spec requires:
6+ *
7+ * 1. --meta / SX_PLUGIN_META=1 -> one line of discovery JSON, exit 0.
8+ * Unauthenticated on purpose: /plugins on the node probes it, and the
9+ * sx-connector-mcp router probes it before it will run anything else.
10+ * 2. --mcp -> MCP JSON-RPC 2.0 over stdio, one request
11+ * per line on stdin, one response per line on stdout. This is what makes
12+ * the plugin a tool provider for SCORPIOX CODE through the single
13+ * sx-connector-mcp router, with no clang change and no extra MCP server
14+ * slot.
15+ * 3. ?action=... | ?format=json | POST -> the JSON node API the browser UI
16+ * talks to. Same nine operations as --mcp, so the UI can never drift
17+ * away from what an agent sees.
18+ * 4. GET (default) -> the knowledge-graph browser page.
19+ * 5. --version -> id + version.
20+ *
21+ * Modes 3 and 4 sit behind require_node_auth(): the node's :8150 is reachable
22+ * from the LAN, so a plugin that reads and writes the operator's knowledge
23+ * graph must not answer a bare curl. --meta stays open so discovery works.
24+ *
25+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
26+ */
27+
28+#if defined(_WIN32) && !defined(_WIN32_WINNT)
29+# define _WIN32_WINNT 0x0601
30+#endif
31+
32+#if !defined(_WIN32)
33+# define _POSIX_C_SOURCE 200809L
34+# define _DEFAULT_SOURCE 1
35+# if defined(__APPLE__)
36+# define _DARWIN_C_SOURCE 1
37+# endif
38+#endif
39+
40+#include <stdio.h>
41+#include <stdlib.h>
42+#include <string.h>
43+#include <ctype.h>
44+
45+#if defined(_WIN32)
46+# define WIN32_LEAN_AND_MEAN
47+# include <windows.h>
48+# include <io.h>
49+# include <fcntl.h>
50+/* MinGW's CRT starts stdout in TEXT mode and rewrites every \n we emit into
51+ * \r\n. A CGI header block must end with exactly CRLF CRLF; text mode turns
52+ * that into \r\r\n\r\r\n, scorpiox-server cannot find the header/body
53+ * separator, and the whole reply (headers included) is served as a body. Same
54+ * for the MCP loop: a JSON-RPC line with a stray \r confuses line readers.
55+ * Force binary stdio before main() runs. */
56+__attribute__((constructor))
57+static void sx_plugin_binary_stdio(void)
58+{
59+ _setmode(_fileno(stdout), _O_BINARY);
60+ _setmode(_fileno(stdin), _O_BINARY);
61+}
62+#else
63+# include <unistd.h>
64+#endif
65+
66+#include "memory.h"
67+
68+/* In api.c */
69+int api_handle(void); /* returns process exit code */
70+
71+/* ------------------------------------------------------------------ */
72+/* --meta */
73+/* ------------------------------------------------------------------ */
74+
75+static int mode_meta(void)
76+{
77+ printf("{\"name\":\"%s\",\"desc\":\"%s\",\"kind\":\"mcp\",\"mcp\":true,"
78+ "\"daemon\":false,\"menus\":false,\"verified\":\"live\","
79+ "\"category\":\"devtools\",\"version\":\"%s\"}\n",
80+ PLUGIN_NAME, PLUGIN_DESC, PLUGIN_VER);
81+ fflush(stdout);
82+ return 0;
83+}
84+
85+/* ------------------------------------------------------------------ */
86+/* --mcp : MCP JSON-RPC 2.0 over stdio */
87+/* */
88+/* The contract sx-connector-mcp (and any other MCP host) exercises: */
89+/* */
90+/* initialize -> notifications/initialized -> tools/list -> */
91+/* tools/call */
92+/* */
93+/* Rules that matter: */
94+/* */
95+/* - one request per line, one response per line, flushed every time. */
96+/* A host reads stdout blocking, so an unflushed reply is a hang. */
97+/* - a notification (no "id" member) gets NO response, not an empty */
98+/* one. Answering a notification is how a router deadlocks. */
99+/* - the id is echoed back exactly as it arrived (number in, number */
100+/* out; string in, string out). */
101+/* - a tool that fails returns a RESULT with isError:true, because */
102+/* the JSON-RPC call itself succeeded and this is what hosts render */
103+/* for the user. Only protocol problems are JSON-RPC errors. */
104+/* ------------------------------------------------------------------ */
105+
106+static void put_id(buf_t *b, yyjson_val *id)
107+{
108+ if (!id) { buf_puts(b, "null"); return; }
109+ switch (yyjson_get_type(id)) {
110+ case YYJSON_TYPE_STR:
111+ json_str(b, yyjson_get_str(id));
112+ break;
113+ case YYJSON_TYPE_NUM:
114+ if (yyjson_get_subtype(id) == YYJSON_SUBTYPE_UINT) {
115+ char t[32];
116+ snprintf(t, sizeof t, "%llu",
117+ (unsigned long long)yyjson_get_uint(id));
118+ buf_puts(b, t);
119+ } else if (yyjson_get_subtype(id) == YYJSON_SUBTYPE_SINT) {
120+ char t[32];
121+ snprintf(t, sizeof t, "%lld", (long long)yyjson_get_sint(id));
122+ buf_puts(b, t);
123+ } else {
124+ char t[64];
125+ snprintf(t, sizeof t, "%g", yyjson_get_num(id));
126+ buf_puts(b, t);
127+ }
128+ break;
129+ case YYJSON_TYPE_BOOL:
130+ buf_puts(b, yyjson_get_bool(id) ? "true" : "false");
131+ break;
132+ default:
133+ buf_puts(b, "null");
134+ break;
135+ }
136+}
137+
138+static void send_result(yyjson_val *id, const char *result_json)
139+{
140+ buf_t b;
141+ buf_init(&b);
142+ buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");
143+ put_id(&b, id);
144+ buf_puts(&b, ",\"result\":");
145+ buf_puts(&b, result_json ? result_json : "{}");
146+ buf_puts(&b, "}");
147+ fputs(buf_str(&b), stdout);
148+ fputc('\n', stdout);
149+ fflush(stdout);
150+ buf_free(&b);
151+}
152+
153+static void send_error(yyjson_val *id, int code, const char *message)
154+{
155+ buf_t b;
156+ buf_init(&b);
157+ buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");
158+ put_id(&b, id);
159+ buf_puts(&b, ",\"error\":{\"code\":");
160+ { char t[16]; snprintf(t, sizeof t, "%d", code); buf_puts(&b, t); }
161+ buf_puts(&b, ",\"message\":");
162+ json_str(&b, message ? message : "error");
163+ buf_puts(&b, "}}");
164+ fputs(buf_str(&b), stdout);
165+ fputc('\n', stdout);
166+ fflush(stdout);
167+ buf_free(&b);
168+}
169+
170+/* resources/read serves the same graph the tools read, as one JSON text
171+ * under the well-known URI. A subscription notification is not emitted: the
172+ * reference server sends resources/updated to subscribers, and this connector
173+ * is a single request/response process with no channel to notify on. */
174+static char *resource_text(void)
175+{
176+ tool_out_t t;
177+ char *s = NULL;
178+
179+ tool_out_init(&t);
180+ tool_read_graph(NULL, &t);
181+ if (!t.is_error && t.md && t.root)
182+ s = yyjson_mut_write(t.md, 0, NULL);
183+ tool_free(&t);
184+ return s;
185+}
186+
187+static void handle_request(yyjson_val *root, yyjson_val *id, const char *method)
188+{
189+ if (strcmp(method, "initialize") == 0) {
190+ buf_t b;
191+ buf_init(&b);
192+ buf_puts(&b, "{\"protocolVersion\":\"" MCP_PROTOCOL
193+ "\",\"capabilities\":{\"tools\":{\"listChanged\":false},"
194+ "\"resources\":{\"subscribe\":false,"
195+ "\"listChanged\":false}},\"serverInfo\":{\"name\":\""
196+ SERVER_NAME "\",\"title\":\"Knowledge Graph Memory\","
197+ "\"version\":\"" PLUGIN_VER "\"}}");
198+ send_result(id, buf_str(&b));
199+ buf_free(&b);
200+ return;
201+ }
202+ if (strcmp(method, "ping") == 0) {
203+ send_result(id, "{}");
204+ return;
205+ }
206+ if (strcmp(method, "tools/list") == 0) {
207+ char *tools = tools_list_json();
208+ buf_t b;
209+ buf_init(&b);
210+ buf_puts(&b, "{\"tools\":");
211+ buf_puts(&b, tools ? tools : "[]");
212+ buf_puts(&b, "}");
213+ send_result(id, buf_str(&b));
214+ buf_free(&b);
215+ free(tools);
216+ return;
217+ }
218+ if (strcmp(method, "tools/call") == 0) {
219+ yyjson_val *params = yyjson_obj_get(root, "params");
220+ const char *name = NULL;
221+ yyjson_val *args = NULL;
222+ tool_out_t t;
223+ char *res;
224+
225+ if (params && yyjson_is_obj(params)) {
226+ yyjson_val *nv = yyjson_obj_get(params, "name");
227+ if (nv && yyjson_is_str(nv)) name = yyjson_get_str(nv);
228+ args = yyjson_obj_get(params, "arguments");
229+ if (args && !yyjson_is_obj(args)) args = NULL;
230+ }
231+ if (!name) {
232+ send_error(id, -32602, "tools/call needs params.name");
233+ return;
234+ }
235+ if (tool_dispatch(name, args, &t) != 0) {
236+ buf_t b;
237+ buf_init(&b);
238+ buf_puts(&b, "Unknown tool: ");
239+ buf_puts(&b, name);
240+ send_error(id, -32602, buf_str(&b));
241+ buf_free(&b);
242+ tool_free(&t);
243+ return;
244+ }
245+ res = tool_mcp_result(&t);
246+ send_result(id, res ? res : "{\"content\":[],\"isError\":true}");
247+ free(res);
248+ tool_free(&t);
249+ return;
250+ }
251+ if (strcmp(method, "resources/list") == 0) {
252+ send_result(id,
253+ "{\"resources\":[{\"uri\":\"" RESOURCE_URI "\","
254+ "\"name\":\"knowledge-graph\",\"title\":\"Knowledge Graph\","
255+ "\"description\":\"The full knowledge graph with all entities "
256+ "and relations\",\"mimeType\":\"application/json\"}]}");
257+ return;
258+ }
259+ if (strcmp(method, "resources/templates/list") == 0) {
260+ send_result(id, "{\"resourceTemplates\":[]}");
261+ return;
262+ }
263+ if (strcmp(method, "prompts/list") == 0) {
264+ send_result(id, "{\"prompts\":[]}");
265+ return;
266+ }
267+ if (strcmp(method, "resources/read") == 0) {
268+ yyjson_val *params = yyjson_obj_get(root, "params");
269+ const char *uri = NULL;
270+ char *text;
271+ buf_t b;
272+
273+ if (params && yyjson_is_obj(params)) {
274+ yyjson_val *u = yyjson_obj_get(params, "uri");
275+ if (u && yyjson_is_str(u)) uri = yyjson_get_str(u);
276+ }
277+ if (!uri) { send_error(id, -32602, "resources/read needs params.uri"); return; }
278+ if (strcmp(uri, RESOURCE_URI) != 0) {
279+ send_error(id, -32002, "Unknown resource: this server serves "
280+ RESOURCE_URI " only");
281+ return;
282+ }
283+ text = resource_text();
284+ buf_init(&b);
285+ buf_puts(&b, "{\"contents\":[{\"uri\":\"" RESOURCE_URI
286+ "\",\"mimeType\":\"application/json\",\"text\":");
287+ json_str(&b, text ? text : "{}");
288+ buf_puts(&b, "}]}");
289+ send_result(id, buf_str(&b));
290+ buf_free(&b);
291+ free(text);
292+ return;
293+ }
294+ if (strcmp(method, "resources/subscribe") == 0 ||
295+ strcmp(method, "resources/unsubscribe") == 0) {
296+ /* Accepted and ignored: there is no channel to notify on from a
297+ * request/response connector, so a host that subscribes must not be
298+ * left with an error. */
299+ send_result(id, "{}");
300+ return;
301+ }
302+ send_error(id, -32601, "Method not found");
303+}
304+
305+static int mode_mcp(void)
306+{
307+ char *line = (char *)malloc((size_t)STDIN_LINE_MAX);
308+ if (!line) return 1;
309+
310+ for (;;) {
311+ size_t n = 0;
312+ int c;
313+
314+ /* Read one line by hand: fgets with a fixed buffer would truncate a
315+ * tools/call whose arguments carry a long observation, and a
316+ * truncated line parses as valid-but-wrong JSON rather than failing. */
317+ for (;;) {
318+ c = fgetc(stdin);
319+ if (c == EOF) { if (n == 0) { free(line); return 0; } break; }
320+ if (c == '\n') break;
321+ if (c == '\r') continue;
322+ if (n + 1 < (size_t)STDIN_LINE_MAX) line[n++] = (char)c;
323+ }
324+ line[n] = '\0';
325+ if (n == 0) {
326+ if (c == EOF) { free(line); return 0; }
327+ continue; /* blank line */
328+ }
329+
330+ {
331+ yyjson_doc *doc = yyjson_read(line, n, 0);
332+ yyjson_val *root, *mv, *id;
333+ const char *method;
334+
335+ if (!doc) {
336+ send_error(NULL, -32700, "Parse error: not valid JSON");
337+ continue;
338+ }
339+ root = yyjson_doc_get_root(doc);
340+ if (!root || !yyjson_is_obj(root)) {
341+ yyjson_doc_free(doc);
342+ send_error(NULL, -32600, "Invalid request: expected an object");
343+ continue;
344+ }
345+ mv = yyjson_obj_get(root, "method");
346+ method = (mv && yyjson_is_str(mv)) ? yyjson_get_str(mv) : NULL;
347+ id = yyjson_obj_get(root, "id");
348+
349+ if (!method) {
350+ /* No method: either a response to something we never sent, or
351+ * a malformed request. A response gets no reply. */
352+ yyjson_doc_free(doc);
353+ if (yyjson_obj_get(root, "result") ||
354+ yyjson_obj_get(root, "error")) continue;
355+ send_error(id, -32600, "Invalid request: missing method");
356+ continue;
357+ }
358+ if (!id) { /* notification */
359+ yyjson_doc_free(doc);
360+ continue;
361+ }
362+
363+ handle_request(root, id, method);
364+ yyjson_doc_free(doc);
365+ }
366+ }
367+}
368+
369+/* ------------------------------------------------------------------ */
370+/* main */
371+/* ------------------------------------------------------------------ */
372+
373+int main(int argc, char **argv)
374+{
375+ int i;
376+
377+ for (i = 1; i < argc; i++) {
378+ if (strcmp(argv[i], "--meta") == 0) return mode_meta();
379+ if (strcmp(argv[i], "--mcp") == 0) return mode_mcp();
380+ if (strcmp(argv[i], "--version") == 0) {
381+ printf("%s %s\n", PLUGIN_ID, PLUGIN_VER);
382+ return 0;
383+ }
384+ if (strcmp(argv[i], "--schema") == 0) {
385+ char *t = tools_list_json();
386+ printf("%s\n", t ? t : "[]");
387+ free(t);
388+ return 0;
389+ }
390+ if (strcmp(argv[i], "--help") == 0) {
391+ printf("usage: %s [--meta|--mcp|--schema|--version]\n"
392+ "With no arguments this plugin runs as a CGI handler: the\n"
393+ "browser page on GET, the JSON API on ?action=... or POST.\n",
394+ PLUGIN_ID);
395+ return 0;
396+ }
397+ }
398+ if (getenv("SX_PLUGIN_META")) return mode_meta();
399+ if (getenv("SX_PLUGIN_MCP")) return mode_mcp();
400+
401+ return api_handle();
402+}
src/tools.c+1127−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..ecab2acindex 0000000..ecab2ac
--- /dev/null--- /dev/null
+++ b/src/tools.c+++ b/src/tools.c
@@ -0,0 +1,1127 @@@@ -0,0 +1,1127 @@
1+/*
2+ * tools.c - the nine knowledge-graph tools for plugin_memory.
3+ *
4+ * These are exactly the tools of the reference MCP memory server, with the
5+ * same names, the same input schemas and the same semantics, so an agent that
6+ * was tuned against the reference cannot tell the difference:
7+ *
8+ * create_entities skip existing names, report them in `skipped`
9+ * create_relations both ends must exist, dedupe the triple
10+ * add_observations entity must exist, dedupe within call and store
11+ * delete_entities report deleted/notFound, cascade relations
12+ * delete_observations exact-text match, count across missing entities
13+ * delete_relations exact triple match, count what actually went
14+ * read_graph optional entityTypes + observationLimit
15+ * search_nodes case-insensitive substring, limit, either-end
16+ * open_nodes exact names, either-end relations
17+ *
18+ * The rules that are easy to lose, and are therefore pinned by tests:
19+ *
20+ * - create_entities SKIPS a name that already exists (or repeats earlier in
21+ * the same batch) rather than adding its observations, and must say so in
22+ * the result - otherwise an agent reads a skip as a store.
23+ * - create_relations validates EVERY relation before adding ANY, so one bad
24+ * end fails the whole call and nothing is written.
25+ * - add_observations keeps the first occurrence of a string repeated within
26+ * one call.
27+ * - the read tools keep a relation when EITHER endpoint is in the result
28+ * set; requiring both made a node's outside connections undiscoverable.
29+ * - observationLimit 0 is a real value (names, types and counts only) and is
30+ * not the same as omitting the option; observationCount appears only when
31+ * the limit was given.
32+ * - a line the loader cannot parse is preserved and written back, so a
33+ * hand-edited graph survives every tool call.
34+ *
35+ * A tool never frees its own result: the caller serialises and then calls
36+ * tool_free(). That keeps the MCP loop leak-free and stops an error path from
37+ * destroying the error it is about to report.
38+ *
39+ * MIT License. Copyright (c) 2026 SCORPIOX INC.
40+ */
41+
42+#if defined(_WIN32) && !defined(_WIN32_WINNT)
43+# define _WIN32_WINNT 0x0601
44+#endif
45+
46+#if !defined(_WIN32)
47+# define _POSIX_C_SOURCE 200809L
48+# define _DEFAULT_SOURCE 1
49+#endif
50+
51+#include <stdio.h>
52+#include <stdlib.h>
53+#include <string.h>
54+#include <stdarg.h>
55+
56+#include "memory.h"
57+
58+/* ------------------------------------------------------------------ */
59+/* Read options */
60+/* ------------------------------------------------------------------ */
61+
62+void read_opt_init(read_opt_t *o)
63+{
64+ memset(o, 0, sizeof *o);
65+ o->max_entities = 0; /* 0 = unlimited */
66+}
67+
68+static void read_opt_free_types(read_opt_t *o)
69+{
70+ size_t i;
71+ for (i = 0; i < o->n_types; i++) free(o->types[i]);
72+ free(o->types);
73+ o->types = NULL;
74+ o->n_types = 0;
75+}
76+
77+/* ------------------------------------------------------------------ */
78+/* Result record */
79+/* ------------------------------------------------------------------ */
80+
81+void tool_out_init(tool_out_t *t)
82+{
83+ memset(t, 0, sizeof *t);
84+}
85+
86+void tool_err(tool_out_t *t, const char *fmt, ...)
87+{
88+ char tmp[768];
89+ va_list ap;
90+ va_start(ap, fmt);
91+ vsnprintf(tmp, sizeof tmp, fmt, ap);
92+ va_end(ap);
93+ if (!t->error) t->error = dup_or_null(tmp);
94+ t->is_error = 1;
95+}
96+
97+void tool_free(tool_out_t *t)
98+{
99+ if (!t) return;
100+ if (t->md) yyjson_mut_doc_free(t->md);
101+ free(t->notice);
102+ free(t->error);
103+ memset(t, 0, sizeof *t);
104+}
105+
106+static void tool_start(tool_out_t *t)
107+{
108+ if (t->md) return;
109+ t->md = yyjson_mut_doc_new(NULL);
110+ if (!t->md) { tool_err(t, "out of memory"); return; }
111+ t->root = yyjson_mut_obj(t->md);
112+ if (!t->root) { tool_err(t, "out of memory"); return; }
113+ yyjson_mut_doc_set_root(t->md, t->root);
114+}
115+
116+/* ------------------------------------------------------------------ */
117+/* Argument helpers */
118+/* ------------------------------------------------------------------ */
119+
120+static yyjson_val *arg_get(yyjson_val *obj, const char *key)
121+{
122+ return obj ? yyjson_obj_get(obj, key) : NULL;
123+}
124+
125+static const char *arg_str(yyjson_val *obj, const char *key)
126+{
127+ yyjson_val *v = arg_get(obj, key);
128+ return (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL;
129+}
130+
131+/* Optional integer >= lo. Returns 1 when present and valid. */
132+static int arg_opt_int(yyjson_val *obj, const char *key, int lo, int *out)
133+{
134+ yyjson_val *v = arg_get(obj, key);
135+ long long n;
136+ if (!v || yyjson_is_null(v)) return 0;
137+ if (!yyjson_is_int(v)) return -1;
138+ n = (long long)yyjson_get_sint(v);
139+ if (n < lo) return -1;
140+ if (n > 100000000LL) n = 100000000LL;
141+ *out = (int)n;
142+ return 1;
143+}
144+
145+/* ------------------------------------------------------------------ */
146+/* Mut helpers */
147+/* ------------------------------------------------------------------ */
148+
149+static yyjson_mut_val *ent_to_mut(yyjson_mut_doc *md, const entity_t *e,
150+ const read_opt_t *o)
151+{
152+ yyjson_mut_val *o_ = yyjson_mut_obj(md);
153+ yyjson_mut_val *arr = yyjson_mut_arr(md);
154+ size_t i, lim;
155+
156+ if (!o_ || !arr) return o_;
157+ yyjson_mut_obj_add_str(md, o_, "name", e->name ? e->name : "");
158+ yyjson_mut_obj_add_str(md, o_, "entityType", e->etype ? e->etype : "");
159+ lim = e->n_obs;
160+ if (o && o->has_limit && (size_t)o->limit < lim) lim = (size_t)o->limit;
161+ for (i = 0; i < lim; i++)
162+ yyjson_mut_arr_add_str(md, arr, e->obs[i] ? e->obs[i] : "");
163+ yyjson_mut_obj_add_val(md, o_, "observations", arr);
164+ if (o && o->has_limit && o->has_count)
165+ yyjson_mut_obj_add_uint(md, o_, "observationCount", (uint64_t)e->n_obs);
166+ return o_;
167+}
168+
169+static yyjson_mut_val *rel_to_mut(yyjson_mut_doc *md, const char *from,
170+ const char *to, const char *rtype)
171+{
172+ yyjson_mut_val *r = yyjson_mut_obj(md);
173+ if (!r) return NULL;
174+ yyjson_mut_obj_add_str(md, r, "from", from ? from : "");
175+ yyjson_mut_obj_add_str(md, r, "to", to ? to : "");
176+ yyjson_mut_obj_add_str(md, r, "relationType", rtype ? rtype : "");
177+ return r;
178+}
179+
180+static int rel_same(const relation_t *a, const char *from, const char *to,
181+ const char *rtype)
182+{
183+ return strcmp(a->from, from) == 0 && strcmp(a->to, to) == 0 &&
184+ strcmp(a->rtype, rtype) == 0;
185+}
186+/* The same triple test for two plain field triples - used when one side is a
187+ * JSON object rather than a stored relation. A NULL on either side means
188+ * "no match", never a strcmp on NULL. */
189+static int rel_same_fields(const char *af, const char *at, const char *ar,
190+ const char *bf, const char *bt, const char *br)
191+{
192+ if (!af || !at || !ar || !bf || !bt || !br) return 0;
193+ return strcmp(af, bf) == 0 && strcmp(at, bt) == 0 && strcmp(ar, br) == 0;
194+}
195+
196+
197+/* Emit {"entities":[...],"relations":[...]} for a chosen set of entities.
198+ * A relation survives when EITHER endpoint is in the set, which is what makes
199+ * a node's connections to nodes outside the result set discoverable. */
200+static void emit_set(tool_out_t *t, entity_t **ents, size_t n_ents,
201+ const read_opt_t *o)
202+{
203+ yyjson_mut_doc *md = t->md;
204+ yyjson_mut_val *ea = yyjson_mut_arr(md);
205+ yyjson_mut_val *ra = yyjson_mut_arr(md);
206+ size_t i, r;
207+
208+ for (i = 0; i < n_ents; i++)
209+ yyjson_mut_arr_add_val(ea, ent_to_mut(md, ents[i], o));
210+
211+ for (r = 0; r < G.n_rel; r++) {
212+ int hit = 0;
213+ for (i = 0; i < n_ents; i++) {
214+ if (strcmp(G.rel[r].from, ents[i]->name) == 0 ||
215+ strcmp(G.rel[r].to, ents[i]->name) == 0) { hit = 1; break; }
216+ }
217+ if (!hit) continue;
218+ yyjson_mut_arr_add_val(ra, rel_to_mut(md, G.rel[r].from, G.rel[r].to,
219+ G.rel[r].rtype));
220+ }
221+ yyjson_mut_obj_add_val(md, t->root, "entities", ea);
222+ yyjson_mut_obj_add_val(md, t->root, "relations", ra);
223+}
224+
225+/* Emit the whole graph, honouring entityTypes + observationLimit. The kept
226+ * entities are collected as pointers first so the relation filter is a
227+ * pointer compare rather than a re-read of the JSON just built. */
228+static void emit_all(tool_out_t *t, const read_opt_t *o)
229+{
230+ entity_t **kept;
231+ size_t i, k, w;
232+
233+ kept = (entity_t **)malloc((G.n_ent ? G.n_ent : 1) * sizeof *kept);
234+ if (!kept) { tool_err(t, "out of memory"); return; }
235+
236+ w = 0;
237+ for (i = 0; i < G.n_ent; i++) {
238+ if (o->has_types) {
239+ size_t q;
240+ int ok = 0;
241+ for (q = 0; q < o->n_types; q++)
242+ if (strcmp(o->types[q], G.ent[i].etype) == 0) { ok = 1; break; }
243+ if (!ok) continue;
244+ }
245+ if (o->max_entities > 0 && w >= (size_t)o->max_entities) break;
246+ kept[w++] = &G.ent[i];
247+ }
248+ k = w;
249+ emit_set(t, kept, k, o);
250+ free(kept);
251+}
252+
253+/* Pull observationLimit / entityTypes out of args. 0 ok, -1 malformed. */
254+static int parse_read_opts(yyjson_val *args, read_opt_t *o)
255+{
256+ yyjson_val *v;
257+ if (!args) return 0;
258+
259+ v = yyjson_obj_get(args, "observationLimit");
260+ if (v && !yyjson_is_null(v)) {
261+ int r = arg_opt_int(args, "observationLimit", 0, &o->limit);
262+ if (r != 1) return -1;
263+ o->has_limit = 1;
264+ o->has_count = 1;
265+ }
266+ v = yyjson_obj_get(args, "entityTypes");
267+ if (v && !yyjson_is_null(v)) {
268+ if (!yyjson_is_arr(v) || yyjson_arr_size(v) == 0) return -1;
269+ if (str_arr_from(v, &o->types, &o->n_types, 1000) != 0) return -1;
270+ if (o->n_types == 0) return -1;
271+ o->has_types = 1;
272+ }
273+ return 0;
274+}
275+
276+/* ------------------------------------------------------------------ */
277+/* create_entities */
278+/* ------------------------------------------------------------------ */
279+
280+void tool_create_entities(yyjson_val *args, tool_out_t *t)
281+{
282+ yyjson_val *arr = arg_get(args, "entities");
283+ yyjson_mut_val *created, *skipped;
284+ size_t i, max;
285+ char err[256];
286+
287+ if (!arr || !yyjson_is_arr(arr)) {
288+ tool_err(t, "Missing required parameter: entities");
289+ return;
290+ }
291+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
292+
293+ tool_start(t);
294+ if (t->is_error) return;
295+ created = yyjson_mut_arr(t->md);
296+ skipped = yyjson_mut_arr(t->md);
297+ max = yyjson_arr_size(arr);
298+
299+ /* Names already requested earlier in this same batch. */
300+ for (i = 0; i < max; i++) {
301+ yyjson_val *e = yyjson_arr_get(arr, i);
302+ const char *nm, *ty, *prior;
303+ yyjson_val *ob;
304+ char **obs = NULL;
305+ size_t n_obs = 0, j;
306+ int dup = 0;
307+
308+ if (!e || !yyjson_is_obj(e)) {
309+ tool_err(t, "Each entity must be an object with name, entityType "
310+ "and observations.");
311+ return;
312+ }
313+ nm = arg_str(e, "name");
314+ ty = arg_str(e, "entityType");
315+ ob = arg_get(e, "observations");
316+ if (!nm || !*nm || !ty || !*ty) {
317+ tool_err(t, "Each entity needs a non-empty name and entityType.");
318+ return;
319+ }
320+ if (ob && !yyjson_is_arr(ob)) {
321+ tool_err(t, "Entity '%s': observations must be an array of "
322+ "strings.", nm);
323+ return;
324+ }
325+ /* repeat earlier in this batch? */
326+ for (j = 0; j < i && !dup; j++) {
327+ prior = arg_str(yyjson_arr_get(arr, j), "name");
328+ if (prior && strcmp(prior, nm) == 0) dup = 1;
329+ }
330+ if (dup || ent_find(&G, nm) != NULL) {
331+ yyjson_mut_arr_add_str(t->md, skipped, nm);
332+ continue;
333+ }
334+ if (ob && str_arr_from(ob, &obs, &n_obs,
335+ (size_t)MAX_OBS_PER_ENT_DEFAULT) != 0) {
336+ tool_err(t, "out of memory");
337+ return;
338+ }
339+ if (ent_add(&G, nm, ty, obs, n_obs, err, sizeof err) != 0) {
340+ for (j = 0; j < n_obs; j++) free(obs[j]);
341+ free(obs);
342+ tool_err(t, "%s", err[0] ? err : "cannot add the entity");
343+ return;
344+ }
345+ for (j = 0; j < n_obs; j++) free(obs[j]);
346+ free(obs);
347+ G.ent[G.n_ent - 1].keep = 1;
348+ }
349+
350+ if (graph_save(err, sizeof err) != 0) {
351+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
352+ return;
353+ }
354+
355+ {
356+ read_opt_t no;
357+ size_t k;
358+ read_opt_init(&no);
359+ for (k = 0; k < G.n_ent; k++) {
360+ if (!G.ent[k].keep) continue;
361+ yyjson_mut_arr_add_val(created, ent_to_mut(t->md, &G.ent[k], &no));
362+ }
363+ yyjson_mut_obj_add_val(t->md, t->root, "entities", created);
364+ if (yyjson_mut_arr_size(skipped) > 0) {
365+ size_t ns = yyjson_mut_arr_size(skipped), q;
366+ buf_t nb;
367+ char head[128];
368+ yyjson_mut_obj_add_val(t->md, t->root, "skipped", skipped);
369+ buf_init(&nb);
370+ snprintf(head, sizeof head, "Skipped %zu %s: ", ns,
371+ ns == 1 ? "entity that already exists"
372+ : "entities that already exist");
373+ buf_puts(&nb, head);
374+ {
375+ /* Walk the array we just built with the iterator that matches
376+ * it: yyjson's immutable getters on a mutable value are a
377+ * type-lie, not a convenience. */
378+ yyjson_mut_arr_iter ai;
379+ yyjson_mut_val *item;
380+ size_t seen = 0;
381+ yyjson_mut_arr_iter_init(skipped, &ai);
382+ while ((item = yyjson_mut_arr_iter_next(&ai)) != NULL) {
383+ if (seen++) buf_puts(&nb, ", ");
384+ buf_puts(&nb, yyjson_mut_get_str(item));
385+ }
386+ (void)q;
387+ }
388+ buf_puts(&nb, ns == 1
389+ ? ". Its observations were not added; use "
390+ "add_observations for existing entities."
391+ : ". Their observations were not added; use "
392+ "add_observations for existing entities.");
393+ t->notice = dup_or_null(buf_str(&nb));
394+ buf_free(&nb);
395+ }
396+ }
397+
398+ for (i = 0; i < G.n_ent; i++) G.ent[i].keep = 0;
399+}
400+
401+/* ------------------------------------------------------------------ */
402+/* create_relations */
403+/* ------------------------------------------------------------------ */
404+
405+void tool_create_relations(yyjson_val *args, tool_out_t *t)
406+{
407+ yyjson_val *arr = arg_get(args, "relations");
408+ yyjson_mut_val *created;
409+ size_t i, max;
410+ char err[256];
411+
412+ if (!arr || !yyjson_is_arr(arr)) {
413+ tool_err(t, "Missing required parameter: relations");
414+ return;
415+ }
416+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
417+ max = yyjson_arr_size(arr);
418+
419+ /* Validate every relation before adding any: one missing end fails the
420+ * whole call and nothing is written. */
421+ for (i = 0; i < max; i++) {
422+ yyjson_val *r = yyjson_arr_get(arr, i);
423+ const char *from = r ? arg_str(r, "from") : NULL;
424+ const char *to = r ? arg_str(r, "to") : NULL;
425+ const char *ty = r ? arg_str(r, "relationType") : NULL;
426+ if (!r || !yyjson_is_obj(r) || !from || !*from || !to || !*to ||
427+ !ty || !*ty) {
428+ tool_err(t, "Each relation must be an object with non-empty from, "
429+ "to and relationType.");
430+ return;
431+ }
432+ if (!ent_find(&G, from)) {
433+ tool_err(t, "Entity with name %s not found", from);
434+ return;
435+ }
436+ if (!ent_find(&G, to)) {
437+ tool_err(t, "Entity with name %s not found", to);
438+ return;
439+ }
440+ }
441+
442+ tool_start(t);
443+ if (t->is_error) return;
444+ created = yyjson_mut_arr(t->md);
445+
446+ for (i = 0; i < max; i++) {
447+ yyjson_val *r = yyjson_arr_get(arr, i);
448+ const char *from = arg_str(r, "from");
449+ const char *to = arg_str(r, "to");
450+ const char *ty = arg_str(r, "relationType");
451+ size_t j;
452+ int dup = 0;
453+
454+ for (j = 0; j < G.n_rel; j++)
455+ if (rel_same(&G.rel[j], from, to, ty)) { dup = 1; break; }
456+ for (j = 0; j < i && !dup; j++) {
457+ yyjson_val *q = yyjson_arr_get(arr, j);
458+ if (rel_same_fields(arg_str(q, "from"), arg_str(q, "to"),
459+ arg_str(q, "relationType"), from, to, ty))
460+ dup = 1;
461+ }
462+ if (dup) continue;
463+ if (rel_add(&G, from, to, ty, err, sizeof err) != 0) {
464+ tool_err(t, "%s", err[0] ? err : "cannot add the relation");
465+ return;
466+ }
467+ yyjson_mut_arr_add_val(created, rel_to_mut(t->md, from, to, ty));
468+ }
469+
470+ if (graph_save(err, sizeof err) != 0) {
471+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
472+ return;
473+ }
474+ yyjson_mut_obj_add_val(t->md, t->root, "relations", created);
475+}
476+
477+/* ------------------------------------------------------------------ */
478+/* add_observations */
479+/* ------------------------------------------------------------------ */
480+
481+void tool_add_observations(yyjson_val *args, tool_out_t *t)
482+{
483+ yyjson_val *arr = arg_get(args, "observations");
484+ yyjson_mut_val *results;
485+ size_t i, max;
486+ char err[256];
487+
488+ if (!arr || !yyjson_is_arr(arr)) {
489+ tool_err(t, "Missing required parameter: observations");
490+ return;
491+ }
492+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
493+
494+ /* Validate first: an unknown entity fails the whole call. */
495+ max = yyjson_arr_size(arr);
496+ for (i = 0; i < max; i++) {
497+ yyjson_val *o_ = yyjson_arr_get(arr, i);
498+ const char *nm = o_ ? arg_str(o_, "entityName") : NULL;
499+ yyjson_val *contents = o_ ? arg_get(o_, "contents") : NULL;
500+ if (!nm || !*nm) {
501+ tool_err(t, "Each observation needs a non-empty entityName.");
502+ return;
503+ }
504+ if (!contents || !yyjson_is_arr(contents)) {
505+ tool_err(t, "Observations for %s must be an array of strings.", nm);
506+ return;
507+ }
508+ if (!ent_find(&G, nm)) {
509+ tool_err(t, "Entity with name %s not found", nm);
510+ return;
511+ }
512+ }
513+
514+ tool_start(t);
515+ if (t->is_error) return;
516+ results = yyjson_mut_arr(t->md);
517+
518+ for (i = 0; i < max; i++) {
519+ yyjson_val *o_ = yyjson_arr_get(arr, i);
520+ const char *nm = arg_str(o_, "entityName");
521+ yyjson_val *contents = arg_get(o_, "contents");
522+ entity_t *e = ent_find(&G, nm);
523+ yyjson_mut_val *one, *added_arr;
524+ size_t j, n_c;
525+
526+ if (!e) continue;
527+ one = yyjson_mut_obj(t->md);
528+ added_arr = yyjson_mut_arr(t->md);
529+ yyjson_mut_obj_add_str(t->md, one, "entityName", nm);
530+
531+ n_c = yyjson_arr_size(contents);
532+ for (j = 0; j < n_c; j++) {
533+ yyjson_val *cv = yyjson_arr_get(contents, j);
534+ const char *c;
535+ size_t k;
536+ int repeat_in_call = 0, already_there = 0;
537+ if (!cv || !yyjson_is_str(cv)) continue;
538+ c = yyjson_get_str(cv);
539+ if (!c) continue;
540+ /* A string repeated within one call is stored and reported once. */
541+ for (k = 0; k < j && !repeat_in_call; k++) {
542+ yyjson_val *pv = yyjson_arr_get(contents, k);
543+ if (pv && yyjson_is_str(pv) &&
544+ strcmp(yyjson_get_str(pv), c) == 0) repeat_in_call = 1;
545+ }
546+ if (repeat_in_call) continue;
547+ for (k = 0; k < e->n_obs; k++)
548+ if (strcmp(e->obs[k], c) == 0) { already_there = 1; break; }
549+ if (already_there) continue;
550+ if (obs_push(e, c))
551+ yyjson_mut_arr_add_str(t->md, added_arr, c);
552+ }
553+ yyjson_mut_obj_add_val(t->md, one, "addedObservations", added_arr);
554+ yyjson_mut_arr_add_val(results, one);
555+ }
556+
557+ if (graph_save(err, sizeof err) != 0) {
558+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
559+ return;
560+ }
561+ yyjson_mut_obj_add_val(t->md, t->root, "results", results);
562+}
563+
564+/* ------------------------------------------------------------------ */
565+/* delete_entities */
566+/* ------------------------------------------------------------------ */
567+
568+void tool_delete_entities(yyjson_val *args, tool_out_t *t)
569+{
570+ yyjson_val *arr = arg_get(args, "entityNames");
571+ size_t i, n_req, n_deleted = 0;
572+ char err[256];
573+ const char **names = NULL;
574+ int *present = NULL;
575+
576+ if (!arr || !yyjson_is_arr(arr)) {
577+ tool_err(t, "Missing required parameter: entityNames");
578+ return;
579+ }
580+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
581+
582+ n_req = yyjson_arr_size(arr);
583+ names = (const char **)calloc(n_req ? n_req : 1, sizeof *names);
584+ present = (int *)calloc(n_req ? n_req : 1, sizeof *present);
585+ if (!names || !present) {
586+ free((void *)names);
587+ free(present);
588+ tool_err(t, "out of memory");
589+ return;
590+ }
591+
592+ /* Record each requested name and whether the graph held it BEFORE anything
593+ * is removed. Deriving "not found" after the compaction is not possible:
594+ * a name that was deleted and a name that never existed both read as
595+ * absent, so both facts are captured here, as plain ints - the compaction
596+ * below moves G.ent entries, so no entity_t pointer may outlive this loop
597+ * (lesson: a grid of records is not a set of stable addresses). */
598+ for (i = 0; i < n_req; i++) {
599+ yyjson_val *v = yyjson_arr_get(arr, i);
600+ const char *nm = (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL;
601+ size_t k;
602+ int counted = 0;
603+ names[i] = nm;
604+ if (!nm) continue;
605+ for (k = 0; k < G.n_ent; k++)
606+ if (strcmp(G.ent[k].name, nm) == 0) { present[i] = 1; G.ent[k].keep = 1; break; }
607+ for (k = 0; k < i; k++)
608+ if (names[k] && strcmp(names[k], nm) == 0) { counted = 1; break; }
609+ if (present[i] && !counted) n_deleted++;
610+ }
611+
612+ {
613+ size_t w = 0, r2;
614+ for (r2 = 0; r2 < G.n_rel; r2++) {
615+ size_t q;
616+ int hit = 0;
617+ for (q = 0; q < n_req; q++) {
618+ const char *nm = names[q];
619+ if (!nm) continue;
620+ if (strcmp(G.rel[r2].from, nm) == 0 ||
621+ strcmp(G.rel[r2].to, nm) == 0) { hit = 1; break; }
622+ }
623+ if (hit) {
624+ free(G.rel[r2].from);
625+ free(G.rel[r2].to);
626+ free(G.rel[r2].rtype);
627+ continue;
628+ }
629+ G.rel[w++] = G.rel[r2];
630+ }
631+ G.n_rel = w;
632+ }
633+ {
634+ size_t w = 0, r2;
635+ for (r2 = 0; r2 < G.n_ent; r2++) {
636+ if (G.ent[r2].keep) {
637+ size_t q;
638+ for (q = 0; q < G.ent[r2].n_obs; q++) free(G.ent[r2].obs[q]);
639+ free(G.ent[r2].obs);
640+ free(G.ent[r2].name);
641+ free(G.ent[r2].etype);
642+ continue;
643+ }
644+ G.ent[w++] = G.ent[r2];
645+ }
646+ G.n_ent = w;
647+ }
648+
649+ if (graph_save(err, sizeof err) != 0) {
650+ free((void *)names);
651+ free(present);
652+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
653+ return;
654+ }
655+
656+ tool_start(t);
657+ if (!t->is_error) {
658+ buf_t msg;
659+ buf_init(&msg);
660+ if (n_deleted == n_req) {
661+ buf_puts(&msg, "Entities deleted successfully");
662+ } else {
663+ char tmp[96];
664+ int first = 1;
665+ snprintf(tmp, sizeof tmp, "Deleted %zu of %zu entities. Not found: ",
666+ n_deleted, n_req);
667+ buf_puts(&msg, tmp);
668+ for (i = 0; i < n_req; i++) {
669+ if (!names[i] || present[i]) continue;
670+ if (!first) buf_puts(&msg, ", ");
671+ buf_puts(&msg, names[i]);
672+ first = 0;
673+ }
674+ }
675+ yyjson_mut_obj_add_bool(t->md, t->root, "success", 1);
676+ /* add_str keeps the pointer, add_strcpy copies into the doc. The message
677+ * lives in a buf_t that is freed the moment this block ends, so the
678+ * copy is the only way it survives into the serialised result. */
679+ yyjson_mut_obj_add_strcpy(t->md, t->root, "message", buf_str(&msg));
680+ buf_free(&msg);
681+ }
682+ free((void *)names);
683+ free(present);
684+}
685+
686+/* ------------------------------------------------------------------ */
687+/* delete_observations */
688+/* ------------------------------------------------------------------ */
689+
690+void tool_delete_observations(yyjson_val *args, tool_out_t *t)
691+{
692+ yyjson_val *arr = arg_get(args, "deletions");
693+ size_t i, max, requested = 0, deleted = 0;
694+ char err[256];
695+ buf_t missing;
696+
697+ if (!arr || !yyjson_is_arr(arr)) {
698+ tool_err(t, "Missing required parameter: deletions");
699+ return;
700+ }
701+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
702+
703+ buf_init(&missing);
704+ max = yyjson_arr_size(arr);
705+ for (i = 0; i < max; i++) {
706+ yyjson_val *d = yyjson_arr_get(arr, i);
707+ const char *nm = d ? arg_str(d, "entityName") : NULL;
708+ yyjson_val *obs = d ? arg_get(d, "observations") : NULL;
709+ entity_t *e;
710+ size_t j, n_o;
711+
712+ if (!nm || !*nm) {
713+ buf_free(&missing);
714+ tool_err(t, "Each deletion needs a non-empty entityName.");
715+ return;
716+ }
717+ if (!obs || !yyjson_is_arr(obs)) {
718+ buf_free(&missing);
719+ tool_err(t, "Observations for %s must be an array of strings.", nm);
720+ return;
721+ }
722+ e = ent_find(&G, nm);
723+ n_o = yyjson_arr_size(obs);
724+ requested += n_o;
725+ if (!e) {
726+ if (missing.n) buf_puts(&missing, ", ");
727+ buf_puts(&missing, nm);
728+ continue;
729+ }
730+ for (j = 0; j < n_o; j++) {
731+ yyjson_val *v = yyjson_arr_get(obs, j);
732+ const char *c = (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL;
733+ size_t w = 0, q;
734+ if (!c) continue;
735+ for (q = 0; q < e->n_obs; q++) {
736+ if (strcmp(e->obs[q], c) == 0) { free(e->obs[q]); deleted++; continue; }
737+ e->obs[w++] = e->obs[q];
738+ }
739+ e->n_obs = w;
740+ }
741+ }
742+
743+ if (graph_save(err, sizeof err) != 0) {
744+ buf_free(&missing);
745+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
746+ return;
747+ }
748+
749+ tool_start(t);
750+ if (!t->is_error) {
751+ buf_t msg;
752+ buf_init(&msg);
753+ if (deleted == requested) {
754+ buf_puts(&msg, "Observations deleted successfully");
755+ } else {
756+ char tmp[96];
757+ snprintf(tmp, sizeof tmp, "Deleted %zu of %zu observations.",
758+ deleted, requested);
759+ buf_puts(&msg, tmp);
760+ if (missing.n) {
761+ buf_puts(&msg, " Entities not found: ");
762+ buf_puts(&msg, buf_str(&missing));
763+ }
764+ }
765+ yyjson_mut_obj_add_bool(t->md, t->root, "success", 1);
766+ /* add_str keeps the pointer, add_strcpy copies into the doc. The message
767+ * lives in a buf_t that is freed the moment this block ends, so the
768+ * copy is the only way it survives into the serialised result. */
769+ yyjson_mut_obj_add_strcpy(t->md, t->root, "message", buf_str(&msg));
770+ buf_free(&msg);
771+ }
772+ buf_free(&missing);
773+}
774+
775+/* ------------------------------------------------------------------ */
776+/* delete_relations */
777+/* ------------------------------------------------------------------ */
778+
779+void tool_delete_relations(yyjson_val *args, tool_out_t *t)
780+{
781+ yyjson_val *arr = arg_get(args, "relations");
782+ size_t max, before, deleted;
783+ char err[256];
784+
785+ if (!arr || !yyjson_is_arr(arr)) {
786+ tool_err(t, "Missing required parameter: relations");
787+ return;
788+ }
789+ if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; }
790+ max = yyjson_arr_size(arr);
791+
792+ before = G.n_rel;
793+ {
794+ size_t w = 0, r2;
795+ for (r2 = 0; r2 < G.n_rel; r2++) {
796+ size_t q;
797+ int hit = 0;
798+ for (q = 0; q < max; q++) {
799+ yyjson_val *d = yyjson_arr_get(arr, q);
800+ if (!d || !yyjson_is_obj(d)) continue;
801+ if (rel_same_fields(arg_str(d, "from"), arg_str(d, "to"),
802+ arg_str(d, "relationType"),
803+ G.rel[r2].from, G.rel[r2].to,
804+ G.rel[r2].rtype)) { hit = 1; break; }
805+ }
806+ if (hit) {
807+ free(G.rel[r2].from);
808+ free(G.rel[r2].to);
809+ free(G.rel[r2].rtype);
810+ continue;
811+ }
812+ G.rel[w++] = G.rel[r2];
813+ }
814+ G.n_rel = w;
815+ }
816+ deleted = before - G.n_rel;
817+
818+ if (graph_save(err, sizeof err) != 0) {
819+ tool_err(t, "%s", err[0] ? err : "cannot write the graph file");
820+ return;
821+ }
822+
823+ tool_start(t);
824+ if (!t->is_error) {
825+ buf_t msg;
826+ buf_init(&msg);
827+ if (deleted == max) {
828+ buf_puts(&msg, "Relations deleted successfully");
829+ } else {
830+ char tmp[128];
831+ snprintf(tmp, sizeof tmp,
832+ "Deleted %zu of %zu relations. The rest matched nothing.",
833+ deleted, max);
834+ buf_puts(&msg, tmp);
835+ }
836+ yyjson_mut_obj_add_bool(t->md, t->root, "success", 1);
837+ /* add_str keeps the pointer, add_strcpy copies into the doc. The message
838+ * lives in a buf_t that is freed the moment this block ends, so the
839+ * copy is the only way it survives into the serialised result. */
840+ yyjson_mut_obj_add_strcpy(t->md, t->root, "message", buf_str(&msg));
841+ buf_free(&msg);
842+ }
843+}
844+
845+/* ------------------------------------------------------------------ */
846+/* The read tools */
847+/* ------------------------------------------------------------------ */
848+
849+void tool_read_graph(yyjson_val *args, tool_out_t *t)
850+{
851+ read_opt_t o;
852+ read_opt_init(&o);
853+ if (parse_read_opts(args, &o) != 0) {
854+ read_opt_free_types(&o);
855+ tool_err(t, "observationLimit must be an integer >= 0 and entityTypes "
856+ "a non-empty array of strings.");
857+ return;
858+ }
859+ if (graph_load() != 0) {
860+ read_opt_free_types(&o);
861+ tool_err(t, "%s", g_data_err[0]);
862+ return;
863+ }
864+ tool_start(t);
865+ if (!t->is_error) emit_all(t, &o);
866+ read_opt_free_types(&o);
867+}
868+
869+void tool_search_nodes(yyjson_val *args, tool_out_t *t)
870+{
871+ read_opt_t o;
872+ const char *query;
873+ entity_t **hits;
874+ size_t i, n_hits = 0, cap;
875+ int rc;
876+
877+ read_opt_init(&o);
878+ if (!args || !yyjson_is_str(yyjson_obj_get(args, "query"))) {
879+ tool_err(t, "Missing required parameter: query");
880+ return;
881+ }
882+ query = yyjson_get_str(yyjson_obj_get(args, "query"));
883+ rc = arg_opt_int(args, "limit", 1, &o.max_entities);
884+ if (rc == -1) { tool_err(t, "limit must be an integer >= 1"); return; }
885+ if (parse_read_opts(args, &o) != 0) {
886+ read_opt_free_types(&o);
887+ tool_err(t, "observationLimit must be an integer >= 0.");
888+ return;
889+ }
890+ if (graph_load() != 0) {
891+ read_opt_free_types(&o);
892+ tool_err(t, "%s", g_data_err[0]);
893+ return;
894+ }
895+
896+ cap = G.n_ent ? G.n_ent : 1;
897+ hits = (entity_t **)malloc(cap * sizeof *hits);
898+ if (!hits) { read_opt_free_types(&o); tool_err(t, "out of memory"); return; }
899+
900+ for (i = 0; i < G.n_ent; i++) {
901+ size_t q;
902+ int hit = str_icontains(G.ent[i].name, query) ||
903+ str_icontains(G.ent[i].etype, query);
904+ for (q = 0; !hit && q < G.ent[i].n_obs; q++)
905+ if (str_icontains(G.ent[i].obs[q], query)) hit = 1;
906+ if (hit) hits[n_hits++] = &G.ent[i];
907+ if (o.max_entities > 0 && n_hits >= (size_t)o.max_entities) break;
908+ }
909+
910+ tool_start(t);
911+ if (!t->is_error) emit_set(t, hits, n_hits, &o);
912+ free(hits);
913+ read_opt_free_types(&o);
914+}
915+
916+void tool_open_nodes(yyjson_val *args, tool_out_t *t)
917+{
918+ read_opt_t o;
919+ yyjson_val *arr;
920+ entity_t **want;
921+ size_t i, max, n_want = 0;
922+
923+ read_opt_init(&o);
924+ if (!args) { tool_err(t, "Missing required parameter: names"); return; }
925+ arr = yyjson_obj_get(args, "names");
926+ if (!arr || !yyjson_is_arr(arr)) {
927+ tool_err(t, "Missing required parameter: names");
928+ return;
929+ }
930+ if (parse_read_opts(args, &o) != 0) {
931+ read_opt_free_types(&o);
932+ tool_err(t, "observationLimit must be an integer >= 0.");
933+ return;
934+ }
935+ if (graph_load() != 0) {
936+ read_opt_free_types(&o);
937+ tool_err(t, "%s", g_data_err[0]);
938+ return;
939+ }
940+
941+ max = yyjson_arr_size(arr);
942+ want = (entity_t **)malloc(((max ? max : 1)) * sizeof *want);
943+ if (!want) { read_opt_free_types(&o); tool_err(t, "out of memory"); return; }
944+
945+ /* Stored order, one entry per matching entity; names that miss are
946+ * simply skipped. */
947+ for (i = 0; i < G.n_ent && n_want < max; i++) {
948+ size_t q;
949+ for (q = 0; q < max; q++) {
950+ yyjson_val *v = yyjson_arr_get(arr, q);
951+ const char *nm = (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL;
952+ if (nm && strcmp(nm, G.ent[i].name) == 0) { want[n_want++] = &G.ent[i]; break; }
953+ }
954+ }
955+
956+ tool_start(t);
957+ if (!t->is_error) emit_set(t, want, n_want, &o);
958+ free(want);
959+ read_opt_free_types(&o);
960+}
961+
962+/* ------------------------------------------------------------------ */
963+/* tools/list */
964+/* ------------------------------------------------------------------ */
965+
966+static const char *TOOLS_LIST_JSON =
967+"["
968+"{\"name\":\"create_entities\","
969+"\"description\":\"Create multiple new entities in the knowledge graph. An entity whose name already exists, or repeats an earlier entity in the same call, is skipped and its observations are not added; the result lists the skipped names in `skipped`. Use add_observations to add observations to an existing entity.\","
970+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"entities\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\",\"description\":\"The name of the entity\"},\"entityType\":{\"type\":\"string\",\"description\":\"The type of the entity\"},\"observations\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of observation contents associated with the entity\"}},\"required\":[\"name\",\"entityType\",\"observations\"]},\"description\":\"The entities to create, each with a name unique in the graph\"}},\"required\":[\"entities\"]},"
971+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}},"
972+
973+"{\"name\":\"create_relations\","
974+"\"description\":\"Create multiple new relations between entities in the knowledge graph. Relations should be in active voice.\","
975+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"relations\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"from\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation starts\"},\"to\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation ends\"},\"relationType\":{\"type\":\"string\",\"description\":\"The type of the relation\"}},\"required\":[\"from\",\"to\",\"relationType\"]},\"description\":\"The relations to create. Both ends must name existing entities; a relation already in the graph is not added again\"}},\"required\":[\"relations\"]},"
976+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}},"
977+
978+"{\"name\":\"add_observations\","
979+"\"description\":\"Add new observations to existing entities in the knowledge graph.\","
980+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"observations\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"entityName\":{\"type\":\"string\",\"description\":\"The name of the entity to add the observations to\"},\"contents\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of observation contents to add\"}},\"required\":[\"entityName\",\"contents\"]},\"description\":\"The observations to add, grouped by entity. Each entity must already exist; an observation it already has is not added again\"}},\"required\":[\"observations\"]},"
981+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}},"
982+
983+"{\"name\":\"delete_entities\","
984+"\"description\":\"Delete whole entities from the knowledge graph, together with every relation that points to or from them and all their observations. Use it only to remove an entity entirely; to remove a link between two entities and keep both, use delete_relations, and to remove facts from an entity, use delete_observations. Cannot be undone.\","
985+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"entityNames\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of entity names to delete\"}},\"required\":[\"entityNames\"]},"
986+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":true,\"openWorldHint\":false}},"
987+
988+"{\"name\":\"delete_observations\","
989+"\"description\":\"Delete specific observations from entities in the knowledge graph.\","
990+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"deletions\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"entityName\":{\"type\":\"string\",\"description\":\"The name of the entity containing the observations\"},\"observations\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of observations to delete\"}},\"required\":[\"entityName\",\"observations\"]},\"description\":\"The observations to delete, grouped by entity, each matched by its exact text\"}},\"required\":[\"deletions\"]},"
991+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":true,\"openWorldHint\":false}},"
992+
993+"{\"name\":\"delete_relations\","
994+"\"description\":\"Delete specific relations (from, to, relationType) from the knowledge graph and keep the entities they connect. Each relation must match an existing one exactly on all three fields; if unsure, call open_nodes (or search_nodes) first to read the stored relationType. Use it to remove a link between two entities; to remove an entity itself, use delete_entities. Cannot be undone.\","
995+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"relations\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"from\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation starts\"},\"to\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation ends\"},\"relationType\":{\"type\":\"string\",\"description\":\"The type of the relation\"}},\"required\":[\"from\",\"to\",\"relationType\"]},\"description\":\"An array of relations to delete\"}},\"required\":[\"relations\"]},"
996+"\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":true,\"openWorldHint\":false}},"
997+
998+"{\"name\":\"read_graph\","
999+"\"description\":\"Read the entire knowledge graph: every entity with its observations, and every relation. The result grows with the graph, so use this only when you need everything; prefer search_nodes to find entities by keyword and open_nodes to read entities whose names you know.\","
1000+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"entityTypes\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"Return only entities whose entityType is one of these (exact match), and only the relations that touch one of them. Omit to return every entity.\"},\"observationLimit\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"Return at most this many observations per entity (the first ones, in the order they were added) and add each entity's total as observationCount. Use 0 for names, types and counts only: a cheap overview of a large graph, after which open_nodes reads the entities you need in full. Omit to return every observation.\"}}},"
1001+"\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}},"
1002+
1003+"{\"name\":\"search_nodes\","
1004+"\"description\":\"Search the knowledge graph for entities whose name, type or observations contain the query (case-insensitive). Use this when you have a keyword, a topic or part of a name but not the exact entity names. Prefer open_nodes when you already know the exact names, and use read_graph only when you need the whole graph. Returns the matching entities and every relation that touches one of them.\","
1005+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\",\"description\":\"The search query to match against entity names, types and observation content\"},\"limit\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Return at most this many matching entities (the first matches, in stored order), with the relations that touch them. Omit to return every match.\"},\"observationLimit\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"Return at most this many observations per entity (the first ones, in the order they were added) and add each entity's total as observationCount. Use 0 for names, types and counts only: a cheap overview of a large graph, after which open_nodes reads the entities you need in full. Omit to return every observation.\"}},\"required\":[\"query\"]},"
1006+"\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}},"
1007+
1008+"{\"name\":\"open_nodes\","
1009+"\"description\":\"Retrieve specific entities by their exact names, with every relation that touches one of them. Use this when you already know the names (from the conversation, or from an earlier search_nodes or read_graph result); it is the cheapest way to read entities you can name. Prefer search_nodes when you only have a keyword or part of a name. Names that do not exist are skipped.\","
1010+"\"inputSchema\":{\"type\":\"object\",\"properties\":{\"names\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of entity names to retrieve\"},\"observationLimit\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"Return at most this many observations per entity (the first ones, in the order they were added) and add each entity's total as observationCount. Use 0 for names, types and counts only: a cheap overview of a large graph, after which open_nodes reads the entities you need in full. Omit to return every observation.\"}},\"required\":[\"names\"]},"
1011+"\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}}"
1012+"]";
1013+
1014+char *tools_list_json(void)
1015+{
1016+ return dup_or_null(TOOLS_LIST_JSON);
1017+}
1018+
1019+int tool_dispatch(const char *name, yyjson_val *args, tool_out_t *out)
1020+{
1021+ tool_out_init(out);
1022+ if (!name) return -1;
1023+ if (strcmp(name, "create_entities") == 0) { tool_create_entities(args, out); return 0; }
1024+ if (strcmp(name, "create_relations") == 0) { tool_create_relations(args, out); return 0; }
1025+ if (strcmp(name, "add_observations") == 0) { tool_add_observations(args, out); return 0; }
1026+ if (strcmp(name, "delete_entities") == 0) { tool_delete_entities(args, out); return 0; }
1027+ if (strcmp(name, "delete_observations") == 0) { tool_delete_observations(args, out); return 0; }
1028+ if (strcmp(name, "delete_relations") == 0) { tool_delete_relations(args, out); return 0; }
1029+ if (strcmp(name, "read_graph") == 0) { tool_read_graph(args, out); return 0; }
1030+ if (strcmp(name, "search_nodes") == 0) { tool_search_nodes(args, out); return 0; }
1031+ if (strcmp(name, "open_nodes") == 0) { tool_open_nodes(args, out); return 0; }
1032+ return -1;
1033+}
1034+
1035+/* ------------------------------------------------------------------ */
1036+/* Serialisation */
1037+/* ------------------------------------------------------------------ */
1038+
1039+char *tool_mcp_result(tool_out_t *t)
1040+{
1041+ buf_t b;
1042+ char *out;
1043+
1044+ buf_init(&b);
1045+ if (t->is_error) {
1046+ /* A tool-level failure is a *result* with isError, not a JSON-RPC
1047+ * error: the call itself succeeded and this is what hosts render. */
1048+ buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":");
1049+ json_str(&b, t->error ? t->error : "the tool could not be completed");
1050+ buf_puts(&b, "}],\"isError\":true}");
1051+ out = dup_or_null(buf_str(&b));
1052+ buf_free(&b);
1053+ return out;
1054+ }
1055+
1056+ {
1057+ char *pretty = (t->md && t->root)
1058+ ? yyjson_mut_write(t->md, YYJSON_WRITE_PRETTY_TWO_SPACES, NULL)
1059+ : dup_or_null("{}");
1060+ buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":");
1061+ json_str(&b, pretty ? pretty : "{}");
1062+ buf_puts(&b, "}");
1063+ free(pretty);
1064+ if (t->notice && *t->notice) {
1065+ buf_puts(&b, ",{\"type\":\"text\",\"text\":");
1066+ json_str(&b, t->notice);
1067+ buf_puts(&b, "}");
1068+ }
1069+ buf_puts(&b, "],\"isError\":false");
1070+ }
1071+
1072+ if (t->md && t->root && yyjson_mut_obj_size(t->root) > 0) {
1073+ char *compact = yyjson_mut_write(t->md, 0, NULL);
1074+ if (compact) {
1075+ buf_puts(&b, ",\"structuredContent\":");
1076+ buf_puts(&b, compact);
1077+ free(compact);
1078+ }
1079+ }
1080+ buf_puts(&b, "}");
1081+ out = dup_or_null(buf_str(&b));
1082+ buf_free(&b);
1083+ return out;
1084+}
1085+
1086+char *tool_api_result(tool_out_t *t)
1087+{
1088+ buf_t b;
1089+ char *out;
1090+
1091+ buf_init(&b);
1092+ if (t->is_error) {
1093+ buf_puts(&b, "{\"ok\":false,\"error\":");
1094+ json_str(&b, t->error ? t->error : "the tool could not be completed");
1095+ buf_puts(&b, "}");
1096+ out = dup_or_null(buf_str(&b));
1097+ buf_free(&b);
1098+ return out;
1099+ }
1100+ if (!t->md || !t->root || yyjson_mut_obj_size(t->root) == 0) {
1101+ buf_free(&b);
1102+ return dup_or_null("{\"ok\":true}");
1103+ }
1104+ {
1105+ /* The result object always begins with '{', so splicing ok in front
1106+ * of it is a byte-level operation on JSON this very document
1107+ * produced - one buffer, one write, no re-parsing (and no field
1108+ * reordering, which a half-buffer/half-printf builder causes). */
1109+ char *compact = yyjson_mut_write(t->md, 0, NULL);
1110+ if (!compact) {
1111+ buf_free(&b);
1112+ return dup_or_null("{\"ok\":false,\"error\":\"could not "
1113+ "serialise the result\"}");
1114+ }
1115+ buf_puts(&b, "{\"ok\":true");
1116+ if (compact[0] == '{' && compact[1] != '}') {
1117+ buf_putc(&b, ',');
1118+ buf_puts(&b, compact + 1); /* keeps the trailing '}' */
1119+ } else {
1120+ buf_puts(&b, "}");
1121+ }
1122+ free(compact);
1123+ }
1124+ out = dup_or_null(buf_str(&b));
1125+ buf_free(&b);
1126+ return out;
1127+}
src/ui.html+266−0■■■■■
1new file mode 1006441new file mode 100644
index 0000000..c300526index 0000000..c300526
--- /dev/null--- /dev/null
+++ b/src/ui.html+++ b/src/ui.html
@@ -0,0 +1,384 @@@@ -0,0 +1,384 @@
1+<!DOCTYPE html>
2+<html lang="en"><head><meta charset="utf-8">
3+<meta name="viewport" content="width=device-width,initial-scale=1">
4+<title>memory - knowledge graph</title>
5+<!--TOKENS-->
6+<style>
7+*{box-sizing:border-box}
8+html,body{margin:0;height:100%}
9+body{background:var(--bg);color:var(--text);font-family:var(--font);font-size:14px;
10+ line-height:1.5;-webkit-font-smoothing:antialiased;overflow:hidden}
11+#app{display:grid;grid-template-columns:320px minmax(0,1fr);height:100%;min-height:0}
12+.pane{min-width:0;min-height:0;display:flex;flex-direction:column}
13+#side{background:var(--bg-2);border-right:1px solid var(--line)}
14+.hd{display:flex;align-items:center;gap:8px;padding:11px 12px 9px}
15+.brand{font-size:12px;font-weight:700;letter-spacing:.09em;text-transform:uppercase;
16+ color:var(--text-2);flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
17+.icon{display:inline-flex;align-items:center;justify-content:center;background:var(--surface-2);
18+ border:1px solid var(--line);color:var(--text);border-radius:9px;width:30px;height:30px;
19+ padding:0;cursor:pointer;font-family:inherit;font-size:13px;font-weight:600;flex:none}
20+.icon:hover{background:var(--surface-hover);border-color:var(--line-2)}
21+.icon:active{transform:scale(.96)}
22+.icon svg{width:15px;height:15px;display:block;fill:none;stroke:currentColor;stroke-width:1.8;
23+ stroke-linecap:round;stroke-linejoin:round}
24+.search{margin:0 12px 8px;padding:8px 11px;border-radius:9px;border:1px solid var(--line);
25+ background:var(--input-bg);color:var(--text);font-family:inherit;font-size:13px;width:calc(100% - 24px)}
26+.search:focus{outline:2px solid var(--blue);outline-offset:-1px}
27+.chips{display:flex;flex-wrap:wrap;gap:5px;padding:0 12px 8px}
28+.chip{background:var(--surface-2);border:1px solid var(--line);color:var(--text-2);
29+ border-radius:980px;padding:2px 9px;font-size:11px;font-family:inherit;cursor:pointer;
30+ max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
31+.chip.on{background:var(--blue);border-color:var(--blue);color:#fff}
32+.list{flex:1 1 auto;overflow-y:auto;padding:0 8px 8px}
33+.item{display:block;width:100%;text-align:left;background:transparent;border:0;border-radius:10px;
34+ padding:8px 10px;color:var(--text);cursor:pointer;font-family:inherit;margin-bottom:2px}
35+.item:hover{background:var(--surface-hover)}
36+.item.sel{background:var(--surface-2);box-shadow:inset 2px 0 0 var(--blue)}
37+.irow{display:flex;align-items:baseline;gap:7px}
38+.iname{font-weight:600;flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
39+.icount{font-size:11px;color:var(--text-2);font-variant-numeric:tabular-nums;flex:none}
40+.itype{display:inline-block;margin-top:2px;font-size:10.5px;letter-spacing:.03em;text-transform:uppercase;
41+ color:var(--teal);background:var(--surface-2);border-radius:5px;padding:1px 6px;max-width:100%;
42+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
43+#main{overflow-y:auto}
44+.mainhd{display:flex;align-items:center;gap:8px;padding:11px 14px;border-bottom:1px solid var(--line);
45+ position:sticky;top:0;background:var(--bg);z-index:2;flex-wrap:wrap}
46+.title{font-size:15px;font-weight:700;flex:1;min-width:0;overflow-wrap:anywhere}
47+.btn{background:var(--blue);color:#fff;border:0;border-radius:980px;padding:6px 13px;font-weight:600;
48+ font-size:12.5px;cursor:pointer;font-family:inherit;white-space:nowrap}
49+.btn:active{transform:scale(.98)}
50+.btn.ghost{background:var(--surface-2);color:var(--text);border:1px solid var(--line)}
51+.btn.danger{background:transparent;color:var(--red);border:1px solid var(--line);padding:3px 9px;
52+ font-size:11.5px;font-weight:600}
53+.body{padding:14px;display:flex;flex-direction:column;gap:16px}
54+.card{background:var(--bg-card);border:1px solid var(--line);border-radius:14px;padding:13px 14px}
55+.card h3{margin:0 0 9px;font-size:11px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;
56+ color:var(--text-2)}
57+.obs{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
58+.obs li{display:flex;gap:9px;align-items:flex-start;background:var(--surface-2);border-radius:9px;
59+ padding:7px 10px;font-size:13px}
60+.obs li span{flex:1;min-width:0;overflow-wrap:anywhere}
61+.rel{display:flex;gap:9px;align-items:baseline;padding:6px 0;border-top:1px solid var(--line);font-size:13px}
62+.rel:first-of-type{border-top:0;padding-top:0}
63+.rel .arrow{color:var(--text-2);flex:none;font-size:12px}
64+.rel b{font-weight:600;overflow-wrap:anywhere}
65+.rel .rt{color:var(--orange);font-size:11.5px;font-weight:600;overflow-wrap:anywhere}
66+.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
67+input,select{background:var(--input-bg);border:1px solid var(--line);color:var(--text);
68+ border-radius:9px;padding:7px 10px;font-family:inherit;font-size:13px;min-width:0;flex:1 1 130px}
69+input:focus,select:focus{outline:2px solid var(--blue);outline-offset:-1px}
70+.hint{font-size:11.5px;color:var(--text-2);margin:0}
71+.empty{text-align:center;padding:56px 22px;color:var(--text-2)}
72+.empty b{display:block;color:var(--text);font-size:15px;margin-bottom:6px;font-weight:600}
73+.svgwrap{margin:0 auto 12px;width:74px;height:74px;opacity:.85}
74+.svgwrap svg{width:100%;height:100%;fill:none;stroke:var(--blue);stroke-width:1.6}
75+.status{font-size:11.5px;color:var(--text-2);padding:0 14px 12px;min-height:16px;overflow-wrap:anywhere}
76+.status.bad{color:var(--red)}
77+.status.ok{color:var(--green)}
78+.ft{border-top:1px solid var(--line);display:flex;align-items:center;gap:8px;padding:8px 12px;
79+ font-size:11px;color:var(--text-2)}
80+.ft .grow{flex:1}
81+.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0)}
82+@media (max-width:820px){
83+ #app{grid-template-columns:1fr}
84+ #side{border-right:0;border-bottom:1px solid var(--line);max-height:46vh}
85+ body[data-view="detail"] #side{display:none}
86+ body:not([data-view="detail"]) #main{display:none}
87+}
88+</style>
89+</head><body>
90+<div id="app">
91+ <section class="pane" id="side">
92+ <div class="hd">
93+ <span class="brand">knowledge graph</span>
94+ <button class="icon" id="btnTheme" title="Theme" aria-label="Toggle theme">
95+ <svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="4.2"/><path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M18.4 5.6L17 7M7 17l-1.4 1.4"/></svg>
96+ </button>
97+ </div>
98+ <input class="search" id="q" type="search" placeholder="Search names, types, observations" aria-label="Search the graph">
99+ <div class="chips" id="chips"></div>
100+ <div class="list" id="list"></div>
101+ <div class="ft">
102+ <span class="grow" id="tally">loading</span>
103+ <button class="icon" id="btnNew" title="New entity" aria-label="New entity">
104+ <svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>
105+ </button>
106+ </div>
107+ </section>
108+
109+ <section class="pane" id="main">
110+ <div class="mainhd">
111+ <button class="icon" id="btnBack" title="Back to list" aria-label="Back to list" style="display:none">
112+ <svg viewBox="0 0 24 24"><path d="M14 6l-6 6 6 6"/></svg>
113+ </button>
114+ <span class="title" id="title">Select an entity</span>
115+ <button class="btn ghost" id="btnReload" title="Reload">Reload</button>
116+ </div>
117+ <div id="detail" class="body"></div>
118+ <div class="status" id="status"></div>
119+ </section>
120+</div>
121+
122+<script>
123+(function(){
124+"use strict";
125+var q=new URLSearchParams(location.search);
126+var node=q.get('node')||'';
127+var pwd=q.get('pwd')||(node&&localStorage.getItem('bot_pwd_'+node))||
128+ localStorage.getItem('bot_active_pwd')||'';
129+/* Two ways to reach us: the bot's hub proxies /plugins?plugin=plugin_memory,
130+ * while a directly-opened node route is /plugin_memory. Hitting the wrong one
131+ * renders the plugin-LIST JSON instead of the page, so branch on the URL
132+ * rather than assuming the hub. */
133+var ROUTE=q.has('plugin')?'plugins':'plugin_memory';
134+
135+function url(action,extra){
136+ var p=[];
137+ if(q.has('plugin'))p.push('plugin=plugin_memory');
138+ p.push('action='+encodeURIComponent(action));
139+ if(node)p.push('node='+encodeURIComponent(node));
140+ if(pwd)p.push('pwd='+encodeURIComponent(pwd));
141+ if(extra)for(var k in extra)p.push(encodeURIComponent(k)+'='+encodeURIComponent(extra[k]));
142+ return '/'+ROUTE+'?'+p.join('&');
143+}
144+function hdr(x){var h={};for(var k in x)h[k]=x[k];if(pwd)h['X-Bot-Password']=pwd;return h;}
145+function api(action,extra){
146+ return fetch(url(action,extra),{headers:hdr({})}).then(function(r){
147+ if(!r.ok)throw new Error('HTTP '+r.status);
148+ return r.json();
149+ });
150+}
151+function post(action,obj){
152+ return fetch(url(action),{method:'POST',headers:hdr({'Content-Type':'application/json'}),
153+ body:JSON.stringify(obj)}).then(function(r){return r.json().then(function(j){j.__s=r.status;return j;});});
154+}
155+
156+var el=function(id){return document.getElementById(id);};
157+var listEl=el('list'),titleEl=el('title'),detailEl=el('detail'),statusEl=el('status'),
158+ tallyEl=el('tally'),chipsEl=el('chips'),qEl=el('q');
159+var entities=[],sel=null,typeFilter='',timer=null;
160+
161+function say(msg,cls){statusEl.textContent=msg||'';statusEl.className='status'+(cls?' '+cls:'');}
162+
163+function esc(s){return String(s==null?'':s).replace(/[&<>"']/g,function(c){
164+ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];});}
165+
166+function graphThen(fn){
167+ api('graph',{limit:'2000'}).then(function(j){
168+ if(j.ok===false){say(j.error,'bad');return;}
169+ entities=j.entities||[];
170+ fn&&fn();
171+ }).catch(function(e){say('could not read the graph: '+e.message,'bad');});
172+}
173+
174+function tally(){
175+ var n=0,i;
176+ for(i=0;i<entities.length;i++)n+=entities[i].observations.length;
177+ tallyEl.textContent=entities.length+' entities, '+n+' observations';
178+}
179+
180+function chips(){
181+ var seen={},out=[],i;
182+ for(i=0;i<entities.length;i++){var t=entities[i].entityType;if(!seen[t]){seen[t]=1;out.push(t);}}
183+ out.sort(function(a,b){return a.toLowerCase()<b.toLowerCase()?-1:1;});
184+ var h='<button class="chip'+(typeFilter===''?' on':'')+'" data-t="">all</button>';
185+ for(i=0;i<out.length&&i<40;i++)
186+ h+='<button class="chip'+(typeFilter===out[i]?' on':'')+'" data-t="'+esc(out[i])+'">'+esc(out[i])+'</button>';
187+ chipsEl.innerHTML=h;
188+ Array.prototype.forEach.call(chipsEl.querySelectorAll('.chip'),function(b){
189+ b.onclick=function(){typeFilter=b.getAttribute('data-t')||'';renderList();};
190+ });
191+}
192+
193+function renderList(){
194+ var term=(qEl.value||'').toLowerCase().trim(),rows=[],i,j,hit;
195+ for(i=0;i<entities.length;i++){
196+ var e=entities[i];
197+ if(typeFilter&&e.entityType!==typeFilter)continue;
198+ if(term){
199+ hit=e.name.toLowerCase().indexOf(term)>=0||
200+ e.entityType.toLowerCase().indexOf(term)>=0;
201+ for(j=0;!hit&&j<e.observations.length;j++)
202+ if(e.observations[j].toLowerCase().indexOf(term)>=0)hit=true;
203+ if(!hit)continue;
204+ }
205+ rows.push(e);
206+ }
207+ if(!rows.length){
208+ listEl.innerHTML='<div class="empty"><b>Nothing here</b>'+
209+ (entities.length?'No entity matches this filter.':'Add your first entity with the plus below.')+
210+ '</div>';
211+ chips();tally();return;
212+ }
213+ listEl.innerHTML=rows.map(function(e){
214+ return '<button class="item'+(sel&&sel===e.name?' sel':'')+'" data-n="'+esc(e.name)+'">'+
215+ '<span class="irow"><span class="iname">'+esc(e.name)+'</span>'+
216+ '<span class="icount">'+e.observations.length+'</span></span>'+
217+ '<span class="itype">'+esc(e.entityType)+'</span></button>';
218+ }).join('');
219+ Array.prototype.forEach.call(listEl.querySelectorAll('.item'),function(b){
220+ b.onclick=function(){open(b.getAttribute('data-n'));};
221+ });
222+ chips();tally();
223+}
224+
225+function relationRows(rels,dir){
226+ if(!rels.length)return '<p class="hint">None yet.</p>';
227+ return rels.map(function(r){
228+ var other=dir==='out'?r.to:r.from;
229+ return '<div class="rel"><b>'+esc(dir==='out'?r.from:r.to)+'</b>'+
230+ '<span class="arrow">'+(dir==='out'?'to':'from')+'</span>'+
231+ '<span class="rt">'+esc(r.relationType)+'</span>'+
232+ '<span style="flex:1"></span>'+
233+ '<button class="btn danger" data-delrel="'+esc(r.from)+'|'+esc(r.to)+'|'+esc(r.relationType)+'">remove</button>'+
234+ '</div>';
235+ }).join('');
236+}
237+
238+function open(name){
239+ sel=name;
240+ document.body.setAttribute('data-view','detail');
241+ el('btnBack').style.display='';
242+ renderList();
243+ api('entity',{name:name}).then(function(j){
244+ if(j.ok===false){say(j.error,'bad');return;}
245+ var ents=j.entities||[],rels=j.relations||[];
246+ if(!ents.length){titleEl.textContent=name;detailEl.innerHTML=
247+ '<div class="empty"><b>Gone</b>That entity is no longer in the graph.</div>';return;}
248+ var e=ents[0],i,out=[],inn=[];
249+ for(i=0;i<rels.length;i++){
250+ if(rels[i].from===e.name)out.push(rels[i]);
251+ if(rels[i].to===e.name)inn.push(rels[i]);
252+ }
253+ titleEl.textContent=e.name;
254+ detailEl.innerHTML=
255+ '<div class="card"><h3>'+esc(e.entityType)+'</h3><div class="row">'+
256+ '<button class="btn danger" data-dele="'+esc(e.name)+'">Delete entity</button>'+
257+ '<span class="hint">'+e.observations.length+' observation(s), '+rels.length+' relation(s)</span>'+
258+ '</div></div>'+
259+ '<div class="card"><h3>Observations</h3><ul class="obs">'+
260+ (e.observations.length?e.observations.map(function(o){
261+ return '<li><span>'+esc(o)+'</span><button class="btn danger" data-delo="'+
262+ esc(e.name)+'|'+esc(o)+'">remove</button></li>';}).join('')
263+ :'<li><span class="hint">No observations yet.</span></li>')+
264+ '</ul><div class="row" style="margin-top:10px">'+
265+ '<input id="newObs" placeholder="Add an observation" aria-label="New observation">'+
266+ '<button class="btn" id="addObs">Add</button></