Skip to content

memagent: Free Pascal agent with RAG short-term memory and hot-swapped LoRA long-term memory - #1

Merged
FMXExpress merged 24 commits into
mainfrom
claude/optimistic-allen-i3bd3d
Oct 29, 2026
Merged

FMXExpress merged 24 commits into
mainfrom
claude/optimistic-allen-i3bd3d

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

What this adds

memagent is an always-on agent written in Free Pascal with two tiers of memory:

  • Short-term memory: the chat context plus RAG over earlier messages and stored facts. Search combines SQLite FTS5 keyword search with a local MiniLM embedder, then re-scores the results with a local cross-encoder reranker. Both models run inside the Pascal program through ONNX Runtime.
  • Long-term memory: facts are trained into a LoRA by a background trainer (on the second GPU, or the CPU). Each new adapter must pass an eval gate (recall on held-out questions, and drift on general prompts) before it is hot-swapped into the running model between turns.

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

  • Model profiles in models.json: tiny (SmolLM2-135M, CPU), small (Qwen2.5-1.5B), medium (Qwen3-4B, 4-bit) and large (Magistral 24B, 4-bit).
  • Local retrieval brought in from PasClaw as 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 through HTTPS_PROXY, honours NO_PROXY and loads OpenSSL 3. FPC 3.2.2's stock client does none of these. memagent --provision uses it to download the runtime and models.
  • Licensing guard (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."
  • Optional DPO abstention stage, measured and left off by default.
  • Robustness: UTF-8 everywhere, worker crash recovery, rollback that survives a restart, migrations for existing databases.

Measured results (details in bench/README.md)

  • End to end (tiny model, 30 facts told in conversation): 0.32 accuracy before training, 0.80 after one /sleep. Confabulation is 0.20. About 2.7 s per turn on CPU.
  • Guard: confabulation falls from 0.60–0.87 to 0.07–0.27. On the held-out set no correct answer was blocked.
  • Retrieval: the right fact appears in the top 3 for 0.97 of questions (it was 0.75). Search at 12k stored items takes 65 ms per query; before an index fix it took 1.2 s at 3k items.
  • First token on the small model: 2.5 s on average, down from 7.9 s.
  • Facts extracted correctly from sentences: 1.00 (was 0.77).
  • Every tuned default was verified on a held-out set that was never used for tuning.

Testing

  • make test: Pascal retrieval checks, TLS verification checks against a local openssl 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 /quit during 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

  • CUDA and 4-bit paths: never run.
  • medium and large: not run, and their hyperparameters (8 epochs, from v2) are untuned. On tiny and small that many epochs drifted too far. Run INFER_GPU=0 TRAIN_GPU=1 scripts/profile_smoke.sh medium --train before relying on them.
  • Windows: the OpenSSL DLL path is untested.
  • Not built yet: in-process GGUF inference through llama.cpp (the localpal approach). The agent only talks to an IEngine, so it can be added without changing the agent.

Generated by Claude Code

claude added 24 commits October 28, 2026 21:19
…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
…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
…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
… 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
@FMXExpress
FMXExpress merged commit b501358 into main Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants