agent-memory-mini 0.2.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,3 @@
1
+ """agent-memory-mini: tiny file-based session memory for coding agents."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,490 @@
1
+ """CLI: remember / recall / list / summary / sessions / forget.
2
+
3
+ Usage:
4
+ python -m agent_memory remember "fixed login bug" --tags bug,auth
5
+ python -m agent_memory recall "login bug"
6
+ python -m agent_memory list --limit 10
7
+ python -m agent_memory summary --days 7
8
+ python -m agent_memory count
9
+ python -m agent_memory sessions
10
+ python -m agent_memory forget a1b2c3d4
11
+ python -m agent_memory resolve login.rate_limit --at 2026-12-12 --scope mobile
12
+
13
+ Store: JSONL, default .agent-memory/memory.jsonl in the current directory.
14
+ Override with --store PATH or AGENT_MEMORY_STORE.
15
+ """
16
+
17
+ import argparse
18
+ import csv
19
+ import json
20
+ import os
21
+ import sys
22
+ from datetime import date, datetime, timezone
23
+ from pathlib import Path
24
+
25
+ from . import __version__
26
+ from . import resolve as resolve_mod
27
+ from . import search as search_mod
28
+ from . import store as store_mod
29
+ from . import summary as summary_mod
30
+
31
+ DEFAULT_STORE = Path(".agent-memory") / "memory.jsonl"
32
+
33
+
34
+ def _store_path(args) -> Path:
35
+ env = os.environ.get("AGENT_MEMORY_STORE", "").strip()
36
+ if getattr(args, "store", None):
37
+ return Path(args.store)
38
+ if env:
39
+ return Path(env)
40
+ return DEFAULT_STORE
41
+
42
+
43
+ def _print_json(obj) -> None:
44
+ print(json.dumps(obj, indent=2, ensure_ascii=False))
45
+
46
+
47
+ def _parse_moment(value: str, flag: str) -> str | None:
48
+ """Parse an ISO 8601 datetime or YYYY-MM-DD date (midnight UTC).
49
+
50
+ Returns a normalised ISO 8601 string, or None after printing an error.
51
+ """
52
+ try:
53
+ moment = resolve_mod._parse_moment(value)
54
+ except ValueError:
55
+ print(f"error: {flag} must be an ISO 8601 datetime or YYYY-MM-DD date, "
56
+ f"got {value!r}", file=sys.stderr)
57
+ return None
58
+ return moment.isoformat()
59
+
60
+
61
+ def cmd_remember(args) -> int:
62
+ if args.stdin and args.text is not None:
63
+ print("error: --stdin cannot be used with a text argument", file=sys.stderr)
64
+ return 2
65
+ text = sys.stdin.read().strip() if args.stdin else args.text
66
+ if text is None:
67
+ print("error: remember requires text or --stdin", file=sys.stderr)
68
+ return 2
69
+ timestamp = None
70
+ if args.date:
71
+ try:
72
+ parsed = datetime.fromisoformat(args.date)
73
+ except ValueError:
74
+ print(f"error: --date must be an ISO 8601 timestamp, got {args.date!r}",
75
+ file=sys.stderr)
76
+ return 2
77
+ if parsed.tzinfo is None:
78
+ parsed = parsed.replace(tzinfo=timezone.utc)
79
+ timestamp = parsed.isoformat()
80
+ decision = any([args.policy_key, args.scope, args.effective_from,
81
+ args.valid_until, args.supersedes])
82
+ if decision and not args.policy_key:
83
+ print("error: --scope, --effective-from, --valid-until and --supersedes "
84
+ "need --policy-key", file=sys.stderr)
85
+ return 2
86
+ effective_from = valid_until = None
87
+ if args.effective_from:
88
+ effective_from = _parse_moment(args.effective_from, "--effective-from")
89
+ if effective_from is None:
90
+ return 2
91
+ if args.valid_until:
92
+ valid_until = _parse_moment(args.valid_until, "--valid-until")
93
+ if valid_until is None:
94
+ return 2
95
+ supersedes = None
96
+ if args.supersedes:
97
+ target = store_mod.find(_store_path(args), args.supersedes)
98
+ if target is None:
99
+ print(f"error: no unique note with id {args.supersedes!r}",
100
+ file=sys.stderr)
101
+ return 2
102
+ supersedes = target["id"]
103
+ try:
104
+ record = store_mod.append(
105
+ _store_path(args), text,
106
+ tags=args.tags.split(",") if args.tags else [],
107
+ session=args.session,
108
+ timestamp=timestamp,
109
+ policy_key=args.policy_key,
110
+ scope=args.scope,
111
+ effective_from=effective_from,
112
+ valid_until=valid_until,
113
+ supersedes=supersedes,
114
+ )
115
+ except ValueError as exc:
116
+ print(f"error: {exc}", file=sys.stderr)
117
+ return 2
118
+ _print_json(record)
119
+ return 0
120
+
121
+
122
+ def cmd_resolve(args) -> int:
123
+ at = as_of = None
124
+ if args.at:
125
+ at = _parse_moment(args.at, "--at")
126
+ if at is None:
127
+ return 2
128
+ if args.as_of:
129
+ as_of = _parse_moment(args.as_of, "--as-of")
130
+ if as_of is None:
131
+ return 2
132
+ records = store_mod.load_all(_store_path(args))
133
+ _print_json(resolve_mod.resolve(records, args.policy_key, at=at,
134
+ scope=args.scope, as_of=as_of))
135
+ return 0
136
+
137
+
138
+ def cmd_init(args) -> int:
139
+ store_path = _store_path(args)
140
+ store_mod.initialize(store_path)
141
+ print(f"Store ready at {store_path}")
142
+ return 0
143
+
144
+
145
+ def _validate_limit(limit: int) -> bool:
146
+ return isinstance(limit, int) and limit >= 1
147
+
148
+
149
+ def _parse_date(value: str, flag: str) -> date | None:
150
+ try:
151
+ return date.fromisoformat(value)
152
+ except ValueError:
153
+ print(f"error: {flag} must be a YYYY-MM-DD date, got {value!r}", file=sys.stderr)
154
+ return None
155
+
156
+
157
+ def _filter_by_date(records: list, after: date | None, before: date | None) -> list:
158
+ if after is None and before is None:
159
+ return records
160
+
161
+ def _in_range(record):
162
+ day = date.fromisoformat(
163
+ summary_mod._utc_day(summary_mod._record_timestamp(record)))
164
+ return (after is None or day >= after) and (before is None or day <= before)
165
+
166
+ return [r for r in records if _in_range(r)]
167
+
168
+
169
+ def _filter_by_tags(records: list, tags_arg) -> list:
170
+ """Keep only records having every listed tag (case-insensitive)."""
171
+ wanted = {t.strip().lower() for t in (tags_arg or "").split(",") if t.strip()}
172
+ if not wanted:
173
+ return records
174
+ return [r for r in records
175
+ if wanted <= {t.lower() for t in r.get("tags", [])}]
176
+
177
+
178
+ def cmd_recall(args) -> int:
179
+ if not _validate_limit(args.limit):
180
+ print("error: --limit must be a positive integer", file=sys.stderr)
181
+ return 2
182
+ if args.days is not None and args.days < 1:
183
+ print("error: --days must be a positive integer", file=sys.stderr)
184
+ return 2
185
+ after = before = None
186
+ if args.after:
187
+ after = _parse_date(args.after, "--after")
188
+ if after is None:
189
+ return 2
190
+ if args.before:
191
+ before = _parse_date(args.before, "--before")
192
+ if before is None:
193
+ return 2
194
+ records = store_mod.load_all(_store_path(args))
195
+ if args.session:
196
+ records = [r for r in records if r.get("session") == args.session]
197
+ if args.tag:
198
+ records = [r for r in records if args.tag.lower() in r.get("tags", [])]
199
+ records = _filter_by_tags(records, args.tags)
200
+ if args.days is not None:
201
+ records = summary_mod.recent_records(records, args.days)
202
+ records = _filter_by_date(records, after, before)
203
+ _print_json(search_mod.recall(records, args.query, limit=args.limit,
204
+ sort=args.sort, exact=args.exact))
205
+ return 0
206
+
207
+
208
+ def cmd_list(args) -> int:
209
+ if not _validate_limit(args.limit):
210
+ print("error: --limit must be a positive integer", file=sys.stderr)
211
+ return 2
212
+ after = before = None
213
+ if args.after:
214
+ after = _parse_date(args.after, "--after")
215
+ if after is None:
216
+ return 2
217
+ if args.before:
218
+ before = _parse_date(args.before, "--before")
219
+ if before is None:
220
+ return 2
221
+ records = store_mod.load_all(_store_path(args))
222
+ if args.session:
223
+ records = [r for r in records if r.get("session") == args.session]
224
+ if args.tag:
225
+ records = [r for r in records if args.tag.lower() in r.get("tags", [])]
226
+ records = _filter_by_tags(records, args.tags)
227
+ if args.days is not None:
228
+ records = summary_mod.recent_records(records, args.days)
229
+ records = _filter_by_date(records, after, before)
230
+ selected = records[-args.limit:]
231
+ _print_json(selected if args.reverse else selected[::-1])
232
+ return 0
233
+
234
+
235
+ def cmd_summary(args) -> int:
236
+ if args.top is not None and args.top < 1:
237
+ print("error: --top must be a positive integer", file=sys.stderr)
238
+ return 2
239
+ records = store_mod.load_all(_store_path(args))
240
+ if args.session:
241
+ records = [r for r in records if r.get("session") == args.session]
242
+ _print_json(summary_mod.summarise(records, days=args.days, top=args.top))
243
+ return 0
244
+
245
+
246
+ def cmd_count(args) -> int:
247
+ records = store_mod.load_all(_store_path(args))
248
+ if args.session:
249
+ records = [r for r in records if r.get("session") == args.session]
250
+ if args.tag:
251
+ tag = args.tag.lower()
252
+ records = [r for r in records
253
+ if tag in {t.lower() for t in r.get("tags", [])}]
254
+ print(json.dumps({"count": len(records)}, ensure_ascii=False))
255
+ return 0
256
+
257
+
258
+ def cmd_sessions(args) -> int:
259
+ records = store_mod.load_all(_store_path(args))
260
+ _print_json(summary_mod.count_sessions(records))
261
+ return 0
262
+
263
+
264
+ def cmd_tags(args) -> int:
265
+ records = store_mod.load_all(_store_path(args))
266
+ if args.session:
267
+ records = [r for r in records if r.get("session") == args.session]
268
+ counts = summary_mod.count_tags(records)
269
+ if args.sort == "count":
270
+ counts = dict(sorted(counts.items(), key=lambda item: (-item[1], item[0])))
271
+ elif args.sort == "name":
272
+ counts = dict(sorted(counts.items(), key=lambda item: item[0]))
273
+ _print_json(counts)
274
+ return 0
275
+
276
+
277
+ def cmd_export(args) -> int:
278
+ if args.days is not None and args.days < 1:
279
+ print("error: --days must be a positive integer", file=sys.stderr)
280
+ return 2
281
+ records = store_mod.load_all(_store_path(args))
282
+ if args.session:
283
+ records = [r for r in records if r.get("session") == args.session]
284
+ if args.tag:
285
+ records = [r for r in records if args.tag.lower() in r.get("tags", [])]
286
+ if args.days is not None:
287
+ records = summary_mod.recent_records(records, args.days)
288
+ if args.out:
289
+ with open(args.out, "w", newline="", encoding="utf-8") as out:
290
+ return _export_records(args, records, out)
291
+ return _export_records(args, records, sys.stdout)
292
+
293
+
294
+ def _export_records(args, records, out) -> int:
295
+ if args.format == "jsonl":
296
+ for record in records:
297
+ print(json.dumps(record, ensure_ascii=False), file=out)
298
+ return 0
299
+ if args.format == "json":
300
+ print(json.dumps(records, ensure_ascii=False, indent=2), file=out)
301
+ return 0
302
+ writer = csv.writer(out)
303
+ writer.writerow(["id", "timestamp", "session", "text", "tags"])
304
+ for r in records:
305
+ writer.writerow([r.get("id", ""), r.get("timestamp", ""),
306
+ r.get("session", ""), r.get("text", ""),
307
+ ";".join(r.get("tags", []))])
308
+ return 0
309
+
310
+
311
+ def cmd_show(args) -> int:
312
+ record = store_mod.find(_store_path(args), args.record_id)
313
+ if record is None:
314
+ print(f"error: no unique note with id {args.record_id!r}", file=sys.stderr)
315
+ return 2
316
+ _print_json(record)
317
+ return 0
318
+
319
+
320
+ def cmd_forget(args) -> int:
321
+ if args.record_id and args.before:
322
+ print("error: provide either a record_id or --before, not both", file=sys.stderr)
323
+ return 2
324
+ if args.before:
325
+ cutoff = _parse_date(args.before, "--before")
326
+ if cutoff is None:
327
+ return 2
328
+ store_path = _store_path(args)
329
+ records = store_mod.load_all(store_path)
330
+ keep = []
331
+ matches = 0
332
+ for r in records:
333
+ day = date.fromisoformat(
334
+ summary_mod._utc_day(summary_mod._record_timestamp(r))
335
+ )
336
+ if day <= cutoff:
337
+ matches += 1
338
+ else:
339
+ keep.append(r)
340
+ if not args.yes or args.dry_run:
341
+ noun = "note" if matches == 1 else "notes"
342
+ print(
343
+ f"Would delete {matches} {noun} dated on or before {cutoff.isoformat()}. "
344
+ "Re-run with --yes to delete."
345
+ )
346
+ return 0
347
+ store_mod.write_all(store_path, keep)
348
+ noun = "note" if matches == 1 else "notes"
349
+ print(f"Deleted {matches} {noun}.")
350
+ return 0
351
+ if not args.record_id:
352
+ print("error: forget requires a record_id or --before", file=sys.stderr)
353
+ return 2
354
+ if args.dry_run:
355
+ records = store_mod.load_all(_store_path(args))
356
+ record = next((r for r in records if r.get("id") == args.record_id), None)
357
+ if record is None:
358
+ print(f"error: no record with id {args.record_id}", file=sys.stderr)
359
+ return 2
360
+ _print_json(record)
361
+ return 0
362
+ if store_mod.delete(_store_path(args), args.record_id):
363
+ print(f"forgot {args.record_id}")
364
+ return 0
365
+ print(f"error: no record with id {args.record_id}", file=sys.stderr)
366
+ return 2
367
+
368
+
369
+ def build_parser() -> argparse.ArgumentParser:
370
+ parser = argparse.ArgumentParser(
371
+ prog="agent-memory",
372
+ description="Tiny file-based session memory for coding agents.",
373
+ )
374
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
375
+ parser.add_argument("--store", default=None,
376
+ help="Path to the JSONL store (default .agent-memory/memory.jsonl)")
377
+ sub = parser.add_subparsers(dest="command", required=True)
378
+
379
+ p = sub.add_parser("init", help="Create the memory store.")
380
+ p.set_defaults(func=cmd_init)
381
+
382
+ p = sub.add_parser("remember", help="Save a note.")
383
+ p.add_argument("text", nargs="?", default=None)
384
+ p.add_argument("--tags", default="")
385
+ p.add_argument("--session", default="default")
386
+ p.add_argument("--stdin", action="store_true",
387
+ help="Read the note text from stdin instead of an argument.")
388
+ p.add_argument("--date", default=None,
389
+ help="Backdate the note, ISO 8601 timestamp (default: now).")
390
+ p.add_argument("--policy-key", default=None,
391
+ help="Mark the note as a decision, e.g. login.rate_limit.")
392
+ p.add_argument("--scope", default=None,
393
+ help="Which app the decision applies to, e.g. mobile, web, all.")
394
+ p.add_argument("--effective-from", default=None,
395
+ help="When the decision takes effect, ISO 8601 datetime or date.")
396
+ p.add_argument("--valid-until", default=None,
397
+ help="When the decision stops applying, ISO 8601 datetime or date.")
398
+ p.add_argument("--supersedes", default=None,
399
+ help="ID or unique prefix of the note this decision replaces.")
400
+ p.set_defaults(func=cmd_remember)
401
+
402
+ p = sub.add_parser("resolve", help="Look up one decision at a point in time.")
403
+ p.add_argument("policy_key", help="Decision to look up, e.g. login.rate_limit.")
404
+ p.add_argument("--at", default=None,
405
+ help="Time the question is about, ISO 8601 datetime or date.")
406
+ p.add_argument("--scope", default="all",
407
+ help="Which app the question is about (default: all).")
408
+ p.add_argument("--as-of", default=None,
409
+ help="Knowledge cutoff: only evidence recorded by this time counts.")
410
+ p.set_defaults(func=cmd_resolve)
411
+
412
+ p = sub.add_parser("recall", help="Search notes by keyword or exact phrase.")
413
+ p.add_argument("query")
414
+ p.add_argument("--exact", action="store_true",
415
+ help="Match the query as a case-insensitive phrase in note text only.")
416
+ p.add_argument("--limit", type=int, default=5)
417
+ p.add_argument("--session", default=None)
418
+ p.add_argument("--tag", default=None)
419
+ p.add_argument("--tags", default=None, help="Only search notes having all of these tags.")
420
+ p.add_argument("--days", type=int, help="Only search notes from the last N days.")
421
+ p.add_argument("--after", default=None, help="Only search notes on or after YYYY-MM-DD.")
422
+ p.add_argument("--before", default=None, help="Only search notes on or before YYYY-MM-DD.")
423
+ p.add_argument("--sort", choices=("score", "recency"), default="score",
424
+ help="Order results by score (default) or recency.")
425
+ p.set_defaults(func=cmd_recall)
426
+
427
+ p = sub.add_parser("list", help="List newest notes.")
428
+ p.add_argument("--limit", type=int, default=10)
429
+ p.add_argument("--session", default=None)
430
+ p.add_argument("--after", default=None, help="Only list notes on or after YYYY-MM-DD.")
431
+ p.add_argument("--before", default=None, help="Only list notes on or before YYYY-MM-DD.")
432
+ p.add_argument("--tag", default=None)
433
+ p.add_argument("--tags", default=None, help="Only list notes having all of these tags.")
434
+ p.add_argument("--days", type=int, help="Only list notes from the last N days.")
435
+ p.add_argument("--reverse", action="store_true", help="Show the selected notes oldest first.")
436
+ p.set_defaults(func=cmd_list)
437
+
438
+ p = sub.add_parser("summary", help="Counts by tag and session.")
439
+ p.add_argument("--days", type=int, default=7)
440
+ p.add_argument("--session", default=None)
441
+ p.add_argument("--top", type=int, default=None,
442
+ help="Limit by_tag and by_session to the top N entries.")
443
+ p.set_defaults(func=cmd_summary)
444
+
445
+ p = sub.add_parser("count", help="Print the number of notes as JSON.")
446
+ p.add_argument("--session", default=None)
447
+ p.add_argument("--tag", default=None, help="Only count notes having this tag.")
448
+ p.set_defaults(func=cmd_count)
449
+
450
+ p = sub.add_parser("sessions", help="List sessions and their note counts.")
451
+ p.set_defaults(func=cmd_sessions)
452
+
453
+ p = sub.add_parser("tags", help="List tags and their note counts.")
454
+ p.add_argument("--session", default=None)
455
+ p.add_argument("--sort", choices=("count", "name"), default=None,
456
+ help="Order tags by count (highest first) or name.")
457
+ p.set_defaults(func=cmd_tags)
458
+
459
+ p = sub.add_parser("export", help="Export notes as CSV or JSONL.")
460
+ p.add_argument("--format", choices=("csv", "jsonl", "json"), default="csv")
461
+ p.add_argument("--out", default=None, help="Write to this file (default: stdout)")
462
+ p.add_argument("--session", default=None)
463
+ p.add_argument("--tag", default=None, help="Only export notes having this tag.")
464
+ p.add_argument("--days", type=int, help="Only export notes from the last N days.")
465
+ p.set_defaults(func=cmd_export)
466
+
467
+ p = sub.add_parser("show", help="Print one note as JSON.")
468
+ p.add_argument("record_id", help="Note ID or unique ID prefix.")
469
+ p.set_defaults(func=cmd_show)
470
+
471
+ p = sub.add_parser("forget", help="Delete a note by id or bulk-delete with --before.")
472
+ p.add_argument("record_id", nargs="?", default=None)
473
+ p.add_argument("--dry-run", action="store_true",
474
+ help="Print the record that would be deleted, without deleting it.")
475
+ p.add_argument("--before", default=None,
476
+ help="Delete notes dated on or before YYYY-MM-DD.")
477
+ p.add_argument("--yes", action="store_true",
478
+ help="Confirm bulk deletion without prompting.")
479
+ p.set_defaults(func=cmd_forget)
480
+
481
+ return parser
482
+
483
+
484
+ def main(argv=None) -> int:
485
+ args = build_parser().parse_args(argv)
486
+ return args.func(args)
487
+
488
+
489
+ if __name__ == "__main__":
490
+ raise SystemExit(main())
@@ -0,0 +1,122 @@
1
+ """Point-in-time decision lookup.
2
+
3
+ `resolve` answers "what did we know on this date, for this app, at that
4
+ time?" using the decision fields a note may carry:
5
+
6
+ - `recorded_at`: when the evidence was actually received (set by the store,
7
+ never backdated). Only evidence with `recorded_at <= as_of` counts.
8
+ - `effective_from`: when the decision takes effect.
9
+ - `valid_until`: optional end date; the decision applies while `at` is
10
+ before it.
11
+ - `policy_key`: which decision this note is about, e.g. `login.rate_limit`.
12
+ - `scope`: which app the decision applies to, e.g. `mobile`, `web`, or
13
+ `all` (applies everywhere).
14
+ - `supersedes`: id of the note this decision replaces.
15
+
16
+ Plain notes without a `policy_key` are ignored here but still work with
17
+ `recall`. The decision value is the note text.
18
+ """
19
+
20
+ from datetime import datetime, timezone
21
+
22
+
23
+ def _parse_moment(value):
24
+ """Parse an ISO 8601 datetime or a YYYY-MM-DD date (midnight UTC)."""
25
+ if value is None:
26
+ return None
27
+ if isinstance(value, datetime):
28
+ moment = value
29
+ else:
30
+ text = str(value).strip()
31
+ try:
32
+ moment = datetime.fromisoformat(text)
33
+ except ValueError:
34
+ moment = datetime.fromisoformat(text + "T00:00:00")
35
+ if moment.tzinfo is None:
36
+ moment = moment.replace(tzinfo=timezone.utc)
37
+ return moment
38
+
39
+
40
+ def _record_moment(record, field, fallback_field=None):
41
+ """Moment stored under `field`, or under `fallback_field` when missing.
42
+
43
+ Only `recorded_at` falls back to `timestamp` (old notes predate the
44
+ field). Other fields have no fallback: a missing `valid_until` means
45
+ the decision never expires.
46
+ """
47
+ raw = record.get(field)
48
+ if raw is None and fallback_field is not None:
49
+ raw = record.get(fallback_field)
50
+ if raw is None:
51
+ return None
52
+ try:
53
+ return _parse_moment(raw)
54
+ except ValueError:
55
+ return None
56
+
57
+
58
+ def resolve(records, policy_key, at=None, scope="all", as_of=None):
59
+ """Resolve one decision at a point in time.
60
+
61
+ Returns a dict with status `resolved`, `ambiguous`, or
62
+ `insufficient_evidence`. `at` and `as_of` default to now; a missing
63
+ scope means the universal (`all`) decisions only.
64
+ """
65
+ now = datetime.now(timezone.utc)
66
+ at = _parse_moment(at) if at is not None else now
67
+ as_of = _parse_moment(as_of) if as_of is not None else now
68
+ scope = (scope or "all").strip().lower()
69
+
70
+ applicable = []
71
+ for record in records:
72
+ if record.get("policy_key") != policy_key:
73
+ continue
74
+ note_scope = str(record.get("scope") or "all").strip().lower()
75
+ if note_scope != scope and note_scope != "all":
76
+ continue
77
+ recorded_at = _record_moment(record, "recorded_at", "timestamp")
78
+ if recorded_at is None or recorded_at > as_of:
79
+ continue
80
+ effective_from = _record_moment(record, "effective_from") or recorded_at
81
+ if effective_from > at:
82
+ continue
83
+ valid_until = _record_moment(record, "valid_until")
84
+ if valid_until is not None and at >= valid_until:
85
+ continue
86
+ applicable.append((effective_from, recorded_at, record))
87
+
88
+ # A note superseded by another applicable note no longer applies.
89
+ superseded_ids = {
90
+ str(r.get("supersedes", "")).strip().lower()
91
+ for _, _, r in applicable if r.get("supersedes")
92
+ }
93
+ applicable = [
94
+ item for item in applicable
95
+ if str(item[2].get("id", "")).strip().lower() not in superseded_ids
96
+ ]
97
+
98
+ base = {
99
+ "policy_key": policy_key,
100
+ "scope": scope,
101
+ "at": at.isoformat(),
102
+ "as_of": as_of.isoformat(),
103
+ }
104
+ if not applicable:
105
+ return {**base, "status": "insufficient_evidence"}
106
+
107
+ latest_effective = max(item[0] for item in applicable)
108
+ newest = [item for item in applicable if item[0] == latest_effective]
109
+ values = {item[2].get("text", "") for item in newest}
110
+ if len(values) > 1:
111
+ return {
112
+ **base,
113
+ "status": "ambiguous",
114
+ "candidates": [item[2] for item in newest],
115
+ }
116
+ _, _, winner = max(newest, key=lambda item: item[1])
117
+ return {
118
+ **base,
119
+ "status": "resolved",
120
+ "value": winner.get("text", ""),
121
+ "source_id": winner.get("id", ""),
122
+ }
agent_memory/search.py ADDED
@@ -0,0 +1,47 @@
1
+ """Keyword and exact phrase recall: simple, explainable, no embeddings.
2
+
3
+ Score = number of query tokens found in text + tags.
4
+ Ties break by recency (newest first). Empty query returns newest first.
5
+ """
6
+
7
+ import re
8
+
9
+ _TOKEN = re.compile(r"[a-z0-9]+")
10
+
11
+
12
+ def tokens(text: str) -> list:
13
+ return _TOKEN.findall((text or "").lower())
14
+
15
+
16
+ def score_record(record: dict, query_tokens: list) -> int:
17
+ haystack = " ".join([record.get("text", ""), " ".join(record.get("tags", []))])
18
+ hay = set(tokens(haystack))
19
+ return sum(1 for t in query_tokens if t in hay)
20
+
21
+
22
+ def recall(records: list, query: str, limit: int = 5, sort: str = "score",
23
+ exact: bool = False) -> list:
24
+ """Return up to `limit` records.
25
+
26
+ sort="score": best score first, newest first on ties (default).
27
+ sort="recency": newest first, ignoring score.
28
+ exact=True: match a case-insensitive phrase in text only. All matches have
29
+ equal scores, so both sort modes return newest first.
30
+ """
31
+ query_tokens = tokens(query)
32
+ phrase = query.casefold() if exact else ""
33
+ scored = []
34
+ for i, r in enumerate(records):
35
+ if exact:
36
+ score = int(phrase in r.get("text", "").casefold())
37
+ else:
38
+ score = score_record(r, query_tokens) if query_tokens else 0
39
+ scored.append((score, i, r))
40
+ # Keep only matches when there is a query; empty query lists newest.
41
+ if query_tokens or exact:
42
+ scored = [s for s in scored if s[0] > 0]
43
+ if sort == "recency":
44
+ scored.sort(key=lambda s: s[1], reverse=True)
45
+ else:
46
+ scored.sort(key=lambda s: (s[0], s[1]), reverse=True)
47
+ return [r for _, _, r in scored[:limit]]
agent_memory/store.py ADDED
@@ -0,0 +1,124 @@
1
+ """File store: one JSON object per line (JSONL).
2
+
3
+ A record is a plain dict:
4
+ {"id": "a1b2c3d4", "timestamp": "2026-11-29T11:30:00+00:00",
5
+ "recorded_at": "2026-11-29T11:30:00+00:00",
6
+ "session": "default", "text": "...", "tags": ["bug", "api"]}
7
+
8
+ `recorded_at` is always set to the moment the note was stored. A decision
9
+ note may also carry `policy_key`, `scope`, `effective_from`, `valid_until`,
10
+ and `supersedes` (see resolve.py).
11
+
12
+ No server, no database, no API key. The file is the memory.
13
+ """
14
+
15
+ import json
16
+ import secrets
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+
20
+
21
+ def _now_iso() -> str:
22
+ return datetime.now(timezone.utc).isoformat()
23
+
24
+
25
+ def _new_id() -> str:
26
+ return secrets.token_hex(4)
27
+
28
+
29
+ def load_all(store_path: Path) -> list:
30
+ """Return all records in file order. Missing file means no records."""
31
+ if not store_path.exists():
32
+ return []
33
+ records = []
34
+ for raw_line in store_path.read_text(encoding="utf-8").splitlines():
35
+ line = raw_line.strip()
36
+ if not line:
37
+ continue
38
+ records.append(json.loads(line))
39
+ return records
40
+
41
+
42
+ def initialize(store_path: Path) -> None:
43
+ """Create the store directory and empty file if they are missing."""
44
+ store_path.parent.mkdir(parents=True, exist_ok=True)
45
+ store_path.touch(exist_ok=True)
46
+
47
+
48
+ def append(store_path: Path, text: str, tags=None, session: str = "default",
49
+ timestamp: str | None = None, policy_key: str | None = None,
50
+ scope: str | None = None, effective_from: str | None = None,
51
+ valid_until: str | None = None, supersedes: str | None = None) -> dict:
52
+ """Append one record and return it. Raises ValueError on empty text.
53
+
54
+ `recorded_at` is always set to now: it is when the evidence was actually
55
+ received, so `--date` (which only backdates `timestamp`) never changes
56
+ it. Decision fields are stored only when supplied; `effective_from`
57
+ defaults to `recorded_at` and `scope` defaults to "all" for a decision
58
+ note.
59
+ """
60
+ text = (text or "").strip()
61
+ if not text:
62
+ raise ValueError("note text must not be empty")
63
+ recorded_at = _now_iso()
64
+ record = {
65
+ "id": _new_id(),
66
+ "timestamp": timestamp or recorded_at,
67
+ "recorded_at": recorded_at,
68
+ "session": session or "default",
69
+ "text": text,
70
+ "tags": sorted({t.strip().lower() for t in (tags or []) if t.strip()}),
71
+ }
72
+ if policy_key:
73
+ record["policy_key"] = policy_key.strip()
74
+ record["scope"] = (scope or "all").strip().lower()
75
+ record["effective_from"] = effective_from or recorded_at
76
+ if valid_until:
77
+ record["valid_until"] = valid_until
78
+ if supersedes:
79
+ record["supersedes"] = supersedes
80
+ store_path.parent.mkdir(parents=True, exist_ok=True)
81
+ with store_path.open("a", encoding="utf-8") as f:
82
+ f.write(json.dumps(record, ensure_ascii=False) + "\n")
83
+ return record
84
+
85
+
86
+ def _find_record_index(records: list, record_id: str) -> int | None:
87
+ prefix = (record_id or "").strip().lower()
88
+ if not prefix:
89
+ return None
90
+ match = None
91
+ for i, record in enumerate(records):
92
+ if str(record.get("id", "")).lower().startswith(prefix):
93
+ if match is not None:
94
+ return None
95
+ match = i
96
+ return match
97
+
98
+
99
+ def find(store_path: Path, record_id: str) -> dict | None:
100
+ """Read one record by id or unique id prefix without modifying the store."""
101
+ records = load_all(store_path)
102
+ index = _find_record_index(records, record_id)
103
+ return records[index] if index is not None else None
104
+
105
+
106
+ def delete(store_path: Path, record_id: str) -> bool:
107
+ """Delete by id or unique id prefix. Returns True if one was removed."""
108
+ if not (record_id or "").strip():
109
+ return False
110
+ records = load_all(store_path)
111
+ index = _find_record_index(records, record_id)
112
+ if index is None:
113
+ return False
114
+ del records[index]
115
+ write_all(store_path, records)
116
+ return True
117
+
118
+
119
+ def write_all(store_path: Path, records: list) -> None:
120
+ """Overwrite *store_path* with *records*."""
121
+ store_path.parent.mkdir(parents=True, exist_ok=True)
122
+ with store_path.open("w", encoding="utf-8") as f:
123
+ for r in records:
124
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
@@ -0,0 +1,56 @@
1
+ """Extractive summary: counts only, no LLM, no invented content.
2
+
3
+ Returns counts by tag, session, and UTC day, total notes, and the newest notes.
4
+ """
5
+
6
+ from collections import Counter
7
+ from datetime import datetime, timedelta, timezone
8
+
9
+
10
+ def _record_timestamp(record: dict) -> datetime:
11
+ return datetime.fromisoformat(str(record.get("timestamp", "")).replace("Z", "+00:00"))
12
+
13
+
14
+ def _utc_day(timestamp: datetime) -> str:
15
+ if timestamp.tzinfo is not None:
16
+ timestamp = timestamp.astimezone(timezone.utc)
17
+ return timestamp.date().isoformat()
18
+
19
+
20
+ def recent_records(records: list, days: int) -> list:
21
+ now = datetime.now(timezone.utc)
22
+ cutoff = now - timedelta(days=days) if days else None
23
+ recent = []
24
+ for r in records:
25
+ try:
26
+ ts = _record_timestamp(r)
27
+ except ValueError:
28
+ continue
29
+ if cutoff is None or ts >= cutoff:
30
+ recent.append(r)
31
+ return recent
32
+
33
+
34
+ def count_sessions(records: list) -> dict[str, int]:
35
+ return dict(Counter(r.get("session", "default") for r in records).most_common())
36
+
37
+
38
+ def count_tags(records: list) -> dict[str, int]:
39
+ return dict(Counter(t for r in records for t in r.get("tags", [])).most_common())
40
+
41
+
42
+ def summarise(records: list, days: int = 7, top: int | None = None) -> dict:
43
+ recent = recent_records(records, days)
44
+ tag_counts = Counter(t for r in recent for t in r.get("tags", []))
45
+ session_counts = count_sessions(recent)
46
+ if top is not None:
47
+ session_counts = dict(list(session_counts.items())[:top])
48
+ return {
49
+ "days": days,
50
+ "total": len(records),
51
+ "recent": len(recent),
52
+ "by_tag": dict(tag_counts.most_common(top)),
53
+ "by_session": session_counts,
54
+ "latest": recent[-5:][::-1],
55
+ "by_day": dict(Counter(_utc_day(_record_timestamp(r)) for r in recent)),
56
+ }
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-memory-mini
3
+ Version: 0.2.0
4
+ Summary: Tiny file-based session memory for coding agents: remember, recall, list, summarise. No server, no API key, no GPU.
5
+ Author-email: Xylos Labs <hello@xyloslabs.com>
6
+ License: MIT
7
+ Keywords: agents,memory,cli,notes
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development
13
+ Requires-Python: >=3.10
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest>=7.0; extra == "dev"
18
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
19
+ Requires-Dist: ruff>=0.4; extra == "dev"
20
+ Requires-Dist: mypy>=1.0; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ # agent-memory-mini
24
+
25
+ [![CI](https://github.com/Xylos-Labs/agent-memory-mini/actions/workflows/ci.yml/badge.svg)](https://github.com/Xylos-Labs/agent-memory-mini/actions/workflows/ci.yml)
26
+ [![GitHub stars](https://img.shields.io/github/stars/Xylos-Labs/agent-memory-mini?style=flat)](https://github.com/Xylos-Labs/agent-memory-mini/stargazers)
27
+ [![GitHub forks](https://img.shields.io/github/forks/Xylos-Labs/agent-memory-mini?style=flat)](https://github.com/Xylos-Labs/agent-memory-mini/network/members)
28
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
29
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
30
+
31
+ Tiny file-based session memory for coding agents: remember, recall, list, summarise. No server, no API key, no GPU, no embeddings.
32
+
33
+ Built by [Xylos Labs](https://github.com/Xylos-Labs) as an open-source, reproducible project. The store is one JSONL file, one record per line, so you can read it, grep it, and back it up like any other file.
34
+
35
+ ## Quick start
36
+
37
+ ```bash
38
+ python -m venv .venv && source .venv/bin/activate
39
+ pip install -e ".[dev]"
40
+
41
+ # Create the store (optional: `remember` creates it on first use)
42
+ python -m agent_memory init
43
+
44
+ # Save a note
45
+ python -m agent_memory remember "fixed login bug" --tags bug,auth
46
+ # {"id": "a1b2c3d4", "timestamp": "...", "session": "default",
47
+ # "text": "fixed login bug", "tags": ["auth", "bug"]}
48
+
49
+ # Read a note from standard input or assign a UTC date
50
+ printf '%s\n' "login review notes" | python -m agent_memory remember --stdin --tags auth --session auth
51
+ python -m agent_memory remember "login rollout" --date 2026-11-25 --tags auth --session auth
52
+
53
+ # Find it later by keyword (text + tags, best match first)
54
+ python -m agent_memory recall "login bug"
55
+
56
+ # Match a phrase in note text, ignoring case (newest match first)
57
+ python -m agent_memory recall --exact "login bug"
58
+
59
+ # Newest notes, or filtered
60
+ python -m agent_memory list --limit 10
61
+ python -m agent_memory list --tag bug
62
+ python -m agent_memory list --days 7
63
+ python -m agent_memory list --after 2026-11-01 --before 2026-11-30
64
+ python -m agent_memory list --reverse # oldest first
65
+
66
+ # List sessions and their note counts
67
+ python -m agent_memory sessions
68
+
69
+ # Recall within one session or tag only
70
+ python -m agent_memory recall "login" --session auth
71
+ python -m agent_memory recall "login" --tag bug
72
+ python -m agent_memory recall "login" --days 7
73
+
74
+ # Sort recall by recency or filter by an inclusive UTC date range
75
+ python -m agent_memory recall "login" --sort recency
76
+ python -m agent_memory recall "login" --after 2026-11-01 --before 2026-11-30
77
+
78
+ # Count tags across all sessions or in one session
79
+ python -m agent_memory tags
80
+ python -m agent_memory tags --session auth
81
+
82
+ # Export everything as CSV (or one session)
83
+ python -m agent_memory export --out notes.csv
84
+ python -m agent_memory export --session auth --out auth-notes.csv
85
+
86
+ # Preserve record fields, including the tags array, as JSON Lines
87
+ python -m agent_memory export --format jsonl --out notes.jsonl
88
+
89
+ # Export a JSON array, or filter exported notes by tag
90
+ python -m agent_memory export --format json --out notes.json
91
+ python -m agent_memory export --tag auth --out auth-tagged.csv
92
+
93
+ # Counts only, no invented content
94
+ python -m agent_memory summary --days 7
95
+ python -m agent_memory summary --session auth
96
+
97
+ # Show only the top three tags
98
+ python -m agent_memory summary --top 3
99
+
100
+ # Preview a date-based deletion without changing the store
101
+ python -m agent_memory forget --before 2026-11-30 --dry-run
102
+
103
+ # Delete by id (or unique prefix)
104
+ python -m agent_memory forget a1b2c3d4
105
+
106
+ # Record a decision with when it was received and when it takes effect
107
+ python -m agent_memory remember "5" --policy-key login.rate_limit --scope all
108
+ python -m agent_memory remember "3" --policy-key login.rate_limit --scope mobile \
109
+ --effective-from 2026-12-12
110
+
111
+ # Ask what the limit was for mobile on Dec 11 (answer: 5, change not yet effective)
112
+ python -m agent_memory resolve login.rate_limit --at 2026-12-11 --scope mobile
113
+
114
+ # Ask what the limit was for mobile on Dec 12 (answer: 3, change now effective)
115
+ python -m agent_memory resolve login.rate_limit --at 2026-12-12 --scope mobile
116
+ ```
117
+
118
+ ## How it works
119
+
120
+ **Store.** Default `.agent-memory/memory.jsonl` in the current directory. Override with `--store PATH` or `AGENT_MEMORY_STORE`. Each record has `id`, `timestamp`, `session`, `text`, `tags`.
121
+
122
+ **List date range.** `--after` and `--before` include their boundary dates, using each note's UTC day. Use either flag alone or both together; they combine with the other filters before `--limit` and `--reverse`.
123
+
124
+ **Recall.** By default, score is how many query words appear in the text or tags, ties break newest first. With `--exact`, the whole query must appear in the note text, ignoring case but preserving punctuation and whitespace. Tags do not count as phrase matches. Exact matches have equal scores and appear newest first with either `--sort` mode; an empty query lists newest notes. All existing filters and `--limit` still apply. No embeddings, no LLM, so results are explainable and offline.
125
+
126
+ **Summary.** Counts by tag, by session and by UTC day for the last N days (default 7), plus the 5 newest notes. It never invents content.
127
+
128
+ **Resolve.** `resolve <policy_key>` answers "what did we know on this date, for this app, at that time?" A decision note carries `recorded_at` (set automatically when the note is stored, never changed by `remember --date`), `effective_from` (when it takes effect, defaults to `recorded_at`), an optional `valid_until`, a `scope` (`mobile`, `web`, or `all`), and an optional `supersedes` id. `resolve` only trusts notes with these fields, picks the applicable note with the latest `effective_from`, and returns its text plus `source_id`. `--as-of` limits the evidence to what was recorded by that time. If two applicable notes conflict it returns `ambiguous` with both notes; if none applies it returns `insufficient_evidence`.
129
+
130
+ ## Why use it: agent handoff in 30 seconds
131
+
132
+ A coding agent's context ends when the session ends. This keeps the decisions:
133
+
134
+ ```bash
135
+ # End of session: save what was decided
136
+ python -m agent_memory remember "use sqlite, not postgres, for the prototype" --tags decision,db --session auth-rework
137
+ python -m agent_memory remember "login rate limit is 5 attempts per minute" --tags decision,auth --session auth-rework
138
+
139
+ # Start of the next session: recall before you code
140
+ python -m agent_memory recall "login" --session auth-rework
141
+ python -m agent_memory summary --days 7
142
+ ```
143
+
144
+ The file is plain JSONL, so the next agent (or you) can read it with `cat`, `grep`, or `export` it to CSV - nothing is locked in a database or a cloud account.
145
+
146
+ ## Project layout
147
+
148
+ ```
149
+ src/agent_memory/ package: store (JSONL), search (keyword), summary (counts), CLI
150
+ tests/ pytest: store, search, CLI subprocess
151
+ ```
152
+
153
+ ## Contributors
154
+
155
+ Thanks to everyone who has contributed!
156
+
157
+ [![Contributors](https://contrib.rocks/image?repo=Xylos-Labs/agent-memory-mini)](https://github.com/Xylos-Labs/agent-memory-mini/graphs/contributors)
158
+
159
+ Want to help? See [CONTRIBUTING.md](CONTRIBUTING.md).
160
+
161
+ ## Licence
162
+
163
+ Code: MIT (see [LICENSE](LICENSE)).
@@ -0,0 +1,12 @@
1
+ agent_memory/__init__.py,sha256=kYjX6O4kx60dBs5dvVjaKhHu3kwZTS8Xlxffc3jYU4w,98
2
+ agent_memory/__main__.py,sha256=gDs7NjnPuQwhvW9r0DjDHXB0E50FQaop5V_Wh07B-Yg,19078
3
+ agent_memory/resolve.py,sha256=9lAgvuVetNdGJiW1r7-ewnV3Vxe6A0V3NChr0l8Nkmg,4305
4
+ agent_memory/search.py,sha256=2psd5ey4lUPUKgi5UkdAuZcC_uxpTxHYnjFuhIg7_iU,1664
5
+ agent_memory/store.py,sha256=NBehuv6friyxrJojXkAgbG5cLx65T94sTf8Cc8MkoAY,4322
6
+ agent_memory/summary.py,sha256=MTEiTx-nnRKrqivIDN_aqd7RWsxNNxK6JNS9O7dU-iw,1846
7
+ agent_memory_mini-0.2.0.dist-info/licenses/LICENSE,sha256=RF0zoK5x_QvTzgsnv7281c8iHo8zGnAQoYIqcTfyli8,1067
8
+ agent_memory_mini-0.2.0.dist-info/METADATA,sha256=omv5XV6D4vBiG2GCLjjhyJdyfJyScwY4Pay0pkci4oE,8017
9
+ agent_memory_mini-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ agent_memory_mini-0.2.0.dist-info/entry_points.txt,sha256=BiXrbMw5VUpDdW3hx4ISkYmYHB4Yp_aTaDVP--1gYx8,60
11
+ agent_memory_mini-0.2.0.dist-info/top_level.txt,sha256=_V9jgaiGPn5u6iTI9a5ZeoWtjGjhYu3EQcTGt3jPCQk,13
12
+ agent_memory_mini-0.2.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
+ agent-memory = agent_memory.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Xylos Labs
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
+ agent_memory