Repository navigation
memagent: Free Pascal agent with RAG short-term memory and hot-swapped LoRA long-term memory - #1
Merged
Merged
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…cess Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…RA long-term memory - memagent/ (Free Pascal): agent loop, SQLite FTS5 memory store, fact bookkeeping, background consolidation scheduling, adapter hot swap, rollback, /ab demo command - trainer/ (Python): long-lived inference worker over JSON lines and a one-shot consolidation trainer with recall + held-out drift eval gate - models.json: tiny (SmolLM2-135M, CPU) through large (Magistral 24B) profiles selected from memagent.ini - tests: Python unit/protocol tests and an end-to-end script that drives the real binary through two consolidations, forget and rollback Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
- Mem.Retrieval: MiniLM sentence embeddings + ms-marco cross-encoder reranker in-process via ONNX Runtime, with the lexical static embedder as a zero-download fallback; units brought in from PasClaw's localvector/memory code as Mem.Onnx*, Mem.Embed.*, Mem.Tokenizer, Mem.SentencePiece, Mem.Rerank.Onnx - Hybrid RAG: FTS5 + cosine fused by reciprocal rank, then reranked; facts and user messages embedded on write, backfilled on startup - Same-subject detection for corrections: cosine shortlist confirmed by the cross-encoder (cosine alone ranks sister/brother above a real paraphrase) - Mem.Https: verifying TLS handler (chain + hostname), HTTPS_PROXY CONNECT tunnelling and OpenSSL 3 loading, which FPC 3.2.2's stock handler lacks; memagent --provision downloads runtime + models - /recall command, retrieval_test.lpr, e2e semantic recall assertions Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
… tests Found by testing from a fresh clone (tiny profile + Qwen2.5-1.5B on CPU): - Restart re-promoted an adapter the user had rolled back from (stale ready.json); ready.json is now cleared once handled - Non-ASCII text was stored as Latin-1 (FPC 3.2.2 CP_ACP strings): Mem.Utf8 + cwstring make UTF-8 the process codepage - LLM fact extraction dropped pretty-printed JSON and accepted invented values; values must now occur in the user's own words - Tool calls: accept bare JSON without <tool> tags, tolerate missing args, and report what remember actually stored - Same fact from the user message and a tool call was stored twice; user-message facts now go first and repeats are skipped - Facts are embedded/reranked as 'subject: text' (relation recall) - Summary prompt moved to a system turn (small models echoed it) - small profile: gradient checkpointing (CPU OOM at 14 GB -> 8.7 GB peak) and 4 epochs / lr 3e-4 (old defaults failed the drift gate) - Mem.Https honours NO_PROXY Tests: scripts/https_test.sh (trusted/untrusted CA, wrong host, expired, plain http), scripts/resilience_test.sh, scripts/profile_smoke.sh, LLM-extraction parsing unit tests, UTF-8 assertions in the e2e. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…s, extractor fixes, batched rerank - bench/: dev and held-out fact sets, bench_memory.py (base / RAG / LoRA / LoRA+RAG accuracy, interference, confabulation incl. near-miss memory), bench_retrieval.lpr (hit@k, MRR, noise, latency, threshold sweep, scale) - Mem.Recall: retrieval pipeline shared by the agent and the benchmarks, with per-stage timing; MEMAGENT_TIMING=1 prints per-turn stage times - Rule extractor: value accuracy 0.77 -> 1.00 (leading function words, 'is called X', no sentence split after Dr./Mr.) - Batched cross-encoder scoring for float rerankers (identical scores); int8 models stay per-pair (batch-dependent dynamic quantization) - rag_include_baked=1: LoRA+RAG 0.93 vs LoRA 0.78 on the dev set - Trainer: optional name questions / abstention negatives / RAFT examples (measured; off by default), --no-gate for benchmarks Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…ed retrieval
Profile:
- search was 1.2 s/query at 2,500 messages: unindexed correlated subquery
on facts.source_msg (gprof: ~0.5 s in our code, the rest in SQLite);
index + top-k selection -> 8 ms; 65 ms/query total at 12k rows
- small profile first token 7.9 s avg: model fact extraction ran before
the reply; now rules before, model pass after, skipped for questions
and greetings -> 2.5 s avg
Improve:
- retrieval defaults from the sweep (cos 0.25, ms-marco rerank_min 1e-4):
hit@3 0.75 -> 0.967 dev / 0.975 held-out
- question-only messages are not recalled as memories
- repeats upgrade a tool-stored fact to the user's framing ('my sister')
- configuration errors print a message instead of an exception dump
Verify: make test, e2e, resilience 8/8, small-profile smoke all pass.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…all-profile baseline
- consolidate.py: optional second stage after SFT. Preference pairs
(unknown -> abstain over the model's own answer, with same-shaped
look-alike facts in the memory block; known -> fact over abstain),
reference log-probs scored once, DPO loss + small NLL on chosen
- manifest: refused_known, dpo {pairs, pair_accuracy, abstain_unseen}
- tests for pair building; bench records the new metrics
- small baseline: base+RAG 0.97, LoRA 0.88, LoRA+RAG 1.00, confab 0.55 /
0.87 with a look-alike; drift 1.61 fails the gate at 30 facts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…(drift grows with fact count) Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…tion (0/6) Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…acc 0.78 -> 0.80) Drift tracks total optimizer steps; anchor replay made it worse. Verified: e2e passes (recall 1.00 on every consolidation, drift 1.10). Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
For 'my X' questions, an answer that uses a stored value belonging to a different subject is replaced with an abstention (cf. 'Stemming Hallucination in Language Models Using a Licensing Oracle', 2511.06073). Subject match: shared content word, or bge-reranker-base(question, 'subject: text') >= 0.03 (ms-marco cannot separate paraphrases from look-alikes; measured with the new diagnostics). Offline on recorded answers: confabulation tiny 0.70 -> 0.25, small 0.55 -> 0.20 (0.87 -> 0.33 with a look-alike in the prompt), for 3-7 points of accuracy. Guarded questions are generated, licensed, then shown. [guard] enabled=auto (on when bge is provisioned); --provision fetches it. Also: bench/bench_agent.py (system benchmark through the real binary), bench_guard (offline guard evaluation). Live agent verification pending. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…ected Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…with guard); LoRA-alone recall drop confounded with epochs, ablation queued Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…ralize (guard: confab 0.60 -> 0.20, 0 false blocks) Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
… 36% faster); DPO stays off Ablation (small, 2 epochs, no DPO) separates the confound: DPO caused the LoRA-alone recall drop. With the guard, 2 epochs reaches LoRA+RAG 0.933 and look-alike confabulation 0.067 (from 0.87); adding DPO gives the same confabulation at 0.867 accuracy and 5.6x training time. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…leep -> 0.83 after, 0 confabulation, 2.3 s/turn Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…e sleep, confab 0.20, 2.7 s/turn Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
…ion rejected after fresh-pair validation Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01NPVFJHeBeotAKkU7EPbTgn
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this adds
memagent is an always-on agent written in Free Pascal with two tiers of memory:
Split between Pascal and Python. The agent itself is Pascal: the loop, the memory store, retrieval, scheduling, adapter bookkeeping and the guard. Python does only the tensor work, as two processes the agent launches with
TProcess: a long-lived inference worker (trainer/worker.py, JSON lines over stdin/stdout) and a one-shot trainer (trainer/consolidate.py).Highlights
models.json:tiny(SmolLM2-135M, CPU),small(Qwen2.5-1.5B),medium(Qwen3-4B, 4-bit) andlarge(Magistral 24B, 4-bit).Mem.*units: ONNX bindings, WordPiece/SentencePiece tokenizers, embedder, reranker and static embedder.Mem.Https: a verifying TLS client. It checks the certificate chain and hostname, tunnels throughHTTPS_PROXY, honoursNO_PROXYand loads OpenSSL 3. FPC 3.2.2's stock client does none of these.memagent --provisionuses it to download the runtime and models.Mem.Guard): for a question about "my X", an answer that uses a stored value belonging to a different subject is replaced with "You haven't told me that yet."Measured results (details in
bench/README.md)/sleep. Confabulation is 0.20. About 2.7 s per turn on CPU.Testing
make test: Pascal retrieval checks, TLS verification checks against a localopenssl s_server, and the Python unit tests.make test-e2e: runs the real binary with the tiny model through two consolidations, a correction,/forget,/rollback, recall by meaning and a non-ASCII fact.scripts/resilience_test.sh: restart, worker crash, static-embedder fallback, and/quitduring training.scripts/profile_smoke.sh small [--train]: smoke test for the larger profiles.bench/: the memory, retrieval, guard and end-to-end benchmarks.All of the above pass on CPU in the build container.
Not tested
mediumandlarge: not run, and their hyperparameters (8 epochs, from v2) are untuned. Ontinyandsmallthat many epochs drifted too far. RunINFER_GPU=0 TRAIN_GPU=1 scripts/profile_smoke.sh medium --trainbefore relying on them.IEngine, so it can be added without changing the agent.Generated by Claude Code