Repository navigation
Expand file tree
/
Copy pathtest.py
More file actions
executable file
·2750 lines (2572 loc) · 133 KB
/
Copy pathtest.py
File metadata and controls
executable file
·2750 lines (2572 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""OptMem invariants, checked against a synthetic life of 5000 memories.
Uses a fake compressor (join + truncate) so the run is deterministic and free.
"""
import contextlib
import datetime
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from importlib.machinery import SourceFileLoader
HERE = os.path.dirname(os.path.realpath(__file__))
MEMO = os.path.join(HERE, "memo")
# Pin the provenance tag before the CLI module loads: every in-process and
# spawned command in this run writes as the same deterministic session.
os.environ["OPTMEM_SESSION"] = "t1"
cli = SourceFileLoader("memo_cli", MEMO).load_module()
cover = cli.cover
def complete(T):
"""Every block buildable from T memories, smallest first. The oracle for
the tool's `pending()`: written straight from the definition, so a bug in
the fast version (which reads level lengths, never scanning) shows up."""
out, size = [], 2
while size <= T:
out += [(i * size, (i + 1) * size) for i in range(T // size)]
size *= 2
return out
# The shipped defaults. A fresh process starts from these, so an in-process
# call must too, or one store's config would leak into the next.
DEFAULTS = {k: getattr(cli, k) for k in cli.KNOBS}
N = 2000
WAKE_LINES = cli.WAKE_LINES # the shipped budget, not a second copy of it
PART_CHARS = cli.PART_CHARS
# Verified caps of the harnesses in the wild: Claude Code cuts a command's
# output at 30,000 chars (middle), pi at 50 KB / 2000 lines (head), Codex
# budgets 10,000 tokens. A part must fit the strictest of each kind.
CAP_CHARS, CAP_LINES = 30000, 2000
ok, fail = 0, 0
def check(cond, msg):
global ok, fail
if cond:
ok += 1
else:
fail += 1
print("FAIL: " + msg)
# The reviewable README block is the generated agent contract with the short
# PATH command substituted. Keeping this exact prevents documentation drift.
with open(os.path.join(HERE, "README.md"), encoding="utf-8") as readme_file:
readme = readme_file.read()
documented = re.search(
r"## Agent instruction block \(reference\).*?```markdown\n(.*?)\n```",
readme, re.DOTALL)
expected_instructions = cli.TEMPLATE.format(
memo="memo", data="~/.optmem/memory",
chars=cli.KNOBS["ENTRY_CHARS"][0]).rstrip()
check(documented and documented.group(1).rstrip() == expected_instructions,
"README agent instructions differ from the generated template")
# ---- pure block math -------------------------------------------------
for T in list(range(1, 400)) + [1000, 4096, 10000, 65536, 100003]:
c = cover(T, WAKE_LINES)
check(len(c) <= WAKE_LINES, "T=%d: %d lines > budget" % (T, len(c)))
check(c[0][0] == 0 and c[-1][1] == T, "T=%d: does not span [0,T)" % T)
for a, b in zip(c, c[1:]):
check(a[1] == b[0], "T=%d: gap or overlap at %s %s" % (T, a, b))
for lo, hi in c:
s = hi - lo
check(s & (s - 1) == 0 and lo % s == 0,
"T=%d: [%d,%d) is not an aligned power-of-two block" % (T, lo, hi))
for a, b in zip(c, c[1:]):
check(b[1] - b[0] <= a[1] - a[0],
"T=%d: detail does not increase toward the present" % T)
check(cover(300, 320) == [(i, i + 1) for i in range(300)],
"under budget, memory should be verbatim")
# every block a cover ever needs must be buildable. cover() costs a 60-step
# binary search, so this walks every tree shape up to 300 and then samples:
# the property is structural, not a function of the exact T.
seen = set()
for T in list(range(1, 300)) + [512, 700, 1000, 1023, 1024, 2000, 2999]:
seen.update(b for b in cover(T, WAKE_LINES) if b[1] - b[0] > 1)
buildable = set(complete(3000))
check(seen <= buildable, "a cover wants a block that complete() never yields")
# work never spikes: naps created by one new memory
worst, prev = 0, 0
for T in range(1, N):
cur = len(complete(T))
worst = max(worst, cur - prev)
prev = cur
check(worst <= 16, "a single memory created %d naps" % worst)
# ---- the real CLI ----------------------------------------------------
d = tempfile.mkdtemp(prefix="optmem-test-")
memo = [sys.executable, MEMO]
class Result:
def __init__(self, returncode, stdout, stderr):
self.returncode, self.stdout, self.stderr = returncode, stdout, stderr
def run(*args, store=None):
"""One `memo` command, in-process. Spawning an interpreter per call cost
~40ms x ~2000 naps; the cross-process behaviour that genuinely needs real
processes (the lock) is tested with real processes below."""
os.environ["MEMORY_DIR"] = store or d
for k, v in DEFAULTS.items():
setattr(cli, k, v)
out, err, code = io.StringIO(), io.StringIO(), 0
try:
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
sd = cli.store()
cli.config(sd)
cli.COMMANDS[args[0]](sd, list(args[1:]))
except SystemExit as e:
code = e.code if isinstance(e.code, int) else 0
return Result(code, out.getvalue(), err.getvalue())
def nap_id(out):
"""The block id from the command a nap prompt offers."""
m = re.search(r"\bnap (\d+)-(\d+)", out)
return "%s-%s" % m.groups() if m else None
def offered(out):
"""The line offering a command. Every command handed to an agent must be
an order, not a label: `Run: memo ...`, never `next: memo ...`."""
return [l for l in out.splitlines()
if l.startswith("Run: ") and (" nap " in l or " wake " in l)]
# the real entry point still has to work: shebang, argv parsing, exit code
smoke = subprocess.run(memo + ["wake"], env=dict(os.environ, MEMORY_DIR=d),
capture_output=True, text=True)
check(smoke.returncode == 0 and "No memories yet" in smoke.stdout,
"the memo CLI does not run: " + smoke.stdout + smoke.stderr)
# a typo in MEMORY_DIR must not silently open a second, empty identity
ghost = subprocess.run(memo + ["wake"], capture_output=True, text=True,
env=dict(os.environ, MEMORY_DIR=d + "-typo"))
check(ghost.returncode == 1 and "No memory at" in ghost.stderr,
"a missing MEMORY_DIR was created instead of reported")
check(not os.path.exists(d + "-typo"), "a missing MEMORY_DIR was created")
dry_source = d + "-dry-source.txt"
with open(dry_source, "w", encoding="utf-8") as f:
f.write("2026-07-27 one portable record\n")
dry_missing = d + "-dry-store"
dry_cli = subprocess.run(
memo + ["import", "--dry-run", dry_source],
capture_output=True, text=True,
env=dict(os.environ, MEMORY_DIR=dry_missing))
check(dry_cli.returncode == 0 and "Valid OptMem import" in dry_cli.stdout
and not os.path.exists(dry_missing),
"import --dry-run created a missing explicit store:\n"
+ dry_cli.stdout + dry_cli.stderr)
os.unlink(dry_source)
# the fresh-user path: no MEMORY_DIR, wake creates a project memory and says
# the global one is missing; init creates that one and remains idempotent
fresh = {k: v for k, v in os.environ.items() if k != "MEMORY_DIR"}
fresh["HOME"] = tempfile.mkdtemp()
fresh["USERPROFILE"] = fresh["HOME"]
fresh["XDG_DATA_HOME"] = os.path.join(fresh["HOME"], ".local", "share")
helped = subprocess.run(memo + ["--help"], capture_output=True, text=True,
env=fresh)
check(helped.returncode == 0 and "Usage:" in helped.stdout
and "setup [--create|--no-create] [FILE ...]" in helped.stdout
and "completion <shell>" in helped.stdout
and "upgrade" in helped.stdout and "uninstall" in helped.stdout
and "scope" in helped.stdout and "doctor" in helped.stdout
and "qmd [help]" in helped.stdout
and "recall [options]" in helped.stdout
and "amend [--fit] <id|lo-hi>" in helped.stdout
and "note [--fit]" in helped.stdout
and "resummarize" in helped.stdout and "export [--with-ids]" in
helped.stdout,
"--help is not a useful command overview:\n" + helped.stdout + helped.stderr)
versioned = subprocess.run(memo + ["--version"], capture_output=True, text=True,
env=fresh)
version_command = subprocess.run(memo + ["version"], capture_output=True,
text=True, env=fresh)
check(versioned.returncode == 0
and versioned.stdout.strip() == "OptMem " + cli.VERSION
and version_command.stdout == versioned.stdout,
"version command/flag is missing or inconsistent")
help_alias = subprocess.run(memo + ["help"], capture_output=True, text=True,
env=fresh)
check(help_alias.returncode == 0 and help_alias.stdout == helped.stdout,
"help and --help disagree")
completion_signatures = {
"bash": "complete -F _memo_completion memo",
"zsh": "compdef _memo memo",
"fish": "complete -c memo",
"powershell": "Register-ArgumentCompleter -Native -CommandName memo",
}
for shell, signature in completion_signatures.items():
completed = subprocess.run(memo + ["completion", shell],
capture_output=True, text=True, env=fresh)
check(completed.returncode == 0 and signature in completed.stdout,
"%s completion is missing or invalid:\n%s%s"
% (shell, completed.stdout, completed.stderr))
check("upgrade" in completed.stdout and "uninstall" in completed.stdout
and "scope" in completed.stdout,
"%s completion omits maintenance commands" % shell)
check("version" in completed.stdout,
"%s completion omits the version command" % shell)
check("limit" in completed.stdout and "context" in completed.stdout
and "depth" in completed.stdout and "semantic" in completed.stdout
and "fast" in completed.stdout and "qmd" in completed.stdout
and "sync" in completed.stdout and "FALLBACK=on" in completed.stdout
and "purge" in completed.stdout and "resummarize" in completed.stdout
and "with-ids" in completed.stdout and "dry-run" in completed.stdout
and "batch" in completed.stdout and "deep" in completed.stdout,
"%s completion omits recall/zoom controls" % shell)
bad_completion = subprocess.run(memo + ["completion", "tcsh"],
capture_output=True, text=True, env=fresh)
check(bad_completion.returncode == 1
and "<bash|zsh|fish|powershell>" in bad_completion.stderr,
"an unsupported completion shell did not show valid choices")
check(not os.path.exists(os.path.join(fresh["HOME"], ".optmem", "memory")),
"printing a completion script created a memory store")
for maintenance_command in ("upgrade", "uninstall"):
refused = subprocess.run(memo + [maintenance_command],
capture_output=True, text=True, env=fresh)
check(refused.returncode == 1 and "source checkout" in refused.stderr
and ("memo %s" % maintenance_command) in refused.stderr,
"%s did not protect the source checkout:\n%s%s"
% (maintenance_command, refused.stdout, refused.stderr))
unknown = subprocess.run(memo + ["wat"], capture_output=True, text=True,
env=fresh)
check(unknown.returncode == 1 and "No such command: wat" in unknown.stderr
and "Run:" in unknown.stderr and "--help" in unknown.stderr,
"an unknown command did not point back to help:\n" + unknown.stderr)
diagnosed = subprocess.run(memo + ["doctor"], capture_output=True, text=True,
env=fresh)
check(diagnosed.returncode == 0 and "OptMem doctor" in diagnosed.stdout
and "Active scope:" in diagnosed.stdout
and "Global store:" in diagnosed.stdout and "FFF recall:" in diagnosed.stdout
and "QMD integration:" in diagnosed.stdout,
"doctor did not explain the installation:\n"
+ diagnosed.stdout + diagnosed.stderr)
check(not os.path.exists(os.path.join(fresh["HOME"], ".optmem", "memory")),
"doctor created the missing global store")
scoped = subprocess.run(memo + ["scope"], capture_output=True, text=True,
env=fresh)
check(scoped.returncode == 0 and "OptMem scope" in scoped.stdout
and "Project:" in scoped.stdout and "Store:" in scoped.stdout
and "Source:" in scoped.stdout
and not os.path.exists(os.path.join(fresh["XDG_DATA_HOME"], "optmem")),
"scope did not explain selection read-only:\n"
+ scoped.stdout + scoped.stderr)
fresh_qmd_status = subprocess.run(
memo + ["qmd", "status"], capture_output=True, text=True, env=fresh)
check(fresh_qmd_status.returncode == 0
and "Integration: disabled" in fresh_qmd_status.stdout
and not os.path.exists(os.path.join(fresh["XDG_DATA_HOME"], "optmem")),
"qmd status created a project store or failed read-only inspection:\n"
+ fresh_qmd_status.stdout + fresh_qmd_status.stderr)
fresh_qmd_help = subprocess.run(
memo + ["qmd"], capture_output=True, text=True, env=fresh)
check(fresh_qmd_help.returncode == 0
and "Optional QMD semantic recall" in fresh_qmd_help.stdout
and "LOG.txt remains authoritative" in fresh_qmd_help.stdout
and not os.path.exists(os.path.join(fresh["XDG_DATA_HOME"], "optmem")),
"qmd help created a project store or omitted its mental model:\n"
+ fresh_qmd_help.stdout + fresh_qmd_help.stderr)
bad_qmd = subprocess.run(
memo + ["qmd", "wat"], capture_output=True, text=True, env=fresh)
check(bad_qmd.returncode == 1 and "Run:" in bad_qmd.stderr
and "qmd help" in bad_qmd.stderr
and not os.path.exists(os.path.join(fresh["XDG_DATA_HOME"], "optmem")),
"an invalid qmd command created a store or omitted help:\n"
+ bad_qmd.stdout + bad_qmd.stderr)
fresh_qmd_config = subprocess.run(
memo + ["qmd", "config"], capture_output=True, text=True, env=fresh)
check(fresh_qmd_config.returncode == 0
and "FALLBACK=off" in fresh_qmd_config.stdout
and not os.path.exists(os.path.join(fresh["XDG_DATA_HOME"], "optmem")),
"reading QMD fallback config created a project store:\n"
+ fresh_qmd_config.stdout + fresh_qmd_config.stderr)
fresh_qmd_fallback = subprocess.run(
memo + ["qmd", "config", "FALLBACK=on"],
capture_output=True, text=True, env=fresh)
check(fresh_qmd_fallback.returncode == 1
and "requires an enabled integration" in fresh_qmd_fallback.stderr
and not os.path.exists(os.path.join(fresh["XDG_DATA_HOME"], "optmem")),
"enabling QMD fallback without QMD created a project store:\n"
+ fresh_qmd_fallback.stdout + fresh_qmd_fallback.stderr)
fresh_qmd_sync = subprocess.run(
memo + ["qmd", "sync"], capture_output=True, text=True, env=fresh)
check(fresh_qmd_sync.returncode == 1
and "not enabled" in fresh_qmd_sync.stderr
and not os.path.exists(os.path.join(fresh["XDG_DATA_HOME"], "optmem")),
"syncing disabled QMD created a project store:\n"
+ fresh_qmd_sync.stdout + fresh_qmd_sync.stderr)
fresh_semantic = subprocess.run(
memo + ["recall", "--semantic", "anything"], capture_output=True,
text=True, env=fresh)
check(fresh_semantic.returncode == 1 and "not enabled" in fresh_semantic.stderr
and not os.path.exists(os.path.join(fresh["XDG_DATA_HOME"], "optmem")),
"disabled semantic recall created a project store:\n"
+ fresh_semantic.stdout + fresh_semantic.stderr)
# `setup` safely connects common agent instruction files without requiring a
# memory to exist. It is repeatable, preserves user text, and preflights every
# target before writing any of them.
setup_dir = tempfile.mkdtemp(prefix="optmem-setup-")
setup = subprocess.run(memo + ["setup"], cwd=setup_dir,
capture_output=True, text=True, env=fresh)
agents = os.path.join(setup_dir, "AGENTS.md")
claude = os.path.join(setup_dir, "CLAUDE.md")
check(setup.returncode == 0 and not os.path.exists(agents)
and not os.path.exists(claude)
and setup.stdout.count("Skipped missing:") == 2
and "--create" in setup.stdout,
"setup created missing instruction files without opt-in:\n"
+ setup.stdout + setup.stderr)
no_create = subprocess.run(memo + ["setup", "--no-create"], cwd=setup_dir,
capture_output=True, text=True, env=fresh)
check(no_create.returncode == 0 and not os.path.exists(agents)
and not os.path.exists(claude)
and no_create.stdout.count("Skipped missing:") == 2,
"setup --no-create did not enforce the safe default:\n"
+ no_create.stdout + no_create.stderr)
created = subprocess.run(memo + ["setup", "--create"], cwd=setup_dir,
capture_output=True, text=True, env=fresh)
check(created.returncode == 0 and os.path.isfile(agents)
and os.path.isfile(claude) and created.stdout.count("Added OptMem") == 2,
"setup --create did not create both default instruction files:\n"
+ created.stdout + created.stderr)
agents_before = open(agents, "rb").read()
claude_before = open(claude, "rb").read()
check(agents_before.count(cli.AGENT_START.encode()) == 1
and b"Your memory is OptMem:" in agents_before,
"AGENTS.md does not contain one managed instruction block")
setup_again = subprocess.run(memo + ["setup"], cwd=setup_dir,
capture_output=True, text=True, env=fresh)
check(setup_again.returncode == 0
and setup_again.stdout.count("Already configured:") == 2
and open(agents, "rb").read() == agents_before
and open(claude, "rb").read() == claude_before,
"setup is not byte-for-byte idempotent:\n"
+ setup_again.stdout + setup_again.stderr)
check(not os.path.exists(os.path.join(fresh["HOME"], ".optmem", "memory")),
"setup created a memory store as a side effect")
custom = os.path.join(setup_dir, "CUSTOM.md")
with open(custom, "w", encoding="utf-8") as f:
f.write("# Existing instructions\n\nKeep this exactly.\n")
custom_setup = subprocess.run(memo + ["setup", "CUSTOM.md"], cwd=setup_dir,
capture_output=True, text=True, env=fresh)
custom_text = open(custom, encoding="utf-8").read()
check(custom_setup.returncode == 0
and custom_text.startswith(cli.AGENT_START)
and custom_text.endswith("# Existing instructions\n\nKeep this exactly.\n"),
"setup did not preserve existing custom instructions")
# A block managed by a previous release is updated in place; surrounding user
# content remains untouched.
with open(custom, "w", encoding="utf-8") as f:
f.write("Before\n%s\nold generated instructions\n%s\nAfter\n"
% (cli.AGENT_START, cli.AGENT_END))
updated = subprocess.run(memo + ["setup", custom], cwd=setup_dir,
capture_output=True, text=True, env=fresh)
custom_text = open(custom, encoding="utf-8").read()
check(updated.returncode == 0 and "Updated OptMem" in updated.stdout
and custom_text.startswith("Before\n")
and custom_text.endswith("\nAfter\n")
and custom_text.count(cli.AGENT_START) == 1
and "Your memory is OptMem:" in custom_text,
"setup did not update one managed block in place")
legacy = os.path.join(setup_dir, "LEGACY.md")
legacy_text = "## Memory\n\nYour memory is OptMem:\n- hand maintained\n"
with open(legacy, "w", encoding="utf-8") as f:
f.write(legacy_text)
legacy_setup = subprocess.run(memo + ["setup", legacy], cwd=setup_dir,
capture_output=True, text=True, env=fresh)
check(legacy_setup.returncode == 0 and "unmanaged legacy block" in legacy_setup.stdout
and open(legacy, encoding="utf-8").read() == legacy_text,
"setup duplicated or changed legacy hand-copied instructions")
malformed = os.path.join(setup_dir, "MALFORMED.md")
untouched = os.path.join(setup_dir, "MUST-NOT-EXIST.md")
with open(malformed, "w", encoding="utf-8") as f:
f.write(cli.AGENT_START + "\nmissing end\n")
bad_setup = subprocess.run(memo + ["setup", "--create", untouched, malformed],
cwd=setup_dir, capture_output=True, text=True,
env=fresh)
check(bad_setup.returncode == 1 and "Malformed OptMem markers" in bad_setup.stderr
and not os.path.exists(untouched),
"setup wrote a partial result before rejecting malformed markers:\n"
+ bad_setup.stdout + bad_setup.stderr)
# AGENTS.md and CLAUDE.md are commonly ONE file under two names: a symlink
# either way, or a hard link where symlinks need a privilege. The block must
# land in it once, both names must still name it afterwards, and the link must
# survive -- setup must never replace a link with a regular file.
def linked_setup(kind):
"""Set up a fresh AGENTS.md/CLAUDE.md pair joined by one link, or None if
this platform will not make that kind of link (Windows without the
privilege). Returns (dir, target, link)."""
where = tempfile.mkdtemp(prefix="optmem-linked-")
target = os.path.join(where, "AGENTS.md")
link = os.path.join(where, "CLAUDE.md")
with open(target, "w", encoding="utf-8") as f:
f.write("# House rules\n\nBe careful.\n")
try:
if kind == "symlink":
os.symlink(target, link)
else:
os.link(target, link)
except (OSError, NotImplementedError, AttributeError):
shutil.rmtree(where, ignore_errors=True)
return None
return where, target, link
for kind in ("symlink", "hardlink"):
made = linked_setup(kind)
if made is None:
continue # the platform refused; the other kind still covers
where, target, link = made
for order in (["AGENTS.md", "CLAUDE.md"], ["CLAUDE.md", "AGENTS.md"], []):
made_each = linked_setup(kind)
if made_each is None:
continue
where_each, target_each, link_each = made_each
r = subprocess.run(memo + ["setup"] + order, cwd=where_each,
capture_output=True, text=True, env=fresh)
body = open(target_each, encoding="utf-8").read()
check(r.returncode == 0,
"%s setup %s failed:\n%s" % (kind, order, r.stdout + r.stderr))
check(body.count(cli.AGENT_START) == 1
and body.count(cli.AGENT_END) == 1,
"%s setup %s wrote the block %d times into one file"
% (kind, order, body.count(cli.AGENT_START)))
check("Be careful." in body,
"%s setup %s dropped the file's own instructions" % (kind, order))
# both names must still be one file, with one content
check(os.path.exists(link_each) and os.path.exists(target_each)
and os.path.samefile(link_each, target_each),
"%s setup %s broke the link between the two names"
% (kind, order))
check(open(link_each, encoding="utf-8").read() == body,
"%s setup %s left the two names with different contents"
% (kind, order))
if kind == "symlink":
check(os.path.islink(link_each) and not os.path.islink(target_each),
"%s setup %s replaced the symlink with a regular file"
% (kind, order))
check(r.stdout.count("Added OptMem instructions") == 1,
"%s setup %s did not report exactly one file written:\n%s"
% (kind, order, r.stdout))
check("same file" in r.stdout,
"%s setup %s did not say the second name is the same file:\n%s"
% (kind, order, r.stdout))
# and it stays idempotent through the link
again = subprocess.run(memo + ["setup"] + order, cwd=where_each,
capture_output=True, text=True, env=fresh)
check(again.returncode == 0
and again.stdout.count("Already configured:") == 1
and open(target_each, encoding="utf-8").read() == body,
"%s setup %s is not idempotent through the link:\n%s"
% (kind, order, again.stdout + again.stderr))
shutil.rmtree(where_each, ignore_errors=True)
shutil.rmtree(where, ignore_errors=True)
# A symlink pointing nowhere must be reported, not silently turned into a
# regular file that the link's owner never asked for.
dangling_dir = tempfile.mkdtemp(prefix="optmem-dangling-")
dangling = os.path.join(dangling_dir, "AGENTS.md")
try:
os.symlink(os.path.join(dangling_dir, "nowhere.md"), dangling)
except (OSError, NotImplementedError):
dangling = None
if dangling:
r = subprocess.run(memo + ["setup", "--create", "AGENTS.md"],
cwd=dangling_dir, capture_output=True, text=True,
env=fresh)
check(r.returncode == 1 and "does not exist" in r.stderr
and os.path.islink(dangling),
"setup followed a dangling symlink instead of reporting it:\n"
+ r.stdout + r.stderr)
shutil.rmtree(dangling_dir, ignore_errors=True)
conflicting_setup = subprocess.run(
memo + ["setup", "--create", "--no-create"], cwd=setup_dir,
capture_output=True, text=True, env=fresh)
check(conflicting_setup.returncode == 1
and "either --create or --no-create" in conflicting_setup.stderr,
"setup accepted conflicting creation flags")
# Uninstall removes only the installed command and integration it owns. It
# must leave both global and project memories—and unrelated profile text—intact.
maintenance_home = tempfile.mkdtemp(prefix="optmem-maintenance-")
maintenance_install = os.path.join(maintenance_home, ".optmem")
os.makedirs(os.path.join(maintenance_install, "memory"))
installed_memo = os.path.join(maintenance_install, "memo")
shutil.copy2(MEMO, installed_memo)
installed_launcher = installed_memo + ".cmd"
with open(installed_launcher, "w", encoding="utf-8") as f:
f.write("@echo off\n")
with open(os.path.join(maintenance_install, "memory", "KEEP"), "w") as f:
f.write("global memory")
maintenance_xdg = os.path.join(maintenance_home, "data")
project_keep = os.path.join(maintenance_xdg, "optmem", "KEEP")
os.makedirs(os.path.dirname(project_keep))
with open(project_keep, "w") as f:
f.write("project memory")
if os.name == "nt":
completion_file = os.path.join(maintenance_install, "memo-completion.ps1")
profile_file = os.path.join(
maintenance_home, "Documents", "WindowsPowerShell", "profile.ps1")
managed_line = ". '%s'" % completion_file.replace("'", "''")
else:
completion_file = os.path.join(
maintenance_xdg, "bash-completion", "completions", "memo")
profile_file = os.path.join(maintenance_home, ".bashrc")
managed_line = 'export PATH="$HOME/.optmem:$PATH"'
os.makedirs(os.path.dirname(completion_file), exist_ok=True)
with open(completion_file, "w") as f:
f.write("completion")
os.makedirs(os.path.dirname(profile_file), exist_ok=True)
with open(profile_file, "w", encoding="utf-8") as f:
f.write("before\n# OptMem %s\n%s\nafter\n"
% ("completion" if os.name == "nt" else "command", managed_line))
maintenance_env = dict(
fresh, HOME=maintenance_home, USERPROFILE=maintenance_home,
XDG_DATA_HOME=maintenance_xdg)
# Exercise the full upgrade downloader/runner against a local authoritative
# installer, never the network or the developer's real installation.
check("releases/latest/download/memo" in open(
os.path.join(HERE, "install.sh"), encoding="utf-8").read()
and "releases/latest/download" in open(
os.path.join(HERE, "install.ps1"), encoding="utf-8").read()
and "releases/latest/download" in cli.INSTALL_BASE,
"install or upgrade still consumes mutable main-branch payloads")
fake_release = tempfile.mkdtemp(prefix="optmem-release-")
upgrade_marker = os.path.join(fake_release, "UPGRADED")
if os.name == "nt":
fake_installer = os.path.join(fake_release, "install.ps1")
with open(fake_installer, "w", encoding="utf-8") as f:
f.write("# OptMem installer\n"
"[IO.File]::WriteAllText($env:OPTMEM_UPGRADE_MARKER, 'ok')\n")
else:
fake_installer = os.path.join(fake_release, "install.sh")
with open(fake_installer, "w", encoding="utf-8") as f:
f.write("#!/bin/sh\n# OptMem installer\n"
"printf ok > \"$OPTMEM_UPGRADE_MARKER\"\n")
saved_module_file, saved_install_base = cli.__file__, cli.INSTALL_BASE
saved_maintenance_env = {
key: os.environ.get(key) for key in
("HOME", "USERPROFILE", "XDG_DATA_HOME", "OPTMEM_UPGRADE_MARKER")}
upgrade_code = 0
try:
os.environ.update(maintenance_env)
os.environ["OPTMEM_UPGRADE_MARKER"] = upgrade_marker
cli.__file__ = installed_memo
from pathlib import Path
cli.INSTALL_BASE = Path(fake_release).as_uri()
try:
cli.cmd_upgrade(None, [])
except SystemExit as e:
upgrade_code = e.code if isinstance(e.code, int) else 1
finally:
cli.__file__, cli.INSTALL_BASE = saved_module_file, saved_install_base
for key, value in saved_maintenance_env.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
check(upgrade_code == 0 and os.path.exists(upgrade_marker)
and open(upgrade_marker).read() == "ok",
"upgrade did not download and execute the validated installer")
removed = subprocess.run(
[sys.executable, installed_memo, "uninstall"],
capture_output=True, text=True, env=maintenance_env)
check(removed.returncode == 0 and "Preserved global memory" in removed.stdout
and "Preserved project memories" in removed.stdout
and "Agent instruction blocks were not removed" in removed.stdout
and "QMD projections and external collections were not removed" in
removed.stdout,
"uninstall failed:\n" + removed.stdout + removed.stderr)
check(not os.path.exists(installed_memo)
and not os.path.exists(installed_launcher)
and not os.path.exists(completion_file),
"uninstall left installed executable or completion files")
check(os.path.exists(os.path.join(maintenance_install, "memory", "KEEP"))
and os.path.exists(project_keep),
"uninstall deleted memory data")
profile_after = open(profile_file, encoding="utf-8").read()
check(profile_after == "before\nafter\n",
"uninstall damaged unrelated profile content: %r" % profile_after)
noenv = subprocess.run(memo + ["wake"], capture_output=True, text=True, env=fresh)
check(noenv.returncode == 0 and "No global memory yet" in noenv.stdout
and " init" in noenv.stdout,
"with no global memory, wake must still work and point at init:\n"
+ noenv.stdout + noenv.stderr)
init = subprocess.run(memo + ["init"], capture_output=True, text=True, env=fresh)
check(init.returncode == 0 and "## Memory" in init.stdout
and "You are a" in init.stdout, "init must print the AGENTS.md block")
check("append-first log" in init.stdout
and "binary tree of lossy one-line" in init.stdout
and "raw memories remain searchable" in init.stdout
and "max 280 UTF-8 bytes" in init.stdout
and "recall --semantic" in init.stdout
and "amend <id>" in init.stdout and "retract <id>" in init.stdout
and "Later amendments, corrections, and retractions override" in
init.stdout
and "may reference earlier `#IDs`" in init.stdout
and "Never record secrets, credentials" in init.stdout,
"agent instructions do not explain the memory/compression model")
check("BEGIN OPTMEM AGENT INSTRUCTIONS" in init.stdout
and "END OPTMEM AGENT INSTRUCTIONS" in init.stdout
and "Verify this installation" in init.stdout,
"init did not delimit the copyable block or explain the next step")
check(os.path.exists(os.path.join(fresh["HOME"], ".optmem", "memory", "config")),
"init must create ~/.optmem/memory with its config")
global_doctor = subprocess.run(memo + ["--global", "doctor"],
capture_output=True, text=True, env=fresh)
check(global_doctor.returncode == 0
and "Active scope: global" in global_doctor.stdout
and "Active store:" in global_doctor.stdout,
"--global doctor did not diagnose the global store:\n"
+ global_doctor.stdout + global_doctor.stderr)
if "On PATH: no" in global_doctor.stdout:
check("PATH is not active in this shell; open a new shell" in
global_doctor.stdout,
"doctor did not explain how to recover a missing PATH:\n"
+ global_doctor.stdout)
override_dir = os.path.join(fresh["HOME"], "missing-explicit-store")
override_doctor = subprocess.run(
memo + ["doctor"], capture_output=True, text=True,
env=dict(fresh, MEMORY_DIR=override_dir))
check(override_doctor.returncode == 0
and "Active scope: MEMORY_DIR override" in override_doctor.stdout
and "not created" in override_doctor.stdout
and not os.path.exists(override_dir),
"doctor did not safely diagnose a missing MEMORY_DIR:\n"
+ override_doctor.stdout + override_doctor.stderr)
again = subprocess.run(memo + ["init"], capture_output=True, text=True, env=fresh)
check(again.returncode == 0 and "Found" in again.stdout, "init must be idempotent")
woke = subprocess.run(memo + ["wake"], capture_output=True, text=True, env=fresh)
check(woke.returncode == 0 and "You are awake." in woke.stdout,
"after init, wake must work with zero configuration")
# Every command the tool prints must RUN on the machine it printed it on.
# `curl | sh` puts nothing on PATH, so a bare `memo nap ...` would not: the
# whole loop (note -> merge prompt -> nap) dies on `command not found`.
bare = dict(fresh, PATH=(os.environ.get("PATH", "") if os.name == "nt"
else "/usr/bin:/bin"))
subprocess.run(memo + ["note", "the first thing that happened"], env=bare,
capture_output=True)
asked = subprocess.run(memo + ["note", "the second thing that happened"],
env=bare, capture_output=True, text=True)
order = [l[5:] for l in asked.stdout.splitlines() if l.startswith("Run: ")]
check(len(order) == 1, "note did not order a compression: " + asked.stdout)
command = order[0].replace('"<your line>"', '"both things"')
if os.name == "nt":
obeyed = subprocess.run(["powershell", "-NoProfile", "-Command", command],
env=bare, capture_output=True, text=True)
else:
obeyed = subprocess.run(command, shell=True, env=bare,
capture_output=True, text=True)
check(obeyed.returncode == 0 and "saved" in obeyed.stdout,
"the order the tool printed does not run with nothing on PATH: %r -> %s"
% (order[0], obeyed.stderr.strip()))
# A paginated global wake must enter the project after its final page, and a
# paginated project must then continue without restarting global page 1.
subprocess.run(memo + ["--global", "config", "PART_LINES=1"],
env=fresh, capture_output=True, check=True)
for text in ("global page one", "global page two"):
subprocess.run(memo + ["--global", "note", text],
env=fresh, capture_output=True, check=True)
subprocess.run(memo + ["config", "PART_LINES=1"],
env=fresh, capture_output=True, check=True)
for text in ("project page one", "project page two"):
subprocess.run(memo + ["note", text],
env=fresh, capture_output=True, check=True)
page1 = subprocess.run(memo + ["wake"], env=fresh,
capture_output=True, text=True, check=True)
continuations = [l.split("Run: ", 1)[1] for l in page1.stdout.splitlines()
if "Run: " in l and "--then-project" in l]
check(len(continuations) == 1,
"a paged global wake lost its project continuation:\n" + page1.stdout)
if continuations:
if os.name == "nt":
bridge = subprocess.run(
["powershell", "-NoProfile", "-Command", continuations[0]],
env=fresh, capture_output=True, text=True)
else:
bridge = subprocess.run(continuations[0], shell=True, env=fresh,
capture_output=True, text=True)
check(bridge.returncode == 0
and "global page two" in bridge.stdout
and "== Project memory:" in bridge.stdout,
"global pagination never entered the project:\n"
+ bridge.stdout + bridge.stderr)
project_pages = [bridge.stdout]
current = bridge
for _ in range(16):
project_continuations = [
l.split("Run: ", 1)[1] for l in current.stdout.splitlines()
if l.startswith("Not awake yet. Run: ")
and "--then-project" not in l
]
if not project_continuations:
break
check(len(project_continuations) == 1,
"project pagination did not print one project continuation:\n"
+ current.stdout)
if len(project_continuations) != 1:
break
if os.name == "nt":
current = subprocess.run(
["powershell", "-NoProfile", "-Command",
project_continuations[0]],
env=fresh, capture_output=True, text=True)
else:
current = subprocess.run(project_continuations[0], shell=True,
env=fresh, capture_output=True, text=True)
project_pages.append(current.stdout)
check(current.returncode == 0
and "== Global memory:" not in current.stdout
and "global page one" not in current.stdout,
"project continuation restarted global memory:\n"
+ current.stdout + current.stderr)
project_document = "\n".join(project_pages)
check("project page one" in project_document
and "project page two" in project_document
and project_document.count("You are awake.") == 1
and "Not awake yet." not in current.stdout,
"project pagination did not finish exactly once:\n"
+ project_document + current.stderr)
# a size written by hand into `config` must not brick the tool with a
# recovery that is itself broken: name the file and the line
badcfg = os.path.join(fresh["HOME"], ".optmem", "memory", "config")
with open(badcfg, "a") as f:
f.write("WAKE_LNES = 100\n")
for c in (["wake"], ["--global", "config"]):
r_ = subprocess.run(memo + c, capture_output=True, text=True, env=fresh)
check(r_.returncode == 1 and "config line" in r_.stderr
and "WAKE_LNES" in r_.stderr,
"a typo in config does not say where it is: " + r_.stderr)
open(badcfg, "w").write("")
# the filesystem is the one thing the tool does not control: report it in the
# tool's own voice, never as a Python traceback
r_ = subprocess.run(memo + ["init"], capture_output=True, text=True,
env=dict(fresh, MEMORY_DIR=MEMO)) # a file, not a store
check(r_.returncode == 1 and "Traceback" not in r_.stderr
and ("Not a directory" in r_.stderr
or "cannot find the path specified" in r_.stderr.lower()),
"a filesystem error printed a traceback: " + r_.stderr)
r = run("note", "x" * 281)
check(r.returncode == 1 and "Too long" in r.stderr, "over-long note accepted")
check("over by 1" in r.stderr and 'last 1 bytes: "x"' in r.stderr,
"an over-long note does not show what to cut: " + r.stderr)
r = run("note", "x" * 280 + "é") # 282 bytes: the 2-byte char must be shown
check(r.returncode == 1 and 'last 2 bytes: "é"' in r.stderr,
"the overage suffix split a multi-byte character: " + r.stderr)
r = run("note", "two\nlines")
check(r.returncode == 1 and "one line" in r.stderr, "multi-line note accepted")
r = run("note", " ")
check(r.returncode == 1, "empty note accepted")
r = run("wake")
check("No memories yet" in r.stdout, "empty wake should say so")
check(r.stdout.rstrip().endswith("You are awake."),
"an empty wake must still end with `You are awake.`")
with open(os.path.join(d, "seed.txt"), "w") as f:
day = datetime.date(2020, 1, 1)
for i in range(N):
f.write("%s memory number %d, a thing that happened\n"
% ((day + datetime.timedelta(days=i // 5)).isoformat(), i))
r = run("import", os.path.join(d, "seed.txt"))
check("Imported %d" % N in r.stdout, "import failed: " + r.stdout + r.stderr)
check(not os.path.exists(os.path.join(d, "config")),
"a store wrote its own config file: the defaults are now frozen in it")
r = run("wake")
check(r.returncode == 1 and "Cannot wake" in r.stdout,
"wake must refuse while work is pending")
check("wake again" in r.stdout,
"the refusal must order the agent back to wake")
check("None" not in r.stdout, "the refusal printed a Python None")
# nap loop, with a fake compressor
naps = 0
r = run("nap")
check("Compress memories #" in r.stdout, "nap prompt must name its object")
check("self-contained retrieval cue" in r.stdout
and "causal links" in r.stdout
and "UTF-8 bytes" in r.stdout
and "never imply a link between unrelated facts" in r.stdout,
"nap prompt does not give enough compression guidance")
while "Nothing left to compress" not in r.stdout:
line = offered(r.stdout)
check(bool(line), "no command offered:\n" + r.stdout + r.stderr)
if not line:
break
check(line[0].startswith("Run: "), "a command was offered as a label, not "
"an order: %r" % line[0])
bid = nap_id(r.stdout)
body = [l.strip() for l in r.stdout.splitlines() if l.startswith(" #")]
r = run("nap", bid, (" ".join(body)[:280]).strip() or "empty")
check(r.returncode == 0, "nap rejected a valid merge: " + r.stderr)
naps += 1
check("You are awake" not in r.stdout,
"nap must never claim the agent is awake; only wake may")
check(naps == len(complete(N)), "did %d naps, expected %d" % (naps, len(complete(N))))
r = run("wake")
check(r.returncode == 0, "wake still refuses after a full nap chain")
# the document survives pagination, and every part fits every harness's cap
parts, k = [], 1
while True:
r = run("wake", str(k))
if r.returncode != 0:
break
body = [l for l in r.stdout.splitlines() if l.startswith("#")]
check(len(r.stdout) < CAP_CHARS, "part %d is %d chars, over the %d cap"
% (k, len(r.stdout), CAP_CHARS))
check(len(r.stdout.splitlines()) < CAP_LINES, "part %d is over %d lines"
% (k, CAP_LINES))
parts.append(body)
k += 1
check(len(parts) > 1, "a %d-line memory should need more than one part" % WAKE_LINES)
lines = [l for p in parts for l in p]
check(len(lines) == WAKE_LINES, "woke with %d lines, want %d" % (len(lines), WAKE_LINES))
check(lines[-1].startswith("#%d " % (N - 1)), "newest memory not last / not raw")
check(lines[0].startswith("#0-"), "oldest line should be a summary block")
check(re.search(r"Run: .* wake 2", run("wake").stdout),
"part 1 must ORDER the next command, not label it")
last_part = run("wake", str(len(parts))).stdout
check("You are awake." in last_part, "last part must say it is last")
# the final part reports what the bounded frontier elided, and how to expand
check(re.search(r"Frontier: \d+ of [\d,]+ memories shown raw; .*zoom \d+-\d+",
last_part),
"the last part does not report the elided frontier:\n" + last_part)
check(run("wake", str(len(parts) + 1)).returncode == 1, "a nonexistent part should fail")
# append-only: nothing was ever rewritten
logsz = os.path.getsize(os.path.join(d, "LOG.txt"))
run("note", "one more thing happened today")
check(os.path.getsize(os.path.join(d, "LOG.txt")) > logsz, "note did not append")
check(logsz % 320 == 0, "LOG.txt is not a whole number of records")
for f in os.listdir(os.path.join(d, "TREE")):
check(os.path.getsize(os.path.join(d, "TREE", f)) % 288 == 0,
"TREE/%s is not a whole number of records" % f)
# a nap when nothing is pending writes nothing and says so
r = run("nap", "0-1", "attempted overwrite")
check(r.returncode == 0 and "Nothing left to compress" in r.stdout,
"nap with nothing pending must say so and write nothing")
# recall reaches memories the summaries lost, and matches the whole line:
# id and date included, not just the text
r = run("recall", "memory number 7,")
check(r.returncode == 0 and "#7 " in r.stdout, "recall missed a memory")
check("1 match." in r.stdout, "a single match is not `1 matches`: " + r.stdout)
r = run("recall", "^#7 ")
check("memory number 7," in r.stdout, "recall cannot find a memory by id")
# a query the shell split into words is rejoined, not rejected
r = run("recall", "memory", "number", "7,")
check(r.returncode == 0 and "#7 " in r.stdout,
"recall did not rejoin a shell-split query: " + r.stdout + r.stderr)
r = run("recall", "2020-01-02")
check("#7 " in r.stdout and "5 matches." in r.stdout,
"recall cannot find memories by date: " + r.stdout)
# Limit caps matching entries without reducing search coverage; context adds
# deduplicated neighboring raw memories and clearly marks the actual hits.
r = run("recall", "--limit", "3", "memory number")
limited = [line for line in r.stdout.splitlines() if line.startswith("#")]
check([int(line.split()[0][1:]) for line in limited] == [N - 3, N - 2, N - 1]
and "--limit 3" in r.stdout,
"recall --limit did not keep the newest three matches:\n" + r.stdout)
r = run("recall", "--context", "2", "^#7 ")
context_lines = [line for line in r.stdout.splitlines()
if re.match(r"[ >] #\d+ ", line)]
check(len(context_lines) == 5
and context_lines[0].startswith(" #5 ")
and context_lines[2].startswith("> #7 ")
and context_lines[-1].startswith(" #9 ")
and "Context: up to 2 memories" in r.stdout,
"recall --context did not surround and mark one hit:\n" + r.stdout)
r = run("recall", "--context=2", r"^#(?:7|9) ")
context_lines = [line for line in r.stdout.splitlines()
if re.match(r"[ >] #\d+ ", line)]
check(len(context_lines) == 7
and sum(line.startswith("> ") for line in context_lines) == 2,
"overlapping recall context was not deduplicated:\n" + r.stdout)
check(run("recall", "--limit", "0", "x").returncode == 1,
"recall accepted a zero result limit")
check(run("recall", "--context", "21", "x").returncode == 1,
"recall accepted excessive context")
# FFF is optional: exact recall stays dependency-free, while explicit fuzzy
# recall and zero-result fallback consume its strongest-first raw-memory lines.
real_fff_recall = cli.fff_recall
fuzzy_line = "#7 2020-01-02 memory number 7, a thing that happened"
cli.fff_recall = lambda store, query, limit=None: ([fuzzy_line], None)
r = run("recall", "--fuzzy", "memry numbr sevn")
check(r.returncode == 0 and fuzzy_line in r.stdout
and "FFF, strongest first" in r.stdout,
"explicit FFF recall did not render its result: " + r.stdout + r.stderr)
r = run("recall", "--fuzzy", "--context", "1", "memry numbr sevn")
check("> #7 " in r.stdout and " #6 " in r.stdout and " #8 " in r.stdout
and "context deduplicated" in r.stdout,
"fuzzy recall context did not render neighboring raw memories:\n"
+ r.stdout)
r = run("recall", "definitely absent exact phrase")
check(r.returncode == 0 and "No exact match" in r.stdout
and fuzzy_line in r.stdout,
"zero exact results did not fall back to FFF: " + r.stdout + r.stderr)
cli.fff_recall = lambda store, query, limit=None: (None, "not installed")
r = run("recall", "--fuzzy", "anything")
check(r.returncode == 1 and "pip install fff-search" in r.stderr,
"forced FFF recall did not explain how to enable it: " + r.stderr)
cli.fff_recall = real_fff_recall
# Lifecycle records are later events over stable IDs, not mutations of prior
# facts. Export/import preserves those IDs by restoring only into an empty log.
life = tempfile.mkdtemp(prefix="optmem-lifecycle-")
os.makedirs(os.path.join(life, "TREE"))
open(os.path.join(life, "LOG.txt"), "wb").close()
original = run("note", "Mutation requests may be retried.", store=life)
check("Saved as #0" in original.stdout, "lifecycle seed note failed")
amended = run("amend", "#0", "Only idempotent reads are retried.", store=life)
retracted = run("retract", "0", "Obsolete after the client rewrite.", store=life)
run("note", "The migration rationale is anchored by #0 and #1.", store=life)
check(amended.returncode == 0 and "Amended #0 with #1" in amended.stdout,
"amend did not append a stable lifecycle event: "
+ amended.stdout + amended.stderr)
check(retracted.returncode == 0 and "Retracted #0 with #2" in retracted.stdout,
"retract did not append a stable lifecycle event")
shown = run("show", "0", store=life)
check("Mutation requests may be retried." in shown.stdout
and "Later references:" in shown.stdout
and "Amends #0:" in shown.stdout and "Retracts #0:" in shown.stdout
and "anchored by #0" in shown.stdout,
"show did not resolve the canonical record and later references:\n"
+ shown.stdout + shown.stderr)
before_invalid = os.path.getsize(os.path.join(life, "LOG.txt"))
invalid_amend = run("amend", "99", "Impossible target.", store=life)
check(invalid_amend.returncode == 1
and os.path.getsize(os.path.join(life, "LOG.txt")) == before_invalid,
"amend accepted a missing ID or changed the log")
# supersession outlives compression: a summary-block target is a first-class
# lifecycle record, and every raw memory inside the range shows it later
block_amend = run("amend", "0-1", "Superseding the summarized pair.",
store=life)
check(block_amend.returncode == 0 and "Amended #0-#1" in block_amend.stdout,
"amend of a block was refused: " + block_amend.stdout + block_amend.stderr)
for inner in ("0", "1"):
covered = run("show", inner, store=life)
check("Amends #0-#1: Superseding the summarized pair." in covered.stdout,
"show %s does not list the covering block supersession:\n"
% inner + covered.stdout)
check(run("amend", "3-9", "Not a block.", store=life).returncode == 1,
"amend accepted a non-block range")
check(run("amend", "1024-2047", "Beyond the log.", store=life).returncode == 1,
"amend accepted a block beyond the log")
# a block is also a first-class question: its summary and what supersedes it
block_shown = run("show", "0-1", store=life)
check(block_shown.returncode == 0
and block_shown.stdout.startswith("#0-1 not compressed yet")
and "Amends #0-#1: Superseding the summarized pair." in
block_shown.stdout,