lesson-memory 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ """lesson-memory: verified lesson memory for coding agents.
2
+
3
+ Store the cause of a failure, not the code that fixed it.
4
+
5
+ from lesson_memory import Memory
6
+
7
+ mem = Memory(path="lessons.jsonl", form="rule")
8
+ mem.admit("bug_14", candidate, rule="bounds must exclude the last index",
9
+ test=my_test_function)
10
+ print(mem.prompt_block("fix the search function"))
11
+ """
12
+ from .memory import Memory, Lesson
13
+ from .redact import redact, contains_secret
14
+ from .verify import pytest_verifier
15
+ from .measure import measure_csv, exposure, retention
16
+
17
+ __version__ = "0.1.0"
18
+ __all__ = [
19
+ "Memory", "Lesson", "redact", "contains_secret",
20
+ "pytest_verifier", "measure_csv", "exposure", "retention",
21
+ ]
lesson_memory/cli.py ADDED
@@ -0,0 +1,91 @@
1
+ """Command line interface: lesson measure | reproduce | check."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import glob
6
+ import json
7
+ import os
8
+ import sys
9
+
10
+ from .measure import measure_csv
11
+ from .verify import pytest_verifier
12
+
13
+
14
+ def _fmt(policy: str, m: dict) -> str:
15
+ return (f"{policy:<16} {m['success']:>6.2f} {m['attempts']:>9.2f} "
16
+ f"{m['retained']:>9.2f} {m['exposed']:>8.2f}")
17
+
18
+
19
+ def cmd_measure(args) -> int:
20
+ header = f"{'policy':<16} {'success':>6} {'attempts':>9} {'retained':>9} {'exposed':>8}"
21
+ for path in args.files:
22
+ print(f"\n{os.path.basename(path)}")
23
+ print(header)
24
+ print("-" * len(header))
25
+ for policy, m in measure_csv(path).items():
26
+ print(_fmt(policy, m))
27
+ return 0
28
+
29
+
30
+ def cmd_check(args) -> int:
31
+ """Confirm a task is well formed: the solution passes, the buggy file fails."""
32
+ task_dir = args.task_dir
33
+ verify = pytest_verifier(task_dir)
34
+ sol = os.path.join(task_dir, "solution.py")
35
+ bug = os.path.join(task_dir, "buggy.py")
36
+ if not os.path.exists(sol):
37
+ print(f"no solution.py in {task_dir}", file=sys.stderr)
38
+ return 2
39
+ ok_solution = verify(open(sol, encoding="utf-8").read())
40
+ ok_buggy = verify(open(bug, encoding="utf-8").read()) if os.path.exists(bug) else False
41
+ print(f"solution passes : {ok_solution}")
42
+ print(f"buggy fails : {not ok_buggy}")
43
+ return 0 if (ok_solution and not ok_buggy) else 1
44
+
45
+
46
+ def cmd_reproduce(args) -> int:
47
+ """Recompute the headline numbers from the bundled result files."""
48
+ here = os.path.dirname(os.path.abspath(__file__))
49
+ # bundled inside the installed package when pip-installed; in the repo
50
+ # checkout the files sit one level up, so try both
51
+ data = os.path.join(here, "data", "results")
52
+ files = sorted(glob.glob(os.path.join(data, "*.csv")))
53
+ if not files:
54
+ data = os.path.join(os.path.dirname(here), "data", "results")
55
+ files = sorted(glob.glob(os.path.join(data, "*.csv")))
56
+ if not files:
57
+ print("no result files found", file=sys.stderr)
58
+ return 2
59
+ print("Recomputing from bundled results\n" + "=" * 60)
60
+ for path in files:
61
+ summary = measure_csv(path)
62
+ name = os.path.basename(path).replace(".csv", "")
63
+ print(f"\n{name}")
64
+ for policy, m in summary.items():
65
+ print(" " + _fmt(policy, m))
66
+ return 0
67
+
68
+
69
+ def main(argv=None) -> int:
70
+ p = argparse.ArgumentParser(
71
+ prog="lesson",
72
+ description="Verified lesson memory: store the cause, not the code.")
73
+ sub = p.add_subparsers(dest="cmd", required=True)
74
+
75
+ m = sub.add_parser("measure", help="summarise one or more result files")
76
+ m.add_argument("files", nargs="+")
77
+ m.set_defaults(func=cmd_measure)
78
+
79
+ c = sub.add_parser("check", help="verify a task: solution passes, buggy fails")
80
+ c.add_argument("task_dir")
81
+ c.set_defaults(func=cmd_check)
82
+
83
+ r = sub.add_parser("reproduce", help="recompute the paper's headline numbers")
84
+ r.set_defaults(func=cmd_reproduce)
85
+
86
+ args = p.parse_args(argv)
87
+ return args.func(args)
88
+
89
+
90
+ if __name__ == "__main__":
91
+ raise SystemExit(main())
@@ -0,0 +1,13 @@
1
+ policy,privacy_level,seed,task,family,instance,success,attempts,calls,memory_size,secrets_retained,exposed_via_memory,exposed_via_input,secrets_total
2
+ A_no_memory,0,0,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
3
+ A_no_memory,0,0,debug_10,loop_bounds,2,0,3,3,0,0,0,2,2
4
+ A_no_memory,0,1,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
5
+ A_no_memory,0,1,debug_10,loop_bounds,2,0,3,3,0,0,0,2,2
6
+ A_no_memory,0,2,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
7
+ A_no_memory,0,2,debug_10,loop_bounds,2,0,3,3,0,0,0,2,2
8
+ C_validated,0,0,debug_01,loop_bounds,1,1,1,1,1,0,0,2,2
9
+ C_validated,0,0,debug_10,loop_bounds,2,0,3,3,1,0,0,2,2
10
+ C_validated,0,1,debug_01,loop_bounds,1,1,1,1,1,0,0,2,2
11
+ C_validated,0,1,debug_10,loop_bounds,2,0,3,3,1,0,0,2,2
12
+ C_validated,0,2,debug_01,loop_bounds,1,1,1,1,1,0,0,2,2
13
+ C_validated,0,2,debug_10,loop_bounds,2,0,3,3,1,0,0,2,2
@@ -0,0 +1,13 @@
1
+ policy,privacy_level,seed,task,family,instance,success,attempts,calls,memory_size,secrets_retained,exposed_via_memory,exposed_via_input,secrets_total
2
+ A_no_memory,0,0,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
3
+ A_no_memory,0,0,debug_10,loop_bounds,2,0,3,3,0,0,0,2,2
4
+ A_no_memory,0,1,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
5
+ A_no_memory,0,1,debug_10,loop_bounds,2,0,3,3,0,0,0,2,2
6
+ A_no_memory,0,2,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
7
+ A_no_memory,0,2,debug_10,loop_bounds,2,0,3,3,0,0,0,2,2
8
+ C_validated,0,0,debug_01,loop_bounds,1,1,1,1,1,1,1,2,2
9
+ C_validated,0,0,debug_10,loop_bounds,2,0,3,3,1,1,1,2,2
10
+ C_validated,0,1,debug_01,loop_bounds,1,1,1,1,1,1,1,2,2
11
+ C_validated,0,1,debug_10,loop_bounds,2,0,3,3,1,1,1,2,2
12
+ C_validated,0,2,debug_01,loop_bounds,1,1,1,1,1,1,1,2,2
13
+ C_validated,0,2,debug_10,loop_bounds,2,0,3,3,1,1,1,2,2
@@ -0,0 +1,13 @@
1
+ policy,privacy_level,seed,task,family,instance,success,attempts,calls,memory_size,secrets_retained,exposed_via_memory,exposed_via_input,secrets_total
2
+ A_no_memory,0,0,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
3
+ A_no_memory,0,0,debug_10,loop_bounds,2,1,1,1,0,0,0,2,2
4
+ A_no_memory,0,1,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
5
+ A_no_memory,0,1,debug_10,loop_bounds,2,1,1,1,0,0,0,2,2
6
+ A_no_memory,0,2,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
7
+ A_no_memory,0,2,debug_10,loop_bounds,2,1,1,1,0,0,0,2,2
8
+ C_validated,0,0,debug_01,loop_bounds,1,1,1,1,1,0,0,2,2
9
+ C_validated,0,0,debug_10,loop_bounds,2,1,1,1,2,0,0,2,2
10
+ C_validated,0,1,debug_01,loop_bounds,1,1,1,1,1,0,0,2,2
11
+ C_validated,0,1,debug_10,loop_bounds,2,1,1,1,2,0,0,2,2
12
+ C_validated,0,2,debug_01,loop_bounds,1,1,1,1,1,0,0,2,2
13
+ C_validated,0,2,debug_10,loop_bounds,2,1,1,1,2,0,0,2,2
@@ -0,0 +1,13 @@
1
+ policy,privacy_level,seed,task,family,instance,success,attempts,calls,memory_size,secrets_retained,exposed_via_memory,exposed_via_input,secrets_total
2
+ A_no_memory,0,0,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
3
+ A_no_memory,0,0,debug_10,loop_bounds,2,1,1,1,0,0,0,2,2
4
+ A_no_memory,0,1,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
5
+ A_no_memory,0,1,debug_10,loop_bounds,2,1,1,1,0,0,0,2,2
6
+ A_no_memory,0,2,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
7
+ A_no_memory,0,2,debug_10,loop_bounds,2,1,1,1,0,0,0,2,2
8
+ C_validated,0,0,debug_01,loop_bounds,1,1,1,1,1,1,1,2,2
9
+ C_validated,0,0,debug_10,loop_bounds,2,0,3,3,1,1,1,2,2
10
+ C_validated,0,1,debug_01,loop_bounds,1,1,1,1,1,1,1,2,2
11
+ C_validated,0,1,debug_10,loop_bounds,2,0,3,3,1,1,1,2,2
12
+ C_validated,0,2,debug_01,loop_bounds,1,1,1,1,1,1,1,2,2
13
+ C_validated,0,2,debug_10,loop_bounds,2,0,3,3,1,1,1,2,2
@@ -0,0 +1,13 @@
1
+ policy,privacy_level,seed,task,family,instance,success,attempts,calls,memory_size,secrets_retained,exposed_via_memory,exposed_via_input,secrets_total
2
+ A_no_memory,0,0,debug_02,shared_state,1,1,2,2,0,0,0,2,2
3
+ A_no_memory,0,0,debug_06,shared_state,2,1,3,3,0,0,0,2,2
4
+ A_no_memory,0,1,debug_02,shared_state,1,1,1,1,0,0,0,2,2
5
+ A_no_memory,0,1,debug_06,shared_state,2,1,3,3,0,0,0,2,2
6
+ A_no_memory,0,2,debug_02,shared_state,1,1,2,2,0,0,0,2,2
7
+ A_no_memory,0,2,debug_06,shared_state,2,1,1,1,0,0,0,2,2
8
+ C_validated,0,0,debug_02,shared_state,1,1,3,3,1,0,0,2,2
9
+ C_validated,0,0,debug_06,shared_state,2,0,3,3,1,0,0,2,2
10
+ C_validated,0,1,debug_02,shared_state,1,1,1,1,1,0,0,2,2
11
+ C_validated,0,1,debug_06,shared_state,2,1,3,3,2,0,0,2,2
12
+ C_validated,0,2,debug_02,shared_state,1,1,2,2,1,0,0,2,2
13
+ C_validated,0,2,debug_06,shared_state,2,1,1,1,2,0,0,2,2
@@ -0,0 +1,13 @@
1
+ policy,privacy_level,seed,task,family,instance,success,attempts,calls,memory_size,secrets_retained,exposed_via_memory,exposed_via_input,secrets_total
2
+ A_no_memory,0,0,debug_02,shared_state,1,1,3,3,0,0,0,2,2
3
+ A_no_memory,0,0,debug_06,shared_state,2,1,1,1,0,0,0,2,2
4
+ A_no_memory,0,1,debug_02,shared_state,1,1,1,1,0,0,0,2,2
5
+ A_no_memory,0,1,debug_06,shared_state,2,1,1,1,0,0,0,2,2
6
+ A_no_memory,0,2,debug_02,shared_state,1,0,3,3,0,0,0,2,2
7
+ A_no_memory,0,2,debug_06,shared_state,2,1,1,1,0,0,0,2,2
8
+ C_validated,0,0,debug_02,shared_state,1,1,1,1,1,1,1,2,2
9
+ C_validated,0,0,debug_06,shared_state,2,0,3,3,1,1,1,2,2
10
+ C_validated,0,1,debug_02,shared_state,1,0,3,3,0,1,0,2,2
11
+ C_validated,0,1,debug_06,shared_state,2,1,1,1,1,1,0,2,2
12
+ C_validated,0,2,debug_02,shared_state,1,0,3,3,0,0,0,2,2
13
+ C_validated,0,2,debug_06,shared_state,2,0,3,3,0,0,0,2,2
@@ -0,0 +1,13 @@
1
+ policy,privacy_level,seed,task,family,instance,success,attempts,calls,memory_size,secrets_retained,exposed_via_memory,exposed_via_input,secrets_total
2
+ A_no_memory,0,0,debug_11,type_coercion,1,1,1,1,0,0,0,2,2
3
+ A_no_memory,0,0,debug_07,type_coercion,2,1,1,1,0,0,0,2,2
4
+ A_no_memory,0,1,debug_11,type_coercion,1,1,1,1,0,0,0,2,2
5
+ A_no_memory,0,1,debug_07,type_coercion,2,0,3,3,0,0,0,2,2
6
+ A_no_memory,0,2,debug_11,type_coercion,1,1,1,1,0,0,0,2,2
7
+ A_no_memory,0,2,debug_07,type_coercion,2,0,3,3,0,0,0,2,2
8
+ C_validated,0,0,debug_11,type_coercion,1,1,1,1,1,0,0,2,2
9
+ C_validated,0,0,debug_07,type_coercion,2,1,1,1,2,0,0,2,2
10
+ C_validated,0,1,debug_11,type_coercion,1,1,1,1,1,0,0,2,2
11
+ C_validated,0,1,debug_07,type_coercion,2,1,1,1,2,0,0,2,2
12
+ C_validated,0,2,debug_11,type_coercion,1,1,1,1,1,0,0,2,2
13
+ C_validated,0,2,debug_07,type_coercion,2,1,1,1,2,0,0,2,2
@@ -0,0 +1,13 @@
1
+ policy,privacy_level,seed,task,family,instance,success,attempts,calls,memory_size,secrets_retained,exposed_via_memory,exposed_via_input,secrets_total
2
+ A_no_memory,0,0,debug_11,type_coercion,1,1,1,1,0,0,0,2,2
3
+ A_no_memory,0,0,debug_07,type_coercion,2,1,1,1,0,0,0,2,2
4
+ A_no_memory,0,1,debug_11,type_coercion,1,1,1,1,0,0,0,2,2
5
+ A_no_memory,0,1,debug_07,type_coercion,2,1,1,1,0,0,0,2,2
6
+ A_no_memory,0,2,debug_11,type_coercion,1,1,1,1,0,0,0,2,2
7
+ A_no_memory,0,2,debug_07,type_coercion,2,0,3,3,0,0,0,2,2
8
+ C_validated,0,0,debug_11,type_coercion,1,1,1,1,1,2,1,2,2
9
+ C_validated,0,0,debug_07,type_coercion,2,1,2,2,2,2,1,2,2
10
+ C_validated,0,1,debug_11,type_coercion,1,1,1,1,1,2,1,2,2
11
+ C_validated,0,1,debug_07,type_coercion,2,1,1,1,2,2,1,2,2
12
+ C_validated,0,2,debug_11,type_coercion,1,1,1,1,1,2,1,2,2
13
+ C_validated,0,2,debug_07,type_coercion,2,1,2,2,2,2,1,2,2
@@ -0,0 +1,13 @@
1
+ policy,privacy_level,seed,task,family,instance,success,attempts,calls,memory_size,secrets_retained,exposed_via_memory,exposed_via_input,secrets_total
2
+ A_no_memory,0,0,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
3
+ A_no_memory,0,0,debug_10,loop_bounds,2,1,1,1,0,0,0,2,2
4
+ A_no_memory,0,1,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
5
+ A_no_memory,0,1,debug_10,loop_bounds,2,1,1,1,0,0,0,2,2
6
+ A_no_memory,0,2,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
7
+ A_no_memory,0,2,debug_10,loop_bounds,2,1,3,3,0,0,0,2,2
8
+ C_validated,0,0,debug_01,loop_bounds,1,1,1,1,1,1,0,2,2
9
+ C_validated,0,0,debug_10,loop_bounds,2,1,2,2,2,1,0,2,2
10
+ C_validated,0,1,debug_01,loop_bounds,1,1,1,1,1,1,0,2,2
11
+ C_validated,0,1,debug_10,loop_bounds,2,1,1,1,2,1,0,2,2
12
+ C_validated,0,2,debug_01,loop_bounds,1,1,1,1,1,1,0,2,2
13
+ C_validated,0,2,debug_10,loop_bounds,2,1,2,2,2,1,0,2,2
@@ -0,0 +1,13 @@
1
+ policy,privacy_level,seed,task,family,instance,success,attempts,calls,memory_size,secrets_retained,exposed_via_memory,exposed_via_input,secrets_total
2
+ A_no_memory,0,0,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
3
+ A_no_memory,0,0,debug_10,loop_bounds,2,1,2,2,0,0,0,2,2
4
+ A_no_memory,0,1,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
5
+ A_no_memory,0,1,debug_10,loop_bounds,2,1,1,1,0,0,0,2,2
6
+ A_no_memory,0,2,debug_01,loop_bounds,1,1,1,1,0,0,0,2,2
7
+ A_no_memory,0,2,debug_10,loop_bounds,2,1,3,3,0,0,0,2,2
8
+ C_validated,0,0,debug_01,loop_bounds,1,1,1,1,1,1,1,2,2
9
+ C_validated,0,0,debug_10,loop_bounds,2,0,3,3,1,1,1,2,2
10
+ C_validated,0,1,debug_01,loop_bounds,1,1,1,1,1,1,1,2,2
11
+ C_validated,0,1,debug_10,loop_bounds,2,0,3,3,1,1,1,2,2
12
+ C_validated,0,2,debug_01,loop_bounds,1,1,1,1,1,1,1,2,2
13
+ C_validated,0,2,debug_10,loop_bounds,2,0,3,3,1,1,1,2,2
@@ -0,0 +1,49 @@
1
+ """Measure the two privacy outcomes separately.
2
+
3
+ Retention: is the item still in the store?
4
+ Exposure: is the item reaching the prompt through a retrieved record?
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import csv
9
+ from collections import defaultdict
10
+ from typing import Iterable
11
+
12
+ from .redact import contains_secret
13
+
14
+
15
+ def exposure(record_texts: Iterable[str], secret: str) -> bool:
16
+ """True if the planted item appears in any record text."""
17
+ return any(contains_secret(t, secret) for t in record_texts)
18
+
19
+
20
+ def retention(stored_code: Iterable[str], secret: str) -> bool:
21
+ """True if the planted item is held anywhere in the store, including code."""
22
+ return any(contains_secret(c, secret) for c in stored_code if c)
23
+
24
+
25
+ def measure_csv(path: str) -> dict:
26
+ """Summarise a result file written by ``lesson run``.
27
+
28
+ Expected columns: policy, success, attempts, and either retained/exposed or
29
+ secrets_retained/exposed_via_memory (the harness column names).
30
+ Returns {policy: {success, attempts, retained, exposed, n}}
31
+ """
32
+ agg = defaultdict(lambda: {"success": 0.0, "attempts": 0.0,
33
+ "retained": 0.0, "exposed": 0.0, "n": 0})
34
+ def pick(row, *names):
35
+ for n in names:
36
+ if n in row and row[n] not in ("", None):
37
+ return float(row[n])
38
+ return 0.0
39
+
40
+ with open(path, newline="", encoding="utf-8") as f:
41
+ for row in csv.DictReader(f):
42
+ a = agg[row["policy"]]
43
+ a["success"] += pick(row, "success")
44
+ a["attempts"] += pick(row, "attempts")
45
+ a["retained"] += pick(row, "retained", "secrets_retained")
46
+ a["exposed"] += pick(row, "exposed", "exposed_via_memory")
47
+ a["n"] += 1
48
+ return {p: {k: (round(v / a["n"], 2) if k != "n" else v) for k, v in a.items()}
49
+ for p, a in agg.items()}
@@ -0,0 +1,135 @@
1
+ """The memory itself: admission, storage, retrieval."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ import time
8
+ from dataclasses import dataclass, field, asdict
9
+ from typing import Callable, Iterable, Optional
10
+
11
+ from .redact import redact
12
+
13
+ FORMS = ("rule", "code", "both")
14
+
15
+
16
+ @dataclass
17
+ class Lesson:
18
+ """One admitted lesson."""
19
+ task_id: str
20
+ text: str
21
+ form: str = "rule"
22
+ verified: bool = True
23
+ created: float = field(default_factory=time.time)
24
+ code: Optional[str] = None
25
+
26
+ def to_dict(self) -> dict:
27
+ return asdict(self)
28
+
29
+ @classmethod
30
+ def from_dict(cls, d: dict) -> "Lesson":
31
+ return cls(**d)
32
+
33
+
34
+ class Memory:
35
+ """A lesson store with verifier-gated admission.
36
+
37
+ Parameters
38
+ ----------
39
+ path : optional path to a JSONL file used for persistence.
40
+ form : what an admitted lesson contains.
41
+ "rule" - the stated root cause only (default, recommended)
42
+ "code" - the root cause plus the candidate's first lines
43
+ "both" - keep the rule in text and the code in a separate field
44
+ redact_level : 0-4, applied to every lesson before it is stored.
45
+ keep_code : store the candidate source in ``Lesson.code``. Set False to
46
+ guarantee nothing from the task's code can be retained.
47
+ """
48
+
49
+ def __init__(self, path: Optional[str] = None, form: str = "rule",
50
+ redact_level: int = 1, keep_code: bool = False):
51
+ if form not in FORMS:
52
+ raise ValueError(f"form must be one of {FORMS}")
53
+ self.path = path
54
+ self.form = form
55
+ self.redact_level = redact_level
56
+ self.keep_code = keep_code and form in ("code", "both")
57
+ self.lessons: list[Lesson] = []
58
+ if path and os.path.exists(path):
59
+ self.load()
60
+
61
+ # ---------------------------------------------------------------- admission
62
+ def admit(self, task_id: str, candidate: str, *, rule: Optional[str] = None,
63
+ test: Optional[Callable[[str], bool]] = None,
64
+ verified: Optional[bool] = None) -> bool:
65
+ """Admit a lesson only if the candidate is verified.
66
+
67
+ Exactly one of ``test`` or ``verified`` decides success. If ``test`` is
68
+ given it is called with the candidate source; the model is never asked
69
+ whether it succeeded.
70
+ """
71
+ if test is not None:
72
+ verified = bool(test(candidate))
73
+ if verified is None:
74
+ raise ValueError("pass either test= or verified=")
75
+ if not verified:
76
+ return False
77
+
78
+ body = (rule or "").strip()
79
+ if not body and self.form == "rule":
80
+ raise ValueError("form='rule' needs a rule= describing the root cause")
81
+
82
+ if self.form == "code":
83
+ snippet = "\n".join((candidate or "").splitlines()[:3])
84
+ text = f"{body}\n\n{candidate or ''}".strip() if not body else f"{body}\n\n{snippet}"
85
+ else:
86
+ text = body
87
+
88
+ lesson = Lesson(
89
+ task_id=task_id,
90
+ text=redact(text, self.redact_level),
91
+ form=self.form,
92
+ verified=True,
93
+ code=(candidate if self.keep_code else None),
94
+ )
95
+ self.lessons.append(lesson)
96
+ self.save()
97
+ return True
98
+
99
+ # ---------------------------------------------------------------- retrieval
100
+ def recall(self, query: str, k: int = 1) -> list[Lesson]:
101
+ """Return up to k lessons, ranked by word overlap with the query."""
102
+ words = lambda s: set(re.findall(r"[a-z]{3,}", (s or "").lower()))
103
+ q = words(query)
104
+ scored = [(len(q & words(l.text)), l) for l in self.lessons]
105
+ scored = [(s, l) for s, l in scored if s > 0]
106
+ scored.sort(key=lambda p: -p[0])
107
+ return [l for _, l in scored[:k]]
108
+
109
+ def prompt_block(self, query: str, k: int = 1) -> str:
110
+ """A delimited block ready to paste into a prompt."""
111
+ picked = self.recall(query, k)
112
+ if not picked:
113
+ return ""
114
+ lines = "\n".join(f"- {l.text}" for l in picked)
115
+ return f"<lessons>\n{lines}\n</lessons>"
116
+
117
+ # ---------------------------------------------------------------- plumbing
118
+ def save(self) -> None:
119
+ if not self.path:
120
+ return
121
+ d = os.path.dirname(os.path.abspath(self.path))
122
+ os.makedirs(d, exist_ok=True)
123
+ with open(self.path, "w", encoding="utf-8") as f:
124
+ for l in self.lessons:
125
+ f.write(json.dumps(l.to_dict()) + "\n")
126
+
127
+ def load(self) -> None:
128
+ with open(self.path, encoding="utf-8") as f:
129
+ self.lessons = [Lesson.from_dict(json.loads(line)) for line in f if line.strip()]
130
+
131
+ def __len__(self) -> int:
132
+ return len(self.lessons)
133
+
134
+ def __iter__(self) -> Iterable[Lesson]:
135
+ return iter(self.lessons)
@@ -0,0 +1,42 @@
1
+ """Graded redaction: levels 1-4, each a superset of the one below."""
2
+ import re
3
+
4
+ PATTERNS = {
5
+ 1: [
6
+ (r"\b[A-Za-z0-9_\-]*(?:api[_-]?key|token|secret|password)\s*[:=]\s*\S+", "[REDACTED_CREDENTIAL]"),
7
+ (r"\b[\w.+-]+@[\w-]+\.[\w.]+\b", "[REDACTED_EMAIL]"),
8
+ (r"\bsk-[A-Za-z0-9\-]{8,}\b", "[REDACTED_KEY]"),
9
+ ],
10
+ 2: [
11
+ (r"\b(?:\+91[\s-]?)?[6-9]\d{9}\b", "[REDACTED_PHONE]"),
12
+ (r"\b\d{4}[\s-]?\d{4}[\s-]?\d{4}\b", "[REDACTED_ID]"),
13
+ (r"\b(?:\d[ -]*?){13,16}\b", "[REDACTED_CARD]"),
14
+ ],
15
+ 3: [
16
+ (r"\b(?:Mr|Mrs|Ms|Dr)\.?\s+[A-Z][a-z]+(?:\s+[A-Z][a-z]+)?", "[REDACTED_NAME]"),
17
+ (r"\b[A-Z][a-z]+\s+(?:Nagar|Colony|Road|Street|Layout)\b", "[REDACTED_ADDRESS]"),
18
+ ],
19
+ 4: [
20
+ (r"(?:[A-Za-z]:\\|/)[\w./\\-]{6,}", "[REDACTED_PATH]"),
21
+ (r"\b\d{4,}\b", "[REDACTED_NUMBER]"),
22
+ ],
23
+ }
24
+
25
+
26
+ def redact(text: str, level: int = 1) -> str:
27
+ """Apply every pattern up to and including ``level``."""
28
+ if not text or level <= 0:
29
+ return text
30
+ out = text
31
+ for lvl in range(1, level + 1):
32
+ for pattern, repl in PATTERNS.get(lvl, []):
33
+ out = re.sub(pattern, repl, out, flags=re.IGNORECASE)
34
+ return out
35
+
36
+
37
+ def contains_secret(text: str, secret: str) -> bool:
38
+ """Normalised containment: whitespace and punctuation changes do not hide a leak."""
39
+ if not text or not secret:
40
+ return False
41
+ norm = lambda s: re.sub(r"[^a-z0-9]", "", s.lower())
42
+ return norm(secret) in norm(text)
@@ -0,0 +1,36 @@
1
+ """Verification helpers: success is decided by running tests, never by the model."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ import tempfile
8
+ from typing import Callable
9
+
10
+
11
+ def pytest_verifier(task_dir: str, filename: str = "buggy.py",
12
+ timeout: int = 60) -> Callable[[str], bool]:
13
+ """Return a callable that writes a candidate into a scratch copy of
14
+ ``task_dir`` and runs pytest there.
15
+
16
+ The candidate never touches the original task directory.
17
+ """
18
+ def verify(candidate: str) -> bool:
19
+ work = tempfile.mkdtemp(prefix="lesson_verify_")
20
+ try:
21
+ target = os.path.join(work, "task")
22
+ shutil.copytree(task_dir, target)
23
+ with open(os.path.join(target, filename), "w", encoding="utf-8") as f:
24
+ f.write(candidate)
25
+ proc = subprocess.run(
26
+ ["python", "-m", "pytest", "-q", "--no-header"],
27
+ cwd=target, capture_output=True, text=True, timeout=timeout,
28
+ )
29
+ return proc.returncode == 0
30
+ except subprocess.TimeoutExpired:
31
+ return False
32
+ except Exception:
33
+ return False
34
+ finally:
35
+ shutil.rmtree(work, ignore_errors=True)
36
+ return verify
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: lesson-memory
3
+ Version: 0.1.0
4
+ Summary: Verified lesson memory for coding agents: store the cause, not the code.
5
+ Author: Huligesh D Hosamani Pavar
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Huligeshdh/lesson-memory
8
+ Keywords: agents,memory,llm,privacy,verification
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: pytest>=7
15
+ Dynamic: license-file
16
+
17
+ # lesson-memory
18
+
19
+ **Store the cause of a failure, not the code that fixed it.**
20
+
21
+ When a coding agent fails a task and later succeeds, most memory systems save the
22
+ working code and feed it back next time. On a different task that code can be
23
+ actively harmful: the model copies a pattern that does not apply, and solves
24
+ *fewer* tasks than an agent with no memory at all.
25
+
26
+ `lesson-memory` saves one sentence instead — the stated root cause — and admits a
27
+ lesson **only** when a test suite confirms the fix. The result, measured across
28
+ five models from three families, is that the abstract lesson never hurt
29
+ performance and retained no sensitive data, while the code lesson cost up to 50
30
+ points of solved rate and carried planted credentials into the store.
31
+
32
+ Paper: *Does a Lesson Need the Code? Record Form, Transfer and Retention in
33
+ Verified Agent Memory*.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ pip install lesson-memory
39
+ ```
40
+
41
+ ## Use
42
+
43
+ ```python
44
+ from lesson_memory import Memory, pytest_verifier
45
+
46
+ mem = Memory(path="lessons.jsonl", form="rule")
47
+
48
+ # admit() only stores when the tests pass - the model is never asked
49
+ mem.admit(
50
+ task_id="bug_14",
51
+ candidate=fixed_source,
52
+ rule="Bounds must exclude the last index; range(len(x) - 1) skips it.",
53
+ test=pytest_verifier("tasks/debug_01"),
54
+ )
55
+
56
+ block = mem.prompt_block("fix the loop that skips the last element")
57
+ # <lessons>
58
+ # - Bounds must exclude the last index; range(len(x) - 1) skips it.
59
+ # </lessons>
60
+ ```
61
+
62
+ ## The two forms
63
+
64
+ | form | what is stored | measured effect |
65
+ |---|---|---|
66
+ | `"rule"` | the stated root cause only | never harmful; 0 items retained |
67
+ | `"code"` | the root cause plus the fix | up to −50 points solved rate; carries credentials |
68
+
69
+ `form="both"` keeps the rule in the text and the code in a separate field, so you
70
+ can drop the code at retrieval time.
71
+
72
+ ## Measure the two privacy outcomes separately
73
+
74
+ Retention (is it still in the store?) and exposure (does it reach the prompt?)
75
+ are different questions, and a filter over the lesson text only addresses the
76
+ second one.
77
+
78
+ ```python
79
+ from lesson_memory import exposure, retention
80
+
81
+ exposure([lesson.text for lesson in mem], "+91 98765 43210") # -> False
82
+ retention([lesson.code for lesson in mem], "+91 98765 43210") # -> False
83
+ ```
84
+
85
+ ## Command line
86
+
87
+ ```bash
88
+ lesson check tasks/debug_01 # solution passes, buggy file fails
89
+ lesson measure data/results/arm_rule.csv
90
+ lesson reproduce # recompute the paper's headline numbers
91
+ ```
92
+
93
+ ## Reproducing the paper
94
+
95
+ Every number in Tables 5-7 comes from the result files in `data/results/`.
96
+ Run `lesson reproduce` to recompute them. The task set is in `tasks/`, one
97
+ directory per task, each with a buggy file, a reference solution, tests, the
98
+ family rule and a planted secret.
99
+
100
+ **All planted secrets are synthetic.** They are phone numbers and key-shaped
101
+ strings invented for the experiment, and are safe to publish.
102
+
103
+ ## Licence
104
+
105
+ MIT.
@@ -0,0 +1,22 @@
1
+ lesson_memory/__init__.py,sha256=bKK9_qyGO7zz5At_AEJAa5Jn9yPZi5k-W9xbafyy05M,706
2
+ lesson_memory/cli.py,sha256=mtA80n8vRdWuh-ajFnhuN6LUTavqdDEISgGE-cSWsAY,3148
3
+ lesson_memory/measure.py,sha256=5UW2QYtctkVpeByufLoJHSQEJQTA49rl7ZDQlMa28bc,1858
4
+ lesson_memory/memory.py,sha256=X-pvTJHu-O3SolHsnddymHvUGpNZE0g7wlxyF7s3gbM,4807
5
+ lesson_memory/redact.py,sha256=IVvRU0z1x7L6Ex-RWbFl8-PTiObI3SdV0WdbZ0NjVG4,1493
6
+ lesson_memory/verify.py,sha256=E0emopVS90oHpO-XJXTXWM0AeeXu7pitXBTQhJAv11w,1277
7
+ lesson_memory/data/results/arm_gemma_rule.csv,sha256=cY7E04t9HIM4E_NktiGk2040hF7--xQwizgiGX7k70Q,823
8
+ lesson_memory/data/results/arm_gemma_snippet.csv,sha256=jFGTfV3IjlqO1yyUZo3bGbWe8o8qAW_Iut9pOa-U1W0,823
9
+ lesson_memory/data/results/arm_llama_rule.csv,sha256=HCq7GzU2jIoRlwxd8LrGzl40mK2ULRxbnJO4c1gZx_A,823
10
+ lesson_memory/data/results/arm_llama_snippet.csv,sha256=oWyxO3FxlEz7xdlmbdXq750yUUpTOJROahjEYy9OVlI,823
11
+ lesson_memory/data/results/arm_q15_rule.csv,sha256=kLboLS7P06XW4TtCDDOzd3QcGwUTLDg45x-VU21iHi0,835
12
+ lesson_memory/data/results/arm_q15_snippet.csv,sha256=ELHm5RtStoUSGfUa4wZsu8VJ0-0WwRdhL6yVJu4UYOA,835
13
+ lesson_memory/data/results/arm_q3g_rule.csv,sha256=tkGbGINk-nYOe43A8NqcFzA9YzFyI-OfKdq2fEAm4Yw,847
14
+ lesson_memory/data/results/arm_q3g_snippet.csv,sha256=m6V9JQB9XlqSrF7LpqahSEHvJy3E_HrjIWyRlxSp3UE,847
15
+ lesson_memory/data/results/arm_rule.csv,sha256=ky61jc-2oro4bQy6aiAGx6iQgfDQNKcDNg-ZjKeChUY,823
16
+ lesson_memory/data/results/arm_snippet.csv,sha256=52HdYXGv2kVwbcTXFGn5H8JJVG7VLh8Xf77RfLsaSsM,823
17
+ lesson_memory-0.1.0.dist-info/licenses/LICENSE,sha256=Z-DdSuzDqcj1IluojUROLI4chduUWv0QMExS_LmAbKc,1077
18
+ lesson_memory-0.1.0.dist-info/METADATA,sha256=x67iNQaSAxgUg3-EYVQWwbx6pkyZe4ODwRIpCL-bK24,3556
19
+ lesson_memory-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
20
+ lesson_memory-0.1.0.dist-info/entry_points.txt,sha256=WdFdhwBmlAUotRDGuBsWzySlpb8FVuibenXU5MYXXaI,50
21
+ lesson_memory-0.1.0.dist-info/top_level.txt,sha256=CVHnGCJ2P-xexmtn425-aQSmqQJzTBCpgviT4693UQs,14
22
+ lesson_memory-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ lesson = lesson_memory.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Huligesh D. Hosamani
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ lesson_memory