Repository navigation
Memory: a dependency-free embedding tier, embedder identity, and memory_write - #600
Conversation
Two gaps, and one latent bug that had to be fixed before either could land safely. Static embedding tier. The ONNX embedder costs a ~90 MB model download AND a native runtime, and until `pasclaw memory provision` has run the fact store has no semantic layer at all: no vector column, keyword-only retrieval, and rows that stay unembedded until provisioning happens. PasClaw.Memory.Embed.Static fills that with feature hashing over word unigrams and character 4-grams -- no model, no vocabulary, no runtime. EnableBestFactEmbedder picks ONNX when it loads and this otherwise, and is now wired into the MCP stdio entrypoint as well as agent, TUI and gateway. It is lexical, not semantic, and the code says so in those words. It buys typo and inflection tolerance that BM25 with a Porter stemmer does not, and a second rank for the hybrid fusion from the first turn. It does not know that "car" and "automobile" are related, and a test asserts they score apart so the claim cannot quietly drift. Because a lexical score is a poor basis for an irreversible merge, the tier registers with semantic dedup disabled: it ranks, it never merges. Embedder identity. The facts table stored a vector with no record of which model produced it. CosineSim returns 0 on a length mismatch, so a model switch silently made every existing fact invisible to semantic search -- and two embedders sharing a dimension would have produced confidently wrong rankings with no guard at all, which adding a second tier would have triggered immediately. Vectors now carry a '<name>@<dim>' id, every comparison filters on it, and BackfillEmbeddings re-embeds rows stranded by a switch instead of leaving them dead. SetFactEmbedder refuses an embedder that cannot be named. memory_write. The MCP server already lets another agent READ this memory -- memory_search is tcReadOnly and fuses notes with the fact store -- but nothing could write to it except auto-distillation and a human at `pasclaw memory add`. memory_write closes that: a curated fact, with its declared origin recorded for audit. It is tcMutating, so plan mode refuses it and MCP exposes it only under --mcp-allow-write; a foreign host writing the operator's memory is a decision, not a default. Its fields are validated strictly rather than passed through the distiller's NormaliseFact, which silently turns an unparseable expiry into "never expires" -- right when salvaging a model's JSON, wrong when a caller needs to learn its write was not what it asked for. Verified: the new suite is wired into `make test` and confirmed with `make -n test`, and its gate assertions were negative-tested -- removing the identity filter fails the backfill case, removing the dedup opt-out fails the merge case. End to end, two clients wrote facts through MCP against a home with nothing provisioned and read them back, with vectors stored as hash-ngram-v1@256. One change is unverified here and is called out rather than implied: created_at now passes DateTimeToUnix(Now, False) to match every other fact writer, but this container's FPC returns UTC from Now regardless of TZ, so the difference cannot be reproduced on it. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
The previous commit shipped a test-sqlite-hint failure. That guard exists to catch a tool call site reaching for the bare platform hint instead of SqliteOpenFailureReason(...LastError) -- it was added after exactly this mistake shipped twice on PR #582 -- and it caught this one. The comment justifying the shortcut said IFactStore had no LastError accessor and so no driver detail to report. That was a rationalisation of a gap rather than a reason: IMemoryIndex has had one for as long as it has had a failure path. IFactStore now has the same thing, captured in Open's exception handler and cleared on entry, and memory_write reports through SqliteOpenFailureReason like every other call site. Verified against a corrupt database rather than an unwritable one -- these tests run as root, so chmod proves nothing and the write succeeds anyway. With 4 KB of random bytes at the store path the tool now answers: cannot open the fact store at .../facts.db (TSQLite3Connection : file is not a database) which is the driver's own message, not a guess. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
Testing the static tier end to end with a relay operator turned up that its headline benefit does not hold as documented. memory_search for "relaese chekclist" returns no matches, despite the fact "The release checklist lives at docs/release.md..." being in the store with a vector. Measured cosines against that fact: exact words 0.5569 retrieved one word of two misspelled 0.4229 retrieved BOTH words misspelled 0.1754 dropped unrelated topic (noise) 0.1000 RankFactsBySemantic gates on MinCosine = 0.30, tuned for MiniLM. A fully misspelled short query clears noise but not that gate. The test that claimed otherwise was too easy. It compared "deployment configuration" with "deploymnet configuration" and asserted > 0.7 -- true, but only because the second word matched exactly, so it measured a shared word rather than the typo tolerance it was named for. It is replaced with the three real cases, pinning the limitation as an assertion so the claim cannot drift back. The docs now state what the tier does and does not do, with the numbers. No threshold is changed here: the signal-to-noise margin is real but thin (0.18 vs 0.10), and choosing a per-tier constant off one example pair would be tuning on a sample of one. The principled fix is a scorer suited to short-query/long-document matching, since cosine between L2-normalised bags systematically under-scores a short query -- that is its own piece of work. Everything else the tier claims still holds and was verified through the relay: memory_write reaches the agent's tool registry (18 tools vs main's 17, the delta being exactly this tool), a fact written in one session is stored with a hash-ngram-v1@256 vector on a host with nothing provisioned, and it is injected into a fresh session's system prompt. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c67e56a817
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| 'VALUES (:t, :k, :sc, :cf, :ev, :ex, :ss, :ca, 0, :emb)'; | ||
| 'source_session, created_at, superseded, embedding, embed_model) ' + | ||
| 'VALUES (:t, :k, :sc, :cf, :ev, :ex, :ss, :ca, 0, :emb, :em)'; | ||
| PStr (Q, 'em', GFactEmbedId); |
There was a problem hiding this comment.
Keep each embedding paired with its producing model ID
When a gateway starts on the static tier and provisioning later causes a concurrent /v1/embeddings request to activate ONNX, Add can compute EmbHex through the old function and then read the newly changed GFactEmbedId here. The row is consequently labeled minilm@384 while containing a 256-dimensional static vector; cosine scoring rejects it, and later backfills skip it because its nonempty model ID already matches the active ID. Snapshot the function, ID, and dedup flag atomically for each operation, or synchronize all reads with SetFactEmbedder.
Useful? React with 👍 / 👎.
| for i := 1 to 10 do | ||
| if (i <> 5) and (i <> 8) and ((S[i] < '0') or (S[i] > '9')) then Exit; | ||
| Result := True; |
There was a problem hiding this comment.
Validate that supplied dates exist
For memory_write calls using values such as expires="2026-99-99" or event_date="2026-02-31", this function returns true because it checks only punctuation and digits. The invalid expiry is then compared lexicographically by ActiveFacts and may remain active indefinitely, while the invalid event can never be surfaced by the existing TryEncodeDate path, even though the caller is told the write succeeded. Parse the components and use TryEncodeDate, as the fact-store date helpers already do.
Useful? React with 👍 / 👎.
| T.Handler := Tool_MemoryWrite; | ||
| T.IsCore := True; | ||
| { Mutating: it changes durable state the user owns. That is what makes | ||
| plan mode refuse it and keeps it off the MCP surface unless the | ||
| operator passed --mcp-allow-write. } | ||
| T.Category := tcMutating; | ||
| R.Register(T); |
There was a problem hiding this comment.
Initialize the fallback in every memory-tool host
Registering memory_write through this shared procedure does not ensure that an embedder is active. I checked the pasclaw serve registry (PasClaw.Cmd.Serve.pas) and the heartbeat/embedded-agent registry paths: they call RegisterMemoryTools but never call EnableBestFactEmbedder, unlike the CLI agent, TUI, gateway, and MCP stdio paths changed here. In those contexts newly written facts retain empty vectors and memory_search remains keyword-only even when distilled memory is enabled, contradicting the always-available tier; initialize the embedder in those entrypoints or lazily before fact reads/writes.
Useful? React with 👍 / 👎.
| for i := 1 to Length(S) do | ||
| begin | ||
| Result := Result xor LongWord(Byte(S[i])); | ||
| Result := Result * Prime; |
There was a problem hiding this comment.
Hash a canonical byte encoding across Pascal targets
For non-ASCII text, this hashes different data on the supported compilers: FPC's string here contains UTF-8 bytes, whereas modern Delphi's string is UTF-16 and Byte(S[i]) truncates each code unit. A facts database written by one target and later opened by the other therefore contains incompatible vectors carrying the same hash-ngram-v1@256 identity, defeating the new model-space guard and producing incorrect similarities. Convert normalized text to an explicitly defined encoding such as UTF-8 before hashing, or use target-specific embedder IDs.
Useful? React with 👍 / 👎.
…e hashing Four P2 findings from the Codex review, all legitimate, one only partly. 1. Snapshot the embedder atomically. Add() read GFactEmbed to produce a vector and GFactEmbedId to label it as two separate global reads. Provisioning can swap the tier between them, and the row then claims an id from a different space. That row is also unrecoverable: its id matches the active one, so BackfillEmbeddings skips it. The three globals now sit behind a critical section, and FactEmbedderSnapshot hands out (fn, id, dedup) as one triple. Add, SearchActiveFacts and BackfillEmbeddings each take one snapshot and use only that; no direct global reads remain. 2. Validate that a supplied date exists. The shape check accepted 2026-99-99 and 2026-02-31. Expiry is compared lexicographically, so an impossible date sorts above every real one and the fact never expires -- while the caller is told the write succeeded. TryParseISODate already existed in Facts; it is now exported as IsValidISODateOrEmpty and used at the tool boundary. 3. Activate the embedder where it is needed, not per entrypoint. The review's claim about `pasclaw serve` is wrong -- serve and gateway share TGatewayServer, which already calls EnableBestFactEmbedder -- but PasClaw.Agent, Cmd.Heartbeat and the PasClaw.Tools bundle do register the memory tools without it, and facts written there got no vector. Adding a fourth call site only defers the next omission, so the store now asks once, lazily, through an injectable hook that PasClaw.Memory.Facts.Embed installs from its initialization. The dependency still points away from the ONNX stack, and a build that does not link that unit behaves exactly as before. 4. Hash a canonical byte encoding. FPC's string here is UTF-8, Delphi's is UTF-16, so hashing Byte(S[i]) hashed different data per target for non-ASCII text -- and truncated each UTF-16 unit -- while both rows claimed the same embedder id. That defeats the very guard this branch adds. Hashing now runs on TEncoding.UTF8.GetBytes, with the word/gram distinction folded into the hash seed instead of a character-typed prefix. The space changed, so the id is bumped to hash-ngram-v2@256 and v1 rows are never compared against it -- the identity mechanism doing its job. Verified: impossible dates rejected and a real leap day accepted through MCP; a probe that registers nothing shows no embedder before a write and hash-ngram-v2@256 with 256 dims after it. Two new tests cover the lazy hook and date validity, plus a pinned non-ASCII fingerprint that fails on whichever target regresses the encoding path. Both new guards were negative-tested: removing the hook call fails the vector assertion, weakening the date check fails on non-leap Feb 29. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
All five sites the version-sync lint pins, so a partial bump cannot pass: VersionFallback, the .dproj FileVersion and ProductVersion strings, the structured Release field Delphi writes into VS_FIXEDFILEINFO, and the installer default. The structured field is the one that matters most and is easiest to miss. Delphi puts it in the binary's fixed version block, which is what Windows Explorer, installer upgrade comparisons and inventory tooling read -- the FileVersion string can say one thing while the fixed block says another. Verified by reverting just that field, which fails lint-version with exactly that explanation. Changelog entry for FMXExpress#600 in both mirrors (docs/changelog.md and the README section), under a new 2026-09 heading, with the reference-link definition the entry cites. Note for whoever cuts the release: lint-version reports "no tags reachable" here, so its behind-the-newest-tag check -- the drift that shipped 0.1.0-dev through three releases -- is currently inert. It needs a clone with tags in history (fetch-depth: 0 in CI) to do the job it exists for. The cross-site checks run either way. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6
Two additions to the memory layer, plus one latent bug the first of them would have detonated.
Prompted by a look at Engrim. Most of what that project advertises PasClaw already has — SQLite, FTS5, hybrid RRF, typed records, supersede-not-delete, provenance, budgeted injection — so this takes only the two ideas that were genuinely missing.
1. A vector column that does not wait for a 90 MB download
PasClaw.Memory.Embed.Static— feature hashing over word unigrams and character 4-grams, signed accumulation, sublinear damping, L2 normalise. No model file, no vocabulary, no native runtime.EnableBestFactEmbedderprefers the ONNX embedder and falls back to this, so a host that has never runpasclaw memory provisionstill gets a vector column instead of keyword-only retrieval and a table of unembedded rows.What it is not: semantic.
carandautomobilescore near zero, and there is a test asserting exactly that, because a static hash has never read a corpus. It buys partial-misspelling and inflection tolerance, and a second rank for the hybrid RRF path to fuse.It registers with semantic dedup disabled. Merging two facts is irreversible, and two genuinely different facts sharing vocabulary can clear a 0.85 lexical score far more easily than they can a real encoder's. It ranks; it never merges. Exact-text dedup is untouched.
2.
memory_writememory_searchhas always let another agent read PasClaw's memory — the MCP server exposes it, and it fuses the markdown notes with the fact store. Nothing could write.pasclaw memory addcovers a human at the CLI, but no tool existed, so neither the model nor an MCP client could record a decision.memory_writeistcMutating, so plan mode refuses it and the MCP server exposes it only under--mcp-allow-write. Both gates verified. Each fact records a declared origin (written:<source>) for audit — a label, not authentication, and the docs say so.Validation rejects a malformed date rather than coercing it.
NormaliseFactis deliberately not reused: silently turningexpires: "tomorrow"into "never expires" is right for a distiller parsing model output and wrong for a tool, where the caller should get an error.3. The bug this uncovered
The
factstable storedembedding TEXTwith no record of which model produced it.CosineSimguards on length, so a dimension change degraded quietly — but two embedders sharing a dimension would have produced silently wrong rankings with no guard at all. Adding a second tier makes that reachable.Every vector now carries
embed_modelas<name>@<dim>; comparisons filter on it first;BackfillEmbeddingsre-embeds rows stranded by a model switch; an embedder registered without an id is refused outright.Verification
Full suite green (
SUITE-EXIT=0, 38 suites, 0 make errors), with the newtest-memory-static-embedwired into the aggregate and confirmed viamake -n test.Negative-tested: disabling the identity filters fails the backfill assertion; disabling the dedup gate fails the merge assertion; restoring returns green.
End-to-end through a relay operator:
memory_writereaches the agent's tool registry (18 tools against main's 17, the delta being exactly this tool), a fact written in one session is stored with ahash-ngram-v1@256vector on a host with nothing provisioned, and it is injected into a fresh session's system prompt.A limitation this found, stated plainly
That relay test also showed the typo-tolerance claim did not hold as first written.
memory_search("relaese chekclist")returns nothing, despite the fact it names being in the store:RankFactsBySemanticgates onMinCosine = 0.30, tuned for MiniLM. The test that claimed otherwise compared"deployment configuration"with"deploymnet configuration"and asserted> 0.7— true, but only because the second word matched exactly, so it measured a shared word rather than the tolerance it was named for. Replaced with the three real cases, pinned as assertions so the claim cannot drift back.No threshold is changed here. The signal-to-noise margin is real but thin (0.18 vs 0.10), and picking a per-tier constant off one example pair is tuning on a sample of one. The principled fix is a scorer suited to short-query/long-document matching — cosine between L2-normalised bags systematically under-scores a short query — and that is its own piece of work.
Reviewer notes
f7b9b03fixes a lint failureb5036f7shipped. My first attempt at an honest "cannot open the store" message reached for the bare platform hint, whichtest-sqlite-hintforbids — a guard added after Codex flagged the same thing on Report why a SQLite index failed to open, not a guess #582, and it caught this.IFactStorenow has aLastErrormirroringIMemoryIndex, so the message carries the driver's real reason (verified against a corrupt database:TSQLite3Connection : file is not a database).🤖 Generated with Claude Code
https://claude.ai/code/session_01LGQKz579j1ZnDRwmr6h1V6