Zero Labs
Industry News / AI

Memory That Learns From Mistakes, With a Human Gate and an Expiry Date

Source · Towards AI By Ali Süleyman TOPUZ

From the publisher’s feed, collected in the ZeroLabs newsroom.

I compared four ways agents remember corrections, built a lesson store in .NET with approval, expiry and a scope key, and ran 20 scripted sessions through eight designs. The gate helped less than I expected. The expiry date hurt more.Every coding agent I use has made the same mistake twice. Not the same kind of mistake: the same one. It runs dotnet test on the whole solution, 37 integration tests fail because Postgres isn't running, I tell it to use the filter, and two days later, in a fresh session, it does exactly the same thing.The obvious fix is memory. Record the correction, give it back next time. I’ve written several pieces about agent memory in the last two months, and this one is narrower than the others. It’s about one kind of memory: lessons extracted from mistakes. And it’s about the two ways that memory goes bad. It can learn the wrong thing, because the “fix” in a session was a coincidence. And it can keep a right thing past the day it stopped being right, because the build script changed under it.So the title has two halves. A human gate, for the first problem. An expiry date, for the second.I started from Beacon, which a newsletter summary made sound like exactly this, compared it with three other designs I read about this week, built my own version in .NET, and ran 20 scripted sessions through eight designs. The results are below, and so is a bug in my own reviewer logic that the run surfaced. I’ll be upfront about the sample size now: 20 sessions is small, and I’ll show how small it is when we get to the numbers.How to read the numbers in this pieceNumbers from vendors, sponsored posts or authors describing their own work are labelled as such. I didn’t reproduce any of them. The only numbers I stand behind are from my own run, and that run is scripted: the agent, the mistakes and the reviewer decisions all follow written rules, which I show. It measures the memory layer, not a model.Four designs I looked at1. Beacon: sessions in, reviewed lessons outI first saw Beacon in a Simplifying AI summary on X, which described it as recording sessions from Claude Code, Codex, Cursor and 20+ other tools, extracting corrections and fixes, and letting you approve each lesson. Before repeating that, I went to the project itself.What I could confirm from the site, the repository and its published skills:It’s from Asymptote Labs and open source. The project describes itself as MIT licensed and local-first.It captures prompts, tool calls, edits and outcomes across Claude Code, Cursor, Codex, OpenCode and, in its own words, 20+ other harnesses, into one local log normalised to an OpenTelemetry-based event model.The learning loop is a candidate lifecycle. beacon memory evaluations run scores traces with an evaluator model (Jev). The distill skill is explicit that this step sends trace data to the evaluator over the network, and that the evaluator returns scores only. That's why beacon memory candidates approve takes --title, --body, --kind (workflow, correction, debugging_pattern, gotcha, convention), --applicability and --tag: the person writes the lesson text. There are also reject and supersede --replacement .The distill skill tells the agent not to approve, reject or supersede anything the user hasn’t confirmed. The recall skill says approved memory “has been reviewed by a person” and calls memories lessons from specific sessions, not project policy. I like that sentence a lot.Approved memory can be promoted to an Agent Skill in the repository, and the promote skill warns that a skill’s description decides when it loads, so it has to name the trigger: a command, a path or an error.Two things I did not find. First, any expiry, TTL or automatic invalidation. Supersede is manual. I read the README, the three memory skills and several pull requests; if there is an expiry mechanism elsewhere, I missed it. Second, any measurement of how many approved lessons turn out wrong. One recent pull request (#992, 21 October) fixed a bug where regenerating candidates reset already reviewed ones back to pending. That’s normal for a young project, and it’s also a reminder that the review state is the most valuable data in the system.2. Agent Framework for Python: keep the whole transcript searchableMicrosoft’s 15 October post on vector stores in Agent Framework for Python introduces VectorStoreHistoryProvider. It persists the full conversation in a vector collection and loads only a compacted working set into the model's context. With include_search_tool=True, the agent also gets a tool to search the complete scoped transcript, so an old decision or preference can be found without carrying every message on every call.The post is clear that the vector-store APIs are still experimental and the integration packages are alpha or beta. It’s a Python post; the .NET side has separate vector-store guidance, and I didn’t find this history provider described there.This design doesn’t extract lessons at all. The mistake and its correction both stay as raw messages. That turned out to matter.3. codewithmukesh: every turn is a memory (sponsored)Mukesh Murugan’s “RAG in ASP.NET Core (.NET 10): A Chat API That Remembers” carries a sponsored, partner-content label for GoodMem. He says he built and ran everything himself and that the opinions are his. The product is the sponsor’s; the failure findings are the part I care about, and they’re good:Every question and answer is stored as a memory tagged with kind = conversation and the caller's user_id, which comes from authentication, never from the request body.The last six turns go along with every request as context.In his tests with gpt-5-mini, GoodMem's default system prompt made the model ignore that context, because it told the model to stick to retrieved data. He had to supply his own prompts.The SDK’s default timeout is infinite, and on a streamed call the timeout you set only covers the wait for the response headers.A failed rerank doesn’t fail the request. It falls back to plain vector results and reports a RERANKING_FAILED status event, so you only notice if you read those events.With his first prompt fix, a second user with no history was told an example from one of his articles as if it were their own project.His reranker measurement (28 questions over 19 articles, hit@1 from 25 to 27, about 352 ms extra at the median) is author-run in a sponsored post. I’m repeating it only as his number.4. A seen.md file: the low-tech research deskThe fourth design came from a how-to on running a research desk in Claude Code cloud sessions. The pattern is one file, seen.md, listing what the desk has already covered, read at the start of every run so the next run doesn't repeat itself. I couldn't find the exact page again to link it, so I'm describing only the pattern. One detail from the cloud session docs matters for it: a cloud session works from a clone of your repository, and as I read the docs, personal files under ~/.claude don't come along. A file like this has to live in the repository.No retrieval, no approval, no expiry. Append, deduplicate, load everything.The invalidation story: skills rot, and the key decides what rotsTwo other pieces gave me the vocabulary for the expiry half.Jaroslaw Wasowski’s “Harness Ownership” argues that harness artifacts (instruction files, skills, hooks, tool contracts) are not documentation, and that a harness rots without an owner just like unclaimed code. Medium blocked my reader this time, so I worked from the opening and the summary in my notes, not the full text. The point I took is simple: a lesson nobody owns doesn’t stay correct, it just stays.Realinho’s piece on caching and memoizing agent results for OutSystems ODC and O11 is about caches, not memory, but the idea transfers directly. As my notes summarise it (I couldn’t load the full article either): put the version, the tenant and the permission scope inside the cache key, and if average reuse per entry is below 1, the key is wrong, because you’re writing entries nobody reads again.A lesson is a cached conclusion. If the build script changes, a lesson about how to run the tests is a cache entry with a stale key. So my lesson store got a key: the repository (tenant), a fingerprint of the files the lesson depends on (version), and a permission scope.The build: a lesson store in .NET with SQLite and OllamaThe lesson recordEach lesson has: source session, evidence, scope (repository, a dependency fingerprint, a permission), status (candidate, approved, rejected, superseded), created date, last used, use count, expiry, and supersedes / superseded_by pointers. Retrieval refuses anything unapproved, superseded, expired, outside the caller's permissions, or whose dependency fingerprint no longer matches the files on disk. Refusals are logged with a reason, because "why didn't the agent get this lesson?" is the first question you'll ask.Setup# local embedding modelollama pull nomic-embed-text# or, with Dockerdocker run -d --name ollama -p 11434:11434 -v ollama:/root/.ollama ollama/ollamadocker exec ollama ollama pull nomic-embed-text# projectdotnet new console -n LessonLab -f net10.0cd LessonLabdotnet add package Microsoft.Data.Sqlite --version "10.0.*"Then replace the generated files with the ones below. OLLAMA_URL, EMBED_MODEL and LESSONS_DB override the defaults (http://localhost:11434, nomic-embed-text, lessons.db).LessonLab.csproj Exe net10.0 enable enable lessons Embedder.csnomic-embed-text was trained with search_query: and search_document: prefixes, so the embedder adds them for that model and leaves other models alone.using System.Net.Http.Json;using System.Runtime.InteropServices;namespace LessonLab;public interface IEmbedder{ string Model { get; } Task EmbedAsync(string text, bool isQuery, CancellationToken ct = default);}// Local Ollama: `ollama pull nomic-embed-text`, server on http://localhost:11434public sealed class OllamaEmbedder(HttpClient http, string model) : IEmbedder{ public string Model => model; // nomic-embed-text was trained with task prefixes; other models get the text as is private bool Nomic => model.StartsWith("nomic-embed-text", StringComparison.OrdinalIgnoreCase); public async Task EmbedAsync(string text, bool isQuery, CancellationToken ct = default) { var input = Nomic ? (isQuery ? "search_query: " : "search_document: ") + text : text; var res = await http.PostAsJsonAsync("/api/embed", new { model, input }, ct); res.EnsureSuccessStatusCode(); var body = await res.Content.ReadFromJsonAsync(cancellationToken: ct) ?? throw new InvalidOperationException("empty embed response"); return Vec.Normalize(body.Embeddings[0]); } private sealed record EmbedResponse(float[][] Embeddings);}public static class Vec{ public static float[] Normalize(float[] v) { var n = MathF.Sqrt(v.Sum(x => x * x)); return n == 0 ? v : v.Select(x => x / n).ToArray(); } public static byte[] Pack(float[] v) => MemoryMarshal.AsBytes(v.AsSpan()).ToArray(); public static float[] Unpack(byte[] b) => MemoryMarshal.Cast(b).ToArray(); // inputs are normalized, so the dot product is the cosine public static float Cosine(float[] a, float[] b) { float d = 0; for (var i = 0; i return d; }}LessonStore.csThe RecallPolicy switches let one store stand in for several designs in the experiment. In normal use, leave them all on.using System.Security.Cryptography;using System.Text;using System.Text.Json;using Microsoft.Data.Sqlite;namespace LessonLab;public sealed record Lesson( string Id, string Title, string Body, string Kind, string Repo, string DependsOn, string ToolchainKey, string Permission, string SourceSession, string[] Evidence, string Status, DateTime CreatedAt, DateTime? ApprovedAt, DateTime? LastUsedAt, long UseCount, DateTime? ExpiresAt, string? Supersedes, string? SupersededBy, float[] Embedding);public sealed record Hit(Lesson Lesson, float Score);public sealed record Refusal(Lesson Lesson, float Score, string Reason);public sealed record RecallResult(List Served, List Refused);public sealed record RecallRequest( string Query, string Repo, string RepoRoot, IReadOnlySet Permissions, int K = 3, float MinScore = 0.35f);// Every gate can be switched off, so one store can stand in for several designs.public sealed record RecallPolicy( bool RequireApproval = true, bool ExcludeSuperseded = true, bool EnforceExpiry = true, bool EnforceToolchain = true, bool EnforcePermission = true);public static class Fingerprint{ // Hash of the files a lesson depends on. A changed or newly created file changes the key. public static string Of(string repoRoot, string dependsOn) { var files = dependsOn.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (files.Length == 0) return "*"; var sb = new StringBuilder(); foreach (var f in files.OrderBy(x => x, StringComparer.Ordinal)) { var path = Path.Combine(repoRoot, f); var h = File.Exists(path) ? Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(path))) : "missing"; sb.Append(f).Append('=').Append(h).Append('\n'); } return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sb.ToString())))[..16].ToLowerInvariant(); }}public sealed class LessonStore : IDisposable{ private readonly SqliteConnection _db; private readonly IEmbedder _embedder; private readonly TimeProvider _clock; public LessonStore(string path, IEmbedder embedder, TimeProvider clock) { _embedder = embedder; _clock = clock; _db = new SqliteConnection($"Data Source={path}"); _db.Open(); Exec(""" PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; CREATE TABLE IF NOT EXISTS lessons( id TEXT PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL, kind TEXT NOT NULL, repo TEXT NOT NULL, depends_on TEXT NOT NULL DEFAULT '', toolchain_key TEXT NOT NULL DEFAULT '*', permission TEXT NOT NULL DEFAULT '*', source_session TEXT NOT NULL, evidence TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'candidate', reviewed_by TEXT, review_reason TEXT, created_at TEXT NOT NULL, approved_at TEXT, last_used_at TEXT, use_count INTEGER NOT NULL DEFAULT 0, expires_at TEXT, supersedes TEXT REFERENCES lessons(id), superseded_by TEXT REFERENCES lessons(id), embed_model TEXT NOT NULL, embedding BLOB NOT NULL); CREATE INDEX IF NOT EXISTS ix_lessons_repo_status ON lessons(repo, status); CREATE TABLE IF NOT EXISTS recall_log( at TEXT NOT NULL, lesson_id TEXT NOT NULL, query TEXT NOT NULL, score REAL NOT NULL, outcome TEXT NOT NULL); """); } private DateTime Now => _clock.GetUtcNow().UtcDateTime; private static string Iso(DateTime d) => d.ToString("O"); // ------------------------------------------------------------------ write path public async Task AddCandidateAsync(string title, string body, string kind, string repo, string sourceSession, IEnumerable evidence, CancellationToken ct = default) { var id = "L-" + Convert.ToHexString(RandomNumberGenerator.GetBytes(4)).ToLowerInvariant(); var vec = await _embedder.EmbedAsync($"{title}\n{body}", isQuery: false, ct); Exec(""" INSERT INTO lessons(id,title,body,kind,repo,source_session,evidence,created_at,embed_model,embedding) VALUES($id,$title,$body,$kind,$repo,$src,$ev,$now,$model,$vec) """, ("$id", id), ("$title", title), ("$body", body), ("$kind", kind), ("$repo", repo), ("$src", sourceSession), ("$ev", JsonSerializer.Serialize(evidence.ToArray())), ("$now", Iso(Now)), ("$model", _embedder.Model), ("$vec", Vec.Pack(vec))); return id; } public async Task ApproveAsync(string id, string reviewer, string repoRoot, TimeSpan? ttl, string dependsOn = "", string permission = "*", string? title = null, string? body = null, string? reason = null, CancellationToken ct = default) { var l = Get(id) ?? throw new ArgumentException($"no lesson {id}"); if (l.Status != "candidate") throw new InvalidOperationException($"{id} is {l.Status}, not a candidate"); title ??= l.Title; body ??= l.Body; var vec = (title == l.Title && body == l.Body) ? l.Embedding : await _embedder.EmbedAsync($"{title}\n{body}", isQuery: false, ct); var now = Now; Exec(""" UPDATE lessons SET status='approved', title=$title, body=$body, embedding=$vec, depends_on=$deps, toolchain_key=$tk, permission=$perm, reviewed_by=$who, review_reason=$why, approved_at=$now, expires_at=$exp WHERE id=$id """, ("$id", id), ("$title", title), ("$body", body), ("$vec", Vec.Pack(vec)), ("$deps", dependsOn), ("$tk", Fingerprint.Of(repoRoot, dependsOn)), ("$perm", permission), ("$who", reviewer), ("$why", reason), ("$now", Iso(now)), ("$exp", ttl is null ? null : Iso(now + ttl.Value))); } public void Reject(string id, string reviewer, string reason) => Exec("UPDATE lessons SET status='rejected', reviewed_by=$who, review_reason=$why WHERE id=$id AND status='candidate'", ("$id", id), ("$who", reviewer), ("$why", reason)); // A duplicate candidate for an expired or key-changed lesson is fresh evidence that the lesson // still holds. Renew the old lesson instead of rejecting the candidate as a duplicate. public void Renew(string id, string fromCandidate, string reviewer, string repoRoot, TimeSpan? ttl) { var l = Get(id) ?? throw new ArgumentException($"no lesson {id}"); var c = Get(fromCandidate) ?? throw new ArgumentException($"no candidate {fromCandidate}"); var now = Now; Exec("BEGIN"); Exec("UPDATE lessons SET expires_at=$exp, toolchain_key=$tk, evidence=$ev, review_reason=$why WHERE id=$id", ("$id", id), ("$exp", ttl is null ? null : Iso(now + ttl.Value)), ("$tk", Fingerprint.Of(repoRoot, l.DependsOn)), ("$ev", JsonSerializer.Serialize(l.Evidence.Concat(c.Evidence).ToArray())), ("$why", $"renewed from {fromCandidate} by {reviewer}")); Exec("UPDATE lessons SET status='rejected', reviewed_by=$who, review_reason=$why WHERE id=$c", ("$c", fromCandidate), ("$who", reviewer), ("$why", $"merged into {id}")); Exec("COMMIT"); } // What the reviewer needs to know about an approved lesson before calling something a duplicate. public string Health(Lesson l, string repoRoot) { if (l.Status != "approved") return l.Status; if (l.ExpiresAt is { } e && e if (l.ToolchainKey != "*" && Fingerprint.Of(repoRoot, l.DependsOn) != l.ToolchainKey) return "key changed"; return "live"; } // The old lesson stays in the table for history; it just stops being served. public void Supersede(string oldId, string newId, string reviewer, string reason) { Exec("BEGIN"); Exec("UPDATE lessons SET status='superseded', superseded_by=$new, review_reason=$why, reviewed_by=$who WHERE id=$old", ("$old", oldId), ("$new", newId), ("$why", reason), ("$who", reviewer)); Exec("UPDATE lessons SET supersedes=$old WHERE id=$new", ("$old", oldId), ("$new", newId)); Exec("COMMIT"); } // ------------------------------------------------------------------ read path public async Task RecallAsync(RecallRequest req, RecallPolicy policy, CancellationToken ct = default) { var now = Now; var q = await _embedder.EmbedAsync(req.Query, isQuery: true, ct); var fingerprints = new Dictionary(); var ranked = Query("SELECT * FROM lessons WHERE repo=$repo AND status <> 'rejected'", ("$repo", req.Repo)) .Select(l => (Lesson: l, Score: Vec.Cosine(q, l.Embedding))) .Where(x => x.Score >= req.MinScore) .OrderByDescending(x => x.Score); var served = new List(); var refused = new List(); foreach (var (l, score) in ranked) { var reason = Gate(l, policy, req, now, fingerprints); if (reason is not null) { refused.Add(new Refusal(l, score, reason)); continue; } if (served.Count } Exec("BEGIN"); foreach (var h in served) { Exec("UPDATE lessons SET use_count=use_count+1, last_used_at=$now WHERE id=$id", ("$id", h.Lesson.Id), ("$now", Iso(now))); Log(h.Lesson.Id, req.Query, h.Score, "served", now); } foreach (var r in refused) Log(r.Lesson.Id, req.Query, r.Score, "refused:" + r.Reason, now); Exec("COMMIT"); return new RecallResult(served, refused); } private static string? Gate(Lesson l, RecallPolicy p, RecallRequest req, DateTime now, Dictionary fp) { if (p.RequireApproval && l.Status == "candidate") return "unapproved"; if (p.ExcludeSuperseded && l.Status == "superseded") return "superseded"; if (p.EnforceExpiry && l.ExpiresAt is { } exp && exp if (p.EnforcePermission && l.Permission != "*" && !req.Permissions.Contains(l.Permission)) return "permission"; if (p.EnforceToolchain && l.ToolchainKey != "*") { if (!fp.TryGetValue(l.DependsOn, out var current)) fp[l.DependsOn] = current = Fingerprint.Of(req.RepoRoot, l.DependsOn); if (current != l.ToolchainKey) return "toolchain-changed"; } return null; } public Lesson? Get(string id) => Query("SELECT * FROM lessons WHERE id=$id", ("$id", id)).FirstOrDefault(); public List List(string? status = null, string? repo = null) => Query("SELECT * FROM lessons WHERE ($s IS NULL OR status=$s) AND ($r IS NULL OR repo=$r) ORDER BY created_at, rowid", ("$s", status), ("$r", repo)); // What a reviewer sees next to a candidate: the closest approved lessons in the same repo. public List Neighbours(Lesson candidate, int n = 3, float min = 0.45f) => List("approved", candidate.Repo) .Select(l => new Hit(l, Vec.Cosine(candidate.Embedding, l.Embedding))) .Where(h => h.Score >= min).OrderByDescending(h => h.Score).Take(n).ToList(); // Realinho's check, applied to lessons: average reuse below 1 means the key is too narrow. public (int Approved, double AvgReuse) ReuseStats() { using var cmd = _db.CreateCommand(); cmd.CommandText = "SELECT COUNT(*), COALESCE(AVG(use_count),0) FROM lessons WHERE status IN ('approved','superseded')"; using var r = cmd.ExecuteReader(); r.Read(); return ((int)r.GetInt64(0), r.GetDouble(1)); } // ------------------------------------------------------------------ plumbing private void Log(string id, string query, float score, string outcome, DateTime now) => Exec("INSERT INTO recall_log(at,lesson_id,query,score,outcome) VALUES($at,$id,$q,$s,$o)", ("$at", Iso(now)), ("$id", id), ("$q", query), ("$s", (double)score), ("$o", outcome)); private void Exec(string sql, params (string, object?)[] ps) { using var cmd = _db.CreateCommand(); cmd.CommandText = sql; foreach (var (k, v) in ps) cmd.Parameters.AddWithValue(k, v ?? DBNull.Value); cmd.ExecuteNonQuery(); } private List Query(string sql, params (string, object?)[] ps) { using var cmd = _db.CreateCommand(); cmd.CommandText = sql; foreach (var (k, v) in ps) cmd.Parameters.AddWithValue(k, v ?? DBNull.Value); using var r = cmd.ExecuteReader(); var list = new List(); while (r.Read()) { string S(int i) => r.GetString(i); string? N(int i) => r.IsDBNull(i) ? null : r.GetString(i); DateTime? D(int i) => r.IsDBNull(i) ? null : DateTime.Parse(r.GetString(i), null, System.Globalization.DateTimeStyles.RoundtripKind); list.Add(new Lesson( Id: S(0), Title: S(1), Body: S(2), Kind: S(3), Repo: S(4), DependsOn: S(5), ToolchainKey: S(6), Permission: S(7), SourceSession: S(8), Evidence: JsonSerializer.Deserialize(S(9)) ?? [], Status: S(10), CreatedAt: D(13)!.Value, ApprovedAt: D(14), LastUsedAt: D(15), UseCount: r.GetInt64(16), ExpiresAt: D(17), Supersedes: N(18), SupersededBy: N(19), Embedding: Vec.Unpack(r.GetFieldValue(21)))); } return list; } public void Dispose() => _db.Dispose();}Program.cs: the approval CLIThe experiment block at the top needs the harness files from my experiment (they're in the code bundle, not in this post); delete that block if you only want the CLI.using LessonLab;var ollama = new HttpClient { BaseAddress = new Uri(Environment.GetEnvironmentVariable("OLLAMA_URL") ?? "http://localhost:11434") };var embedder = new OllamaEmbedder(ollama, Environment.GetEnvironmentVariable("EMBED_MODEL") ?? "nomic-embed-text");if (args.Length > 0 && args[0] == "experiment"){ var outDir = Opt(args, "--out") ?? "runs"; GatedLessons.RenewOnDuplicate = !args.Contains("--reject-duplicates"); await Experiment.RunAsync(embedder, outDir); // the settings I chose up front await Experiment.RunAsync(embedder, outDir, k: 5, min: 0.25f, verbose: false); // looser retrieval, as a check return;}using var store = new LessonStore(Environment.GetEnvironmentVariable("LESSONS_DB") ?? "lessons.db", embedder, TimeProvider.System);var reviewer = Environment.GetEnvironmentVariable("USER") ?? "reviewer";switch (args.FirstOrDefault()){ case "add": var body = Opt(args, "--body-file") is { } bf ? File.ReadAllText(bf) : Req(args, "--body"); var id = await store.AddCandidateAsync(Req(args, "--title"), body, Opt(args, "--kind") ?? "correction", Req(args, "--repo"), Req(args, "--session"), Opts(args, "--evidence")); Console.WriteLine(id); break; case "pending": foreach (var l in store.List("candidate", Opt(args, "--repo"))) Console.WriteLine($"{l.Id} [{l.Kind}] {l.Repo} {l.Title} (from {l.SourceSession}, {l.Evidence.Length} evidence)"); break; case "show": var c = store.Get(args[1]) ?? throw new ArgumentException("not found"); Console.WriteLine($"{c.Id} [{c.Status}] {c.Kind} repo={c.Repo} session={c.SourceSession}"); Console.WriteLine($"title: {c.Title}\n\n{c.Body}\n"); Console.WriteLine("evidence:"); foreach (var e in c.Evidence) Console.WriteLine($" - {e}"); Console.WriteLine("closest approved lessons (supersede one of these if this replaces it):"); foreach (var n in store.Neighbours(c)) Console.WriteLine($" {n.Score:F2} {n.Lesson.Id} [{store.Health(n.Lesson, Opt(args, "--root") ?? ".")}] {n.Lesson.Title}"); break; case "approve": await store.ApproveAsync(args[1], reviewer, Opt(args, "--root") ?? ".", ParseTtl(Opt(args, "--ttl")), dependsOn: Opt(args, "--depends-on") ?? "", permission: Opt(args, "--permission") ?? "*", title: Opt(args, "--title"), body: Opt(args, "--body"), reason: Opt(args, "--reason")); Console.WriteLine($"approved {args[1]}"); break; case "renew": store.Renew(args[1], Req(args, "--from"), reviewer, Opt(args, "--root") ?? ".", ParseTtl(Opt(args, "--ttl"))); Console.WriteLine($"renewed {args[1]} from {Opt(args, "--from")}"); break; case "reject": store.Reject(args[1], reviewer, Req(args, "--reason")); Console.WriteLine($"rejected {args[1]}"); break; case "supersede": store.Supersede(args[1], Req(args, "--by"), reviewer, Opt(args, "--reason") ?? "replaced"); Console.WriteLine($"{args[1]} superseded by {Opt(args, "--by")}"); break; case "recall": var perms = (Opt(args, "--perm") ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries).ToHashSet(); var res = await store.RecallAsync( new RecallRequest(args[1], Req(args, "--repo"), Opt(args, "--root") ?? ".", perms, int.Parse(Opt(args, "--k") ?? "3"), float.Parse(Opt(args, "--min") ?? "0.35")), new RecallPolicy()); foreach (var h in res.Served) Console.WriteLine($"SERVED {h.Score:F2} {h.Lesson.Id} {h.Lesson.Title}\n {h.Lesson.Body}"); foreach (var r in res.Refused) Console.WriteLine($"REFUSED {r.Score:F2} {r.Lesson.Id} ({r.Reason}) {r.Lesson.Title}"); break; case "stats": var (n2, avg) = store.ReuseStats(); Console.WriteLine($"approved or superseded lessons: {n2}, average reuse: {avg:F2}{(avg break; default: Console.WriteLine("usage: lessons add|pending|show|approve|renew|reject|supersede|recall|stats|experiment"); break;}static string? Opt(string[] a, string name) { var i = Array.IndexOf(a, name); return i >= 0 && i + 1 static string Req(string[] a, string name) => Opt(a, name) ?? throw new ArgumentException($"{name} is required");static IEnumerable Opts(string[] a, string name) { for (var i = 0; i static TimeSpan? ParseTtl(string? s) => s switch{ null or "none" => null, _ when s.EndsWith('d') => TimeSpan.FromDays(int.Parse(s[..^1])), _ when s.EndsWith('h') => TimeSpan.FromHours(int.Parse(s[..^1])), _ => TimeSpan.Parse(s)};What a review looks likeThis is a real session with the CLI, lightly trimmed. The candidate comes from a session where the agent ran dotnet test and found nothing.$ lessons add --repo payments-api --session "2026-10-20 ali claude-code" --kind convention \ --title "payments-api tests run through ./build.sh" \ --body "Use ./build.sh UnitTests. Plain dotnet test skips fixture generation and discovers 0 tests." \ --evidence "dotnet test: 0 tests discovered in Payments.Tests" \ --evidence "user: use ./build.sh UnitTests" \ --evidence "./build.sh UnitTests: 412 passed"L-daa49246$ lessons show L-daa49246 --root .L-daa49246 [candidate] convention repo=payments-api session=2026-10-20 ali claude-codetitle: payments-api tests run through ./build.shUse ./build.sh UnitTests. Plain dotnet test skips fixture generation and discovers 0 tests.evidence: - dotnet test: 0 tests discovered in Payments.Tests - user: use ./build.sh UnitTests - ./build.sh UnitTests: 412 passedclosest approved lessons (supersede one of these if this replaces it):$ lessons approve L-daa49246 --root . --ttl 60d \ --depends-on build.sh,tests/Directory.Build.props --reason "checked against the build script"approved L-daa49246$ lessons recall "how do I run the unit tests" --repo payments-api --root .SERVED 0.53 L-daa49246 payments-api tests run through ./build.sh Use ./build.sh UnitTests. Plain dotnet test skips fixture generation and discovers 0 tests.$ echo 'dotnet run --project build -- "$@"' >> build.sh$ lessons recall "how do I run the unit tests" --repo payments-api --root .REFUSED 0.53 L-daa49246 (toolchain-changed) payments-api tests run through ./build.shThe second recall is the whole point of the key. Nobody had to remember that this lesson depends on build.sh. The reviewer said so once, at approval time, and the store checks it on every read.The experiment: 20 scripted sessions, eight designsWhat I scriptedTwo repositories, payments-api and search-indexer, and two developers. Ali has the ops role, Deniz doesn't. Twenty sessions between 1 September and 23 October, each with a task and one to four "traps": things an agent gets wrong without being told.trap repo what goes wrong changes?--------- -------------- ------------------------------------------------- -------------------------------A-TEST payments-api runs integration tests that need Postgres yes, S11: moves to ./build.shA-MIGR payments-api dotnet ef without --context BillingDb noA-PROTO payments-api edits generated .g.cs instead of the .proto noA-TIME payments-api DateTime.UtcNow, analyzer PAY001 fails the build noA-OPS payments-api staging backfill credentials (differs by role) no, but two role variantsPKG both Version on PackageReference, NU1008 noB-SEARCH search-indexer no local OpenSearch, tests hit the fake yes, S15: OPENSEARCH_URL -> Search__UrlB-SNAP search-indexer hand-edits .verified files noB-BULK search-indexer bulk size too large, 429s noThe two changes are real file changes in two fake repositories on disk: build.sh and tests/Directory.Build.props appear in payments-api before session 11, and appsettings.json and docker-compose.yml change in search-indexer before session 15. There are also two routine package bumps (Directory.Packages.props) that don't invalidate anything, which is exactly why I added them.Four sessions also produce a wrong “fix” from the user:id session what the user said looks like--------- ------- --------------------------------------------------------- --------------------------W-CLEAN S05 delete bin and obj and rebuild (it passed by coincidence) a fix, with passing buildW-SNAPCI S09 set UPDATE_SNAPSHOTS=1 in CI so drift stops blocking a bypass of a checkW-DISABLE S13 skip the flaky RefundTimeoutTests a bypass of a checkW-RETRY S17 Thread.Sleep(5000) between bulk batches a fix, the 429s went awayThe agent ruleThe agent is scripted. At each trap it queries memory with a paraphrased intent (“check the test suite still passes”, not the lesson’s own words). Among the items it gets back that are about this trap, it acts on the one that looks most relevant, the highest similarity. If that item is correct for the current version, the mistake is avoided. If it’s an old version, that’s a stale hit. If it’s a wrong lesson or the other role’s variant, that’s a wrong-lesson hit. If nothing relevant comes back, it makes the naive mistake. A raw failure message (“Running dotnet test... 37 integration tests fail") counts as no guidance: the agent sees what failed but learns no fix from it. After a mistake, the user corrects it, and that correction becomes memory in whatever form the design uses.This agent obeys perfectly. A real model ignores things in its context sometimes, and the GoodMem default-prompt story shows a model ignoring the conversation entirely. So read these numbers as an upper bound on what each memory layer can deliver.The reviewer ruleThe reviewer is me, as a written rule, applied at roughly weekly reviews after sessions 3, 6, 9, 12, 15 and 18:Reject anything that skips, disables or rewrites a check.Look at the closest approved lessons the CLI shows (cosine 0.45 or higher, top 3). If one is the same lesson, reject the candidate as a duplicate. (More on this rule below; it had a bug.)Otherwise approve, and supersede any visible neighbour that this lesson replaces or contradicts.That rule doesn’t know which “fixes” were coincidences. Neither would I, reading the evidence: W-CLEAN had a failing build and then a passing one.The eight designsThese are my reimplementations of the shape of each design, not the products. I didn’t run Beacon, Agent Framework or GoodMem.design shape-------------------------------- ----------------------------------------------------------------------no memory baselinefull transcript, searchable every turn stored per user, top-3 by similarity (VectorStoreHistoryProvider shape)every turn + last 6 turns the same, plus the user's last 6 turns always included (the GoodMem chat API shape)seen.md, most similar line wins one file per repo, every correction appended, whole file loadedseen.md, newest line wins the same file, but the agent trusts the newest matching lineapproval only (Beacon-like) candidates, human review, supersede; no expiry, no keyapproval + expiry plus TTL by kind: convention 60d, workflow 45d, debugging 30d, gotcha 21dapproval + expiry + coarse key plus a fingerprint of every build file in the repoapproval + expiry + precise key plus a fingerprint of only the files the reviewer namedThe gated designs all use the LessonStore above with different RecallPolicy switches. Retrieval designs use top 3 with a similarity cut of 0.35, which I chose before the run. I also ran top 5 with a cut of 0.25 as a check.How I actually ran itSame disclaimer as my last memory piece, because the sandbox was the same kind of sandbox. I could install the .NET 10 SDK but not reach NuGet, Ollama’s model registry or Hugging Face. So:The C# above is what ran. For Microsoft.Data.Sqlite I compiled against a small stand-in over the system libsqlite3 with the same method names, so the store code is unchanged.For embeddings I ran a tiny local server that answers POST /api/embed the way Ollama does, backed by WordLlama's l2_supercat model (256 dimensions, ships inside its pip package). The OllamaEmbedder talked to it unchanged.WordLlama is a static embedding model and much weaker than nomic-embed-text at matching a question to an answer. That shows up directly in the results, so keep it in mind.The run is deterministic: three runs produced byte-identical output.ResultsDefinitionsRepeated-mistake rate: of the trap encounters where someone had already corrected that exact mistake (same trap, same version, same role) in an earlier session, the share where the agent made it again. 31 encounters qualify.Wrong-lesson rate: of the encounters where the agent acted on a memory item, the share where that item was wrong: a coincidental fix, or the other role’s variant. Stale items are counted separately.Stale-hit rate: of the 8 encounters after a convention changed, the share where the agent acted on the old version.Main run (top 3, similarity 0.35, chosen before the run)design mistakes repeated-mistake wrong-lesson stale-hit items per avg reuse (of 44) rate rate rate lookup per lesson-------------------------------- -------- ----------------- --------------- ------------- --------- ----------no memory 44 100.0% (31/31) n/a 0.0% (0/8) 0.0 -full transcript, searchable 44 100.0% (31/31) n/a (0 used) 0.0% (0/8) 1.7 -every turn + last 6 turns 37 77.4% (24/31) 0.0% (0/8) 12.5% (1/8) 6.7 -seen.md, most similar line wins 20 22.6% (7/31) 5.9% (2/34) 100.0% (8/8) 5.8 -seen.md, newest line wins 21 25.8% (8/31) 26.5% (9/34) 25.0% (2/8) 5.8 -approval only (Beacon-like) 27 45.2% (14/31) 4.8% (1/21) 37.5% (3/8) 0.7 2.13approval + expiry 29 51.6% (16/31) 5.6% (1/18) 25.0% (2/8) 0.6 1.87approval + expiry + coarse key 34 67.7% (21/31) 0.0% (0/10) 0.0% (0/8) 0.4 1.07approval + expiry + precise key 29 51.6% (16/31) 6.2% (1/16) 0.0% (0/8) 0.6 1.73Check run (top 5, similarity 0.25)design repeated-mistake wrong-lesson stale-hit-------------------------------- ----------------- --------------- -------------full transcript, searchable 64.5% (20/31) 0.0% (0/15) 50.0% (4/8)every turn + last 6 turns 48.4% (15/31) 0.0% (0/20) 50.0% (4/8)seen.md (both readings) unchanged, the whole file is always loadedapproval only (Beacon-like) 19.4% (6/31) 3.4% (1/29) 37.5% (3/8)approval + expiry 29.0% (9/31) 4.0% (1/25) 25.0% (2/8)approval + expiry + coarse key 48.4% (15/31) 0.0% (0/16) 0.0% (0/8)approval + expiry + precise key 29.0% (9/31) 4.3% (1/23) 0.0% (0/8)The ranking between designs mostly holds across the two settings. The absolute numbers move a lot, which tells you how much of this is retrieval quality rather than memory design.What I learned, in order of how much it surprised me1. A raw correction is hard to find. A rewritten lesson isn’t.The full-transcript design stored all 43 correct turns and the agent used none of them at top 3. Here’s why, for one query, with the similarities from this run’s embedding model:query: "payments-api: check the test suite still passes"item similarity----------------------------------------------------------- ----------approved lesson (title + body, names the repo and "tests") 0.46the session's task turn ("Add a refund endpoint ...") 0.40the failure turn ("Running dotnet test ... 37 fail") 0.30seen.md line with the correction 0.29the user's correction turn ("Don't run the integration...") 0.28The correction, as the user said it, is the least similar thing in the list. It’s phrased as a reaction (“don’t do that”), not as a description of the situation it applies to. The approved lesson has a title that names the situation, and it wins. That’s the same point Beacon’s promote skill makes about skill descriptions needing to name the trigger.So half of what the human gate bought me wasn’t filtering. It was rewriting. A design that keeps raw transcripts can still work (at top 5 it did, partly), but it pays for it in context: the last-6-turns design carried 6.7 items per lookup to get to 77.4%.2. The flat file was best at not repeating mistakes, and worst at stale onesseen.md had the lowest repeated-mistake rate in the main run, 22.6%. No retrieval to miss, and no review delay: a correction is in the file the moment it's made. After 20 sessions the larger of the two files was about 1.2 KB, so loading it whole was cheap.Then the conventions changed, and every one of the 8 post-change encounters acted on the old line, because the old line looked more relevant than the new one. If instead the agent trusts the newest matching line, stale hits drop to 2 of 8, but wrong-lesson hits jump to 9 of 34: the newest line about the 429 errors was “add a Thread.Sleep”, and the newest line touching the build was “delete bin and obj”. Which of those two readings a real model does is not something I control. That’s the problem with a file that has no supersession: the reader decides what’s current, every time.It also leaked. In session 8, Deniz’s agent acted on Ali’s line about the ops-staging Vault credentials, which Deniz doesn’t have access to.3. The gate caught the bypasses and passed the coincidencesFour wrong candidates went to review. My rule rejected the two that turned off a check (snapshots in CI, skipping the flaky test) and approved the two that looked like fixes, because their evidence said failing, then passing:W-CLEAN (“delete bin and obj”) was approved on 12 September and was still approved at the end of the run in the Beacon-like design. It was never retrieved: its use count is 0. A dormant wrong lesson, waiting for the right query.W-RETRY (“sleep between batches”) was approved and superseded in the same review on 15 October, but only because the correct lesson about bulk size arrived in the same batch and was similar enough to show up as a neighbour. Had the reviews been a day apart, it would have been served.So the human gate’s wrong-lesson rate in this run was 2 approved out of 4 wrong candidates. With four, that’s an anecdote, not a rate. What I take from it is the shape: a reviewer reading evidence catches lessons that look like shortcuts and misses lessons that look like fixes.The one wrong lesson the gated designs actually acted on was something else entirely: in session 19, Ali’s agent got “Without the ops role, staging backfills go through an OPS ticket” (similarity 0.38) and filed a ticket he didn’t need. My permission gate only works one way. It keeps the ops lesson away from people without the role, but nothing keeps the no-role lesson away from people with it.4. Expiry worked, cost three repeats, and exposed a bug in my reviewerFor “approval + expiry”, here are the stale lessons before and after expiry:event count where--------------------------------------------------------------- ----- -----------------------------------------stale lesson served, still within its TTL 2 A-TEST v1 (60-day convention) at S11, S12stale lesson refused because it had expired 1 B-SEARCH v1 (21-day gotcha) at S15still-valid lesson refused because it had expired 3 B-SEARCH v1 at S14, A-TIME at S16, B-SNAP at S20Expiry prevented one stale hit and caused three repeated mistakes. A 60-day TTL on a convention is useless against a build change in week 4, and a 21-day TTL on a gotcha throws away good lessons. Time is a bad proxy for “did the world change”.And the run caught a bug. In my first version, when a fresh candidate matched an expired lesson, the reviewer rule rejected it as a duplicate. The CLI showed the expired lesson as a neighbour, it was the same lesson, so: duplicate. The result is that once a lesson expired, re-learning it never brought it back. I added Renew: a duplicate of an expired or key-changed lesson is fresh evidence, so it extends the old lesson and merges the evidence. The CLI now prints each neighbour's health (live, expired, key changed) next to it.The fix barely moved the numbers in 20 sessions (the coarse-key design went from 71.0% to 67.7% repeated mistakes, the others didn’t change), because most renewals happened after the last relevant encounter. It also has a hole I found in the log: on 5 October, the precise-key design renewed the old OPENSEARCH_URL lesson from a session that happened before the config change, and recomputed its fingerprint against the new files. For a moment, a stale lesson looked valid under the new key. The correct lesson in the same batch superseded it straight away, so it was never served, but that was luck again. The right fix is to snapshot the fingerprint when the evidence is captured, not when it's reviewed. I haven't built that yet.5. The key is what actually stopped stale lessons, and its granularity is everythingBoth key designs had zero stale hits. The difference between them is the cost:The coarse key (fingerprint of every build file in the repo) refused still-valid lessons 9 times, mostly because of the two routine package bumps. Repeated mistakes went up to 67.7%, the worst of the gated designs.The precise key (only the files the reviewer named) never refused a still-valid lesson and still caught both stale ones. Same repeated-mistake rate as expiry alone, with no stale hits.Realinho’s heuristic flagged the coarse key in my first run: average reuse per lesson was 0.93, below 1. After the renew fix it rose to 1.07, just over the line, while the coarse key was still refusing good lessons 9 times. So in a run this small, average reuse is a weak signal. Counting refusals by reason was the better one, and that’s why the store logs every refusal.The catch with the precise key is that a person has to name the dependencies. In my script, the reviewer picked them sensibly. In real life, someone will tie a lesson about central package management to Directory.Packages.props, and every version bump will kill it.6. Most repeated mistakes weren’t about lifecycle at allFor the Beacon-like design, I logged why each repeated mistake happened when nothing was retrieved: 10 times the lesson existed and was approved but didn’t make the top 3 above the cut, once it was waiting for review, once it hadn’t been captured. The retrieval check run at top 5 cut that design’s repeated mistakes from 45.2% to 19.4%. With a weak embedding model, retrieval quality dominated everything I was trying to measure. With nomic-embed-text I'd expect fewer misses, but I haven't measured it.About the sample sizeI want to be specific about how little this is:44 trap encounters, 31 of them repeat opportunities. One encounter moves the repeated-mistake rate by 3.2 points.8 post-change encounters. One encounter moves the stale-hit rate by 12.5 points.4 wrong candidates, 2 of them approved.One scripted agent that always follows the most relevant item, one reviewer that is a rule, one weak embedding model, one similarity cut chosen in advance and one checked afterwards.None of the differences in the table are statistically meaningful. What I’d trust are the mechanisms: the correction turn scoring 0.28 against the rewritten lesson’s 0.46, the expired-duplicate bug, the renewal that briefly revived a stale lesson, the coarse key refusing lessons over a package bump. Each of those is a thing I can point to in the log, and each would happen at any sample size.Design by failure modeMy summary, combining the run with what the four sources say about themselves:design repeated wrong-lesson stale-hit main way it fails mistakes rate rate (top 3) (top 3) (top 3)---------------------------- ----------- ------------- ----------- ------------------------------------------full transcript, searchable 100.0% n/a 0.0% corrections are phrased as reactions and(Agent Framework shape) rank below the failure and the taskevery turn + last 6 77.4% 0.0% 12.5% context grows with every turn; works on(GoodMem chat API shape) recency, not relevanceseen.md 22.6%-25.8% 5.9%-26.5% 25%-100% no supersession: the reader decides what is current, and the file leaks across rolesapproval only (Beacon-like) 45.2% 4.8% 37.5% approved lessons never go stale on their own; coincidental fixes pass reviewapproval + expiry 51.6% 5.6% 25.0% time is a bad proxy for change: kills good lessons, misses fast changesapproval + expiry + 67.7% 0.0% 0.0% over-invalidates on any build file changecoarse keyapproval + expiry + 51.6% 6.2% 0.0% depends on a person naming the right files;precise key renewal must snapshot the key at captureWhat I’m keeping, and what I still don’t knowWhat I’m keeping in my own setup:A human gate, but I now think of it as an editing step as much as a filter. The rewrite into a lesson with a title that names the situation is what made retrieval work.A dependency key per lesson, named by the reviewer, checked on every read. It stopped stale lessons without the cost of expiry.Expiry only as a long backstop (I’m going to try 90 days for everything), not as the main invalidation.Renew on duplicate, with the fingerprint captured from the session that produced the evidence.A refusal log with reasons. It found the bug in this run.Permission scopes in both directions, which I haven’t designed yet.What I still don’t know:How these numbers change with nomic-embed-text and a real model that sometimes ignores its context.How to catch coincidental fixes. My best idea is to require that the “after” evidence is the same check that failed, rerun, not just any passing step, but W-CLEAN would have passed that too.Whether Beacon has an expiry or invalidation mechanism I didn’t find. If it does, I’d like to read how it decides.Whether a reviewer will keep doing weekly reviews for six months. Every gated design depends on that, and nothing in this run tests it.SourcesBeacon site (vendor; capture, dreaming, reuse): https://beacon.shBeacon repository (Asymptote Labs): https://github.com/Asymptote-Labs/agent-beaconBeacon memory distill skill (candidate lifecycle, evaluator sends trace data over the network): https://raw.githubusercontent.com/Asymptote-Labs/agent-beacon/383bd28ec0d99ccbbd35ee1b8a3c768a11fc37d2/agent-skills/skills/beacon-memory-distill/SKILL.mdBeacon memory recall skill (approved memory is reviewed by a person): https://raw.githubusercontent.com/Asymptote-Labs/agent-beacon/383bd28ec0d99ccbbd35ee1b8a3c768a11fc37d2/agent-skills/skills/beacon-memory-recall/SKILL.mdBeacon PR #656, reviewer-written lesson text: https://github.com/Asymptote-Labs/agent-beacon/pull/656Beacon PR #992, regeneration resetting reviewed candidates: https://github.com/Asymptote-Labs/agent-beacon/pull/992Microsoft, “Vector stores in Agent Framework for Python” (VectorStoreHistoryProvider, APIs experimental): https://devblogs.microsoft.com/agent-framework/vector-stores-in-python-agent-framework-familiar-foundations-streamlined-for-agents/Mukesh Murugan, “RAG in ASP.NET Core (.NET 10): A Chat API That Remembers” (sponsored by GoodMem; author-run numbers): https://codewithmukesh.com/blog/rag-in-aspnet-core/Sample repository for that post: https://github.com/iammukeshm/rag-in-aspnet-coreClaude Code cloud sessions documentation: https://code.claude.com/docs/en/claude-code-on-the-webJaroslaw Wasowski, “Harness Ownership: Skills, Hooks, Instruction Files, and the Harness-Team Anti-Pattern”: https://levelup.gitconnected.com/harness-engineering-harness-ownership-skills-hooks-instruction-files-and-the-harness-team-c9ad55d8bdfdRealinho, “Caching and memoizing agent results for ODC and O11”: https://medium.com/itnext/caching-and-memoizing-agent-results-for-odc-and-o11-436d87096db7WordLlama (the embedding model used in my run): https://github.com/dleemiller/WordLlamaTags: AI Agents, Agent Memory, LLM Engineering, DotNet, CSharp, SQLite, Ollama, Developer Tools, Claude Code, Software EngineeringMemory That Learns From Mistakes, With a Human Gate and an Expiry Date was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.