memoryd: Erinnerungen mit Bedeutungssuche, als MCP-Dienst wie tasksd und skilld

Ein Fakt je Datei, ein Embedding je Fakt, Suche über Vektornähe statt Volltext. Sieben
Werkzeuge: add, search, list, get, update, delete, scopes. Ablage sind JSON-Dateien unter
$MEMORYDIR (Standard ~/.hermes/memories), lesbar und sicherbar ohne Datenbank; ein
Scope wählt sich selbst und seine Kinder (van deckt van/technik), wie bei tasksd.

Der Embedder ist OpenAI-kompatibel (EMBED_URL, Standard http://127.0.0.1:8091/v1/embeddings,
EMBED_MODEL nomic-embed-text, 768 Dimensionen) — und ausdrücklich nicht nötig: antwortet er
nicht, wird ohne Vektor gespeichert, das Werkzeug sagt es (WITHOUT embedding) und die Suche
fällt auf Teilstrings zurück, ebenfalls benannt. Ein Speicher, der Bedeutung behauptet, wo
er Buchstaben vergleicht, wäre schlimmer als einer, der es zugibt.

Drei Fehler, die auf dem Weg dorthin Zeit gekostet haben und jetzt im Code stehen:
popen kennt nur eine Richtung ("r+" ist undefiniert, die Schreibseite verschwindet) — der
Rumpf geht über eine temporäre Datei an curl. Diese Datei liegt im Speicherverzeichnis,
nicht in /tmp: die Einheit läuft mit ProtectSystem=strict, dort ist /tmp schreibgeschützt,
und ein Embedder, der an mkstemp scheitert, sieht wie ein toter Embedder aus. Und die
Bind-Adresse wird aus "--http host:port" übernommen, sonst hörte der Dienst trotz
127.0.0.1 in der Einheit auf allen Adressen.

Tests: 16 Prüfungen gegen den laufenden Dienst (HTTP-Transport mit Sitzung), mit einem
deterministischen Embedder-Stub — die Suite hängt nicht davon ab, ob hier gerade ein
Modell geladen ist. Geprüft werden unter anderem: sieben Werkzeuge, Reihenfolge nach Nähe,
Scope-Vererbung, Re-Embedding beim Ändern, der gespeicherte Vektor auf der Platte, das
Verhalten ohne Embedder und dass eine gelöschte Erinnerung wirklich weg ist.

Auf n95 installiert: memoryd.service auf 127.0.0.1:8795, MEMORYDIR=/var/lib/memoryd,
in junction als MCP-Server eingetragen (27 Werkzeuge über :8090/mcp, memoryd__memory_search
liefert über junction einen Treffer mit score 0.69).
This commit is contained in:
Hermes Agent committed 2026-11-08 16:53:05 +00:00
commit 5108636d84
8 files changed
+2556

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
memoryd
*.o
+21
View File
@@ -0,0 +1,21 @@
CC ?= cc
CFLAGS ?= -std=c99 -O2 -Wall -Wextra -Werror
LIBDIR ?= vendor/libmcp
PREFIX ?= /usr/local
all: memoryd
memoryd: memoryd.c $(LIBDIR)/mcp.h
$(CC) $(CFLAGS) -I$(LIBDIR) -o $@ memoryd.c -lm
test: memoryd
./tests/run.sh
install: memoryd
mkdir -p $(DESTDIR)$(PREFIX)/bin
cp memoryd $(DESTDIR)$(PREFIX)/bin/
clean:
rm -f memoryd
.PHONY: all test install clean
+73
View File
@@ -0,0 +1,73 @@
# memoryd
What an agent remembered, searchable by meaning.
One fact per file, one embedding per fact, and a search that answers "how was it with the
frost protection" with the note that says "coolant down to -25 °C" — even though the word
frost never appears in it. Served over MCP, like `tasksd` and `skilld`.
```sh
memoryd # stdio, JSON-RPC per line
memoryd --http 8795 # Streamable HTTP, so every host uses the same store
```
## Storage
One JSON file per memory under `$MEMORYDIR` (default `~/.hermes/memories`):
```json
{
"id": "m00001",
"scope": "van/technik",
"text": "Der Frostschutz steht auf -25 Grad, aufgefüllt wird G12+ blau.",
"tags": "kühlmittel",
"source": "konrad",
"model": "nomic-embed-text",
"created": 1794147600,
"embedding": [0.0428, 0.0418, ...]
}
```
Readable, diffable, backupable without a database. A `scope` is a free string and selects
itself plus its children, so `van` covers `van/technik` — the same rule as tasksd.
## Tools
| tool | what it is for |
|---|---|
| `memory_add` | store one fact: text (required), scope, tags, source |
| `memory_search` | meaning-based search with scores; scope and limit optional |
| `memory_list` | what exists in a scope, newest first |
| `memory_get` | one memory in full |
| `memory_update` | correct a fact (re-embeds the new text) |
| `memory_delete` | remove what is wrong or obsolete |
| `memory_scopes` | which scopes exist, how many memories each |
## The embedder
OpenAI-compatible `/v1/embeddings`, `EMBED_URL` (default
`http://127.0.0.1:8091/v1/embeddings`), `EMBED_MODEL` (default `nomic-embed-text`, 768
dimensions).
**It is not required to run.** If it does not answer, the memory is stored without a
vector and the tool says so (`WITHOUT embedding`); search then falls back to a
case-insensitive substring match and labels the result `substring match`. A store that
silently pretends to understand meaning is worse than one that admits it is matching
letters.
## What does not belong here
Secrets, keys, passwords, long transcripts. The text is the conclusion, not the raw
material — one paragraph that still makes sense to an agent who was not there. A store
that keeps everything makes every search worse.
## Build and test
```sh
make # C99 + POSIX, no dependency beyond libc, libm, and curl at runtime
make test # 16 checks against the running service (HTTP + stdio), stub embedder
sudo make install
```
The suite starts its own embedder stub with deterministic vectors, so it does not depend
on a model being loaded on this machine.
+1019
View File
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
[Unit]
Description=memoryd — was ein Agent sich gemerkt hat, mit Bedeutungssuche (MCP über HTTP)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=lotherk
Group=lotherk
Environment=MEMORYDIR=/var/lib/memoryd
# Der Embedder läuft auf demselben Rechner; steht er woanders, hier eintragen.
Environment=EMBED_URL=http://127.0.0.1:8091/v1/embeddings
Environment=EMBED_MODEL=nomic-embed-text
ExecStart=/usr/local/bin/memoryd --http 127.0.0.1:8795
Restart=always
RestartSec=3
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=/var/lib/memoryd
NoNewPrivileges=yes
[Install]
WantedBy=multi-user.target
+261
View File
@@ -0,0 +1,261 @@
#!/usr/bin/env python3
"""memoryd — Prüfungen gegen den laufenden Dienst, nicht gegen die Funktion.
Der Embedder wird durch einen Stub ersetzt: die Suite soll nicht davon abhängen, ob auf
diesem Rechner gerade ein Modell im Speicher liegt. Der Stub liefert deterministische
Vektoren (Zählung von Buchstabengruppen), damit Nähe berechenbar und die Reihenfolge
prüfbar ist. Ob nomic-embed-text Bedeutung gut trifft, ist eine andere Frage als die,
ob memoryd Vektoren richtig schreibt, liest und sortiert.
"""
import http.server
import json
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import threading
import time
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
BIN = os.path.join(os.path.dirname(HERE), "memoryd")
FAILED = []
def ok(msg):
print(" OK %s" % msg)
def bad(msg):
print(" FAIL %s" % msg)
FAILED.append(msg)
def free_port():
s = socket.socket()
s.bind(("127.0.0.1", 0))
p = s.getsockname()[1]
s.close()
return p
class EmbedStub(http.server.BaseHTTPRequestHandler):
"""Zählt Buchstaben in 32 Eimern — ähnliche Wörter, ähnliche Vektoren."""
def log_message(self, format, *args): # noqa: A002 - Signatur der Basisklasse
pass
def do_POST(self):
n = int(self.headers.get("Content-Length", "0"))
body = json.loads(self.rfile.read(n) or b"{}")
text = (body.get("input") or "").lower()
vec = [0.0] * 32
for ch in text:
if ch.isalpha():
vec[ord(ch) % 32] += 1.0
norm = sum(v * v for v in vec) ** 0.5 or 1.0
vec = [round(v / norm, 6) for v in vec]
out = json.dumps({"data": [{"embedding": vec, "index": 0}],
"model": body.get("model", "stub")}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(out)))
self.end_headers()
self.wfile.write(out)
class Mcp:
"""Minimaler MCP-Client über Streamable HTTP (JSON-RPC 2.0 auf POST)."""
def __init__(self, port):
self.url = "http://127.0.0.1:%d/mcp" % port
self.sid = None
self.n = 0
def _post(self, payload):
data = json.dumps(payload).encode()
h = {"Content-Type": "application/json",
"Accept": "application/json, text/event-stream"}
if self.sid:
h["Mcp-Session-Id"] = self.sid
req = urllib.request.Request(self.url, data=data, headers=h)
with urllib.request.urlopen(req, timeout=30) as r:
self.sid = r.headers.get("Mcp-Session-Id", self.sid)
raw = r.read().decode()
if not raw.strip():
return {}
# Streamable HTTP: entweder reines JSON oder SSE-Zeilen
for line in raw.splitlines():
if line.startswith("data:"):
return json.loads(line[5:].strip())
return json.loads(raw)
def call(self, method, params=None):
self.n += 1
return self._post({"jsonrpc": "2.0", "id": self.n, "method": method,
"params": params or {}})
def tool(self, name, **args):
r = self.call("tools/call", {"name": name, "arguments": args})
res = r.get("result", {})
content = res.get("content") or []
text = content[0].get("text", "") if content else json.dumps(res)
return text, bool(res.get("isError"))
def wait_port(port, limit=10.0):
end = time.time() + limit
while time.time() < end:
try:
with socket.create_connection(("127.0.0.1", port), timeout=0.3):
return True
except OSError:
time.sleep(0.05)
return False
def main():
work = tempfile.mkdtemp(prefix="memoryd-test-")
eport, mport = free_port(), free_port()
stub = http.server.HTTPServer(("127.0.0.1", eport), EmbedStub)
threading.Thread(target=stub.serve_forever, daemon=True).start()
env = dict(os.environ)
env["MEMORYDIR"] = os.path.join(work, "memories")
env["EMBED_URL"] = "http://127.0.0.1:%d/v1/embeddings" % eport
env["EMBED_MODEL"] = "stub"
srv = subprocess.Popen([BIN, "--http", "127.0.0.1:%d" % mport],
env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
try:
if not wait_port(mport):
print(srv.stdout.read().decode()[:400] if srv.stdout else "")
bad("memoryd did not come up")
return 1
c = Mcp(mport)
init = c.call("initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
"clientInfo": {"name": "test", "version": "0"}})
if init.get("result", {}).get("serverInfo", {}).get("name") == "memoryd":
ok("initialize answers with the server name")
else:
bad("initialize did not name the server: %s" % json.dumps(init)[:120])
tools = c.call("tools/list").get("result", {}).get("tools", [])
names = sorted(t["name"] for t in tools)
want = ["memory_add", "memory_delete", "memory_get", "memory_list",
"memory_scopes", "memory_search", "memory_update"]
if names == want:
ok("seven tools, the expected ones")
else:
bad("tools are %s" % names)
t, err = c.tool("memory_add", text="Der Frostschutz steht auf -25 Grad.",
scope="van/technik", tags="kühlmittel", source="konrad")
if not err and "embedded" in t and "m00001" in t:
ok("a memory is stored and embedded (768 → 32 dims in the stub)")
else:
bad("memory_add said: %s" % t)
t, err = c.tool("memory_add", text="Der Frostschutz steht auf -25 Grad, G12+ blau.")
if not err:
ok("a second memory lands in the default scope")
else:
bad("second add failed: %s" % t)
t, err = c.tool("memory_search", query="frostschutz grad", limit=2)
if not err and "score=" in t and "m00001" in t:
ok("search returns scored hits from the vector path")
top = t.splitlines()[0]
if "m00001" in t.split("m00002")[0]:
ok("the closer memory ranks first (%s)" % top.strip())
else:
bad("ranking looks wrong: %s" % top.strip())
else:
bad("search said: %s" % t[:200])
t, err = c.tool("memory_search", query="frostschutz", scope="van")
if not err and "m00001" in t:
ok("a scope selects itself and its children (van → van/technik)")
else:
bad("scope filter: %s" % t[:160])
t, err = c.tool("memory_list", limit=5)
if not err and t.count("m0000") == 2:
ok("memory_list shows both, newest first")
else:
bad("memory_list: %s" % t[:160])
t, err = c.tool("memory_get", id="m00001")
if not err and "-25 Grad" in t:
ok("memory_get returns the text")
else:
bad("memory_get: %s" % t[:160])
t, err = c.tool("memory_update", id="m00001", text="Der Frostschutz steht auf -30 Grad.")
if not err and "embedding: yes" in t:
ok("memory_update re-embeds the new text")
else:
bad("memory_update: %s" % t[:160])
path = os.path.join(env["MEMORYDIR"], "m00001.json")
raw = open(path).read() if os.path.exists(path) else ""
if '"embedding"' in raw and "-30 Grad" in raw:
ok("the file on disk carries the vector and the new text")
else:
bad("the stored file looks wrong: %s" % raw[:120])
t, err = c.tool("memory_scopes")
if not err and "van/technik" in t and "general" in t:
ok("memory_scopes counts both scopes")
else:
bad("memory_scopes: %s" % t[:160])
# Ohne Embedder: speichern geht weiter, die Suche sagt, was sie tut.
stub.shutdown()
t, err = c.tool("memory_add", text="Die Pumpe läuft seit März leise.", scope="van/technik")
if not err and "WITHOUT embedding" in t:
ok("a dead embedder is reported, not hidden")
else:
bad("storing without an embedder: %s" % t[:160])
t, err = c.tool("memory_search", query="pumpe")
if not err and "substring match" in t and "Pumpe" in t:
ok("search falls back to substrings and says so")
else:
bad("fallback search: %s" % t[:200])
t, err = c.tool("memory_delete", id="m00002")
if not err and "deleted" in t and not os.path.exists(
os.path.join(env["MEMORYDIR"], "m00002.json")):
ok("memory_delete removes the file")
else:
bad("memory_delete: %s" % t[:160])
t, err = c.tool("memory_get", id="m00002")
if err:
ok("a deleted memory is really gone")
else:
bad("memory_get still returns the deleted memory")
finally:
srv.terminate()
try:
srv.wait(timeout=5)
except subprocess.TimeoutExpired:
srv.kill()
stub.shutdown()
shutil.rmtree(work, ignore_errors=True)
print()
if FAILED:
print("FAILURES: %d" % len(FAILED))
return 1
print("PASS")
return 0
if __name__ == "__main__":
sys.exit(main())
Executable
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# memoryd-Prüfungen. Braucht python3 (HTTP-Client), keinen laufenden Embedder:
# der Stub in run.py ist deterministisch.
set -eu
cd "$(dirname "$0")/.."
[ -x memoryd ] || make -s
exec python3 tests/run.py
+1150
View File
File diff suppressed because it is too large. Load diff