forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_scenarios.py
More file actions
1494 lines (1333 loc) · 57.5 KB
/
Copy pathmemory_scenarios.py
File metadata and controls
1494 lines (1333 loc) · 57.5 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
"""Synthetic local memory product scenario fixtures and seed/reset tooling.
These fixtures are for the local emulator dev harness only. They are safe to
commit, use deterministic synthetic IDs/content, and intentionally cannot choose
evidence labels. Any local report/session metadata emitted by this module is
hard-coded to ``LOCAL_EMULATOR_DEV`` and ``activation_eligible=false``.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import socket
import sys
import time
import urllib.error
import urllib.request
from dataclasses import asdict, dataclass, field, is_dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterable, Literal, Mapping, Sequence
from urllib.parse import quote
from . import config, safety
SCHEMA_VERSION = 1
EVIDENCE_CLASS = "LOCAL_EMULATOR_DEV"
ACTIVATION_ELIGIBLE = False
WATERMARK = "NOT_ACTIVATION_EVIDENCE"
DEFAULT_LOCAL_USER_ID = "local_default_user"
ALICE_USER_ID = "alice"
BOB_USER_ID = "bob"
CHAT_FIRST_E2E_ENABLED_USER_ID = "omi-local-emulator-chat-first-enabled-v1"
CHAT_FIRST_E2E_DISABLED_CONTROL_USER_ID = "omi-local-emulator-chat-first-disabled-v1"
# Short-term seeds must stay visible across long local-dev sessions.
SHORT_TERM_EXPIRES_AT = "2027-12-31T23:59:59Z"
SYNTHETIC_SOURCE_VERSION = "memory-local-synthetic-source-1"
AUTH_UID_MANIFEST = "canonical-auth-uids.json"
LOCAL_DEV_PROJECT_ID = safety.DEFAULT_LOCAL_FIREBASE_PROJECT_ID
LOCAL_DEV_DATABASE_ID = safety.DEFAULT_FIRESTORE_DATABASE_ID
GLOBAL_READ_GATE_PATH = "memory_control/global_read_gate"
RouteDecision = Literal["disabled", "legacy_primary", "memory_read", "fail_closed"]
@dataclass(frozen=True)
class DeterministicContext:
now: str
run_id: str
cursor_secret: str
cursor_policy_version: str
cursor_secret_version: str
cursor_ttl_seconds: int
ids: Mapping[str, str]
cursors: Mapping[str, str]
@dataclass(frozen=True)
class ScenarioUser:
uid: str
email: str
display_name: str
password: str
@dataclass(frozen=True)
class FirestoreSeed:
path: str
data: Mapping[str, object]
protected: bool = False
@dataclass(frozen=True)
class RedisSeed:
key: str
value: str
@dataclass(frozen=True)
class FileSeed:
relative_path: str
content: str
@dataclass(frozen=True)
class RequestCase:
case_id: str
method: str
path: str
query: Mapping[str, str] = field(default_factory=dict)
authenticated_user: str = ALICE_USER_ID
expected_status: int = 200
expected_route_decision: RouteDecision = "memory_read"
expected_memory_ids: tuple[str, ...] = ()
expected_read_paths: tuple[str, ...] = ()
expected_no_write: bool = True
expected_fail_closed_reason: str | None = None
@dataclass(frozen=True)
class ExpectedProtectedCollectionChange:
collection_path: str
allowed_changes: tuple[str, ...] = ()
@dataclass(frozen=True)
class ExpectedFailClosedBehavior:
fail_closed: bool
reason: str | None = None
no_legacy_fallback: bool = True
no_cross_user_disclosure: bool = True
no_memory_writes: bool = True
@dataclass(frozen=True)
class LocalReportMetadata:
evidence_class: str = EVIDENCE_CLASS
activation_eligible: bool = ACTIVATION_ELIGIBLE
watermark: str = WATERMARK
firebase_project_id: str = LOCAL_DEV_PROJECT_ID
firestore_database_id: str = LOCAL_DEV_DATABASE_ID
@dataclass(frozen=True)
class MemoryScenario:
schema_version: int
scenario_id: str
description: str
deterministic: DeterministicContext
users: tuple[ScenarioUser, ...]
selected_user: str
local_flags: Mapping[str, object]
auth_seed: tuple[Mapping[str, object], ...]
profile_seed: tuple[FirestoreSeed, ...]
firestore_seed: tuple[FirestoreSeed, ...]
redis_seed: tuple[RedisSeed, ...]
file_seed: tuple[FileSeed, ...]
request_cases: tuple[RequestCase, ...]
expected_protected_collection_changes: tuple[ExpectedProtectedCollectionChange, ...]
expected_fail_closed: ExpectedFailClosedBehavior
report_metadata: LocalReportMetadata = field(default_factory=LocalReportMetadata)
@dataclass(frozen=True)
class SeedOperation:
kind: Literal["auth", "firestore", "redis", "file", "metadata"]
action: Literal["upsert", "delete", "write"]
target: str
payload: Mapping[str, object] | str | None = None
protected: bool = False
@dataclass(frozen=True)
class SeedManifest:
schema_version: int
scenario_id: str
scenario_digest: str
generated_at: str
dry_run: bool
applied: bool
emulator_available: Mapping[str, bool]
report_metadata: LocalReportMetadata
operations: tuple[SeedOperation, ...]
def _iso(ts: str) -> str:
return ts
def _user(uid: str, name: str) -> ScenarioUser:
return ScenarioUser(
uid=uid,
email=f"{uid}@local.omi.invalid",
display_name=f"Synthetic {name}",
password=f"{uid}-local-password-030",
)
USERS = (
_user(DEFAULT_LOCAL_USER_ID, "Default"),
_user(ALICE_USER_ID, "Alice"),
_user(BOB_USER_ID, "Bob"),
_user(CHAT_FIRST_E2E_ENABLED_USER_ID, "Chat-first E2E Enabled"),
_user(CHAT_FIRST_E2E_DISABLED_CONTROL_USER_ID, "Chat-first E2E Disabled Control"),
)
def _auth_seed(users: Sequence[ScenarioUser]) -> tuple[Mapping[str, object], ...]:
return tuple(
{
"localId": user.uid,
"email": user.email,
"displayName": user.display_name,
"password": user.password,
"emailVerified": True,
"disabled": False,
}
for user in users
)
def _profile_seeds(users: Sequence[ScenarioUser]) -> tuple[FirestoreSeed, ...]:
return tuple(
FirestoreSeed(
path=f"users/{user.uid}",
protected=True,
data={
"uid": user.uid,
"email": user.email,
"display_name": user.display_name,
"synthetic": True,
"local_harness": True,
"created_by": "TICKET-030-memory-scenario-fixtures",
},
)
for user in users
)
def _clock() -> DeterministicContext:
return DeterministicContext(
now="2026-01-15T12:00:00Z",
run_id="memory-local-synthetic-run-030",
cursor_secret="synthetic-memory-local-cursor-secret-030",
cursor_policy_version="memory-v3-cursor-policy-local-030",
cursor_secret_version="local-synthetic-030",
cursor_ttl_seconds=600,
ids={
"alice_short_active": "mem_alice_short_active_030",
"alice_short_stale": "mem_alice_short_stale_030",
"alice_short_demo": "mem_alice_short_demo_030",
"alice_short_dentist": "mem_alice_short_dentist_030",
"alice_short_grocery": "mem_alice_short_grocery_030",
"alice_short_call_mom": "mem_alice_short_call_mom_030",
"alice_short_pr_review": "mem_alice_short_pr_review_030",
"alice_short_yoga": "mem_alice_short_yoga_030",
"alice_short_presentation": "mem_alice_short_presentation_030",
"alice_short_flights": "mem_alice_short_flights_030",
"alice_long": "mem_alice_long_030",
"alice_long_birthplace": "mem_alice_long_birthplace_030",
"alice_long_partner": "mem_alice_long_partner_030",
"alice_long_work": "mem_alice_long_work_030",
"alice_long_tool_warp": "mem_alice_long_tool_warp_030",
"alice_long_tool_obsidian": "mem_alice_long_tool_obsidian_030",
"alice_long_pref_coffee": "mem_alice_long_pref_coffee_030",
"alice_long_pref_sf": "mem_alice_long_pref_sf_030",
"alice_long_family_sister": "mem_alice_long_family_sister_030",
"alice_long_commit_rust": "mem_alice_long_commit_rust_030",
"alice_long_health_running": "mem_alice_long_health_running_030",
"alice_long_lang_spanish": "mem_alice_long_lang_spanish_030",
"alice_long_pet": "mem_alice_long_pet_030",
"alice_long_goal_marathon": "mem_alice_long_goal_marathon_030",
"alice_long_edu": "mem_alice_long_edu_030",
"alice_archive": "mem_alice_archive_030",
"bob_long": "mem_bob_long_030",
"kg_alice": "kg_alice_030",
"kg_jordan": "kg_jordan_030",
"kg_mia": "kg_mia_030",
"kg_omi": "kg_omi_030",
"kg_sf": "kg_sf_030",
"kg_portland": "kg_portland_030",
"kg_warp": "kg_warp_030",
"kg_pixel": "kg_pixel_030",
"projection_commit": "projection_commit_local_030",
"source_commit": "source_commit_local_030",
},
cursors={
"valid_start": "cursor_local_start_030",
"malformed": "not-a-valid-memory-cursor",
"cross_user_bob": "cursor_claims_bob_subject_synthetic_invalid_for_alice",
},
)
def _global_gate(*, enabled: bool, kill: bool = False) -> FirestoreSeed:
return FirestoreSeed(
path=GLOBAL_READ_GATE_PATH,
protected=True,
data={
"route_scope": "get_v3_memories",
"purpose": "memory_v3_runtime_enablement",
"owner": "memory_platform_local_harness",
"config_schema_version": 1,
"memory_reads_enabled": enabled,
"kill_switch_active": kill,
"fixture_source": "TICKET-030-local-synthetic",
},
)
def _control(uid: str, *, default_grant: bool = True, archive: bool = False) -> FirestoreSeed:
return FirestoreSeed(
path=f"users/{uid}/memory_control/state",
protected=True,
data={
"uid": uid,
"schema_version": 1,
"head_commit_id": "ledger_commit_local_030",
"account_generation": 7,
"source_generation": 1,
"commit_sequence": 1,
"grants": {"omi_chat": {"default_memory": default_grant, "archive": archive}},
},
)
def _synthetic_conversation_id(memory_key: str) -> str:
return f"conv_local_{memory_key}_030"
def _synthetic_evidence_id(memory_key: str) -> str:
return f"ev_local_{memory_key}_030"
def _synthetic_memory_evidence(memory_key: str, content: str) -> dict[str, object]:
"""Structurally valid synthetic local-QA evidence for the dev harness.
Self-referential (quote equals memory content; no seeded transcript or
conversation document). Satisfies apply validation in the local emulator
but is not transcript-grounded or production-grade authoritative evidence.
"""
conversation_id = _synthetic_conversation_id(memory_key)
return {
"evidence_id": _synthetic_evidence_id(memory_key),
"source_type": "conversation",
"source_id": conversation_id,
"source_version": SYNTHETIC_SOURCE_VERSION,
"conversation_id": conversation_id,
"artifact_refs": [],
"artifact_preservation": "preserved",
"quote_refs": [{"quote": content, "source_id": conversation_id}],
"source_state": "active",
"provenance_visibility": "visible",
"redaction_status": "active",
"encryption_or_redaction_status": "active",
}
def _memory_evidence_doc(uid: str, memory_key: str, content: str) -> FirestoreSeed:
"""Firestore seed for synthetic local-QA evidence (see ``_synthetic_memory_evidence``)."""
evidence = _synthetic_memory_evidence(memory_key, content)
return FirestoreSeed(
path=f"users/{uid}/memory_evidence/{evidence['evidence_id']}",
protected=True,
data=evidence,
)
def _append_sourced_memory(
seeds: list[FirestoreSeed],
uid: str,
memory_key: str,
memory_id: str,
tier: str,
content: str,
captured: str,
expires: str | None = None,
) -> None:
"""Append a memory_items doc plus matching synthetic local-QA evidence doc."""
seeds.append(_memory_doc(uid, memory_id, tier, content, captured, expires, memory_key=memory_key))
seeds.append(_memory_evidence_doc(uid, memory_key, content))
def _memory_doc(
uid: str,
memory_id: str,
tier: str,
content: str,
captured: str,
expires: str | None = None,
*,
memory_key: str | None = None,
) -> FirestoreSeed:
evidence_entries: list[dict[str, object]] = []
if memory_key is not None:
evidence_entries = [_synthetic_memory_evidence(memory_key, content)]
data: dict[str, object] = {
"memory_id": memory_id,
"uid": uid,
"canonical_memory_id": memory_id,
"version": 1,
"tier": tier,
"status": "active",
"processing_state": "processed",
"content": content,
"evidence": evidence_entries,
"source_state": "active",
"sensitivity_labels": [],
"visibility": "private",
"user_asserted": True,
"captured_at": captured,
"updated_at": captured,
"ledger_commit_id": "ledger_commit_local_030" if tier == "long_term" else None,
"ledger_sequence": 1 if tier == "long_term" else None,
"item_revision": 1,
"source_commit_id": "source_commit_local_030",
"source_commit_sequence": 1,
"content_hash": hashlib.sha256(content.encode("utf-8")).hexdigest(),
"account_generation": 7,
}
if expires is not None:
data["expires_at"] = expires
return FirestoreSeed(path=f"users/{uid}/memory_items/{memory_id}", protected=True, data=data)
def _kg_node(uid: str, node_id: str, label: str, node_type: str, *, memory_ids: Sequence[str] = ()) -> FirestoreSeed:
label_lower = label.lower()
return FirestoreSeed(
path=f"users/{uid}/knowledge_nodes/{node_id}",
protected=True,
data={
"id": node_id,
"label": label,
"node_type": node_type,
"aliases": [],
"memory_ids": list(memory_ids),
"created_at": "2026-01-10T09:00:00Z",
"updated_at": "2026-01-10T09:00:00Z",
"label_lower": label_lower,
"aliases_lower": [],
},
)
def _kg_edge(
uid: str, edge_id: str, source_id: str, target_id: str, label: str, *, memory_ids: Sequence[str] = ()
) -> FirestoreSeed:
return FirestoreSeed(
path=f"users/{uid}/knowledge_edges/{edge_id}",
protected=True,
data={
"id": edge_id,
"source_id": source_id,
"target_id": target_id,
"label": label,
"memory_ids": list(memory_ids),
"created_at": "2026-01-10T09:00:00Z",
},
)
def _alice_default_memory_ids(ctx: DeterministicContext) -> tuple[str, ...]:
short_keys = (
"alice_short_active",
"alice_short_demo",
"alice_short_dentist",
"alice_short_grocery",
"alice_short_call_mom",
"alice_short_pr_review",
)
long_keys = (
"alice_long",
"alice_long_birthplace",
"alice_long_partner",
"alice_long_work",
"alice_long_tool_warp",
"alice_long_tool_obsidian",
"alice_long_pref_coffee",
"alice_long_pref_sf",
"alice_long_family_sister",
"alice_long_commit_rust",
"alice_long_health_running",
"alice_long_lang_spanish",
"alice_long_pet",
"alice_long_goal_marathon",
"alice_long_edu",
"alice_short_yoga",
"alice_short_presentation",
"alice_short_flights",
)
return tuple(ctx.ids[key] for key in (*short_keys, *long_keys))
def _alice_knowledge_graph_seeds(uid: str, ctx: DeterministicContext) -> list[FirestoreSeed]:
ids = ctx.ids
long_work = ids["alice_long_work"]
long_partner = ids["alice_long_partner"]
long_sf = ids["alice_long_pref_sf"]
long_warp = ids["alice_long_tool_warp"]
long_pet = ids["alice_long_pet"]
long_sister = ids["alice_long_family_sister"]
long_birthplace = ids["alice_long_birthplace"]
return [
_kg_node(uid, ids["kg_alice"], "Alice", "person"),
_kg_node(uid, ids["kg_jordan"], "Jordan Chen", "person", memory_ids=(long_partner,)),
_kg_node(uid, ids["kg_mia"], "Mia", "person", memory_ids=(long_sister,)),
_kg_node(uid, ids["kg_omi"], "Omi", "organization", memory_ids=(long_work,)),
_kg_node(uid, ids["kg_sf"], "San Francisco", "place", memory_ids=(long_sf,)),
_kg_node(uid, ids["kg_portland"], "Portland", "place", memory_ids=(long_birthplace,)),
_kg_node(uid, ids["kg_warp"], "Warp", "thing", memory_ids=(long_warp,)),
_kg_node(uid, ids["kg_pixel"], "Pixel", "thing", memory_ids=(long_pet,)),
_kg_edge(uid, "kg_edge_alice_lives_sf_030", ids["kg_alice"], ids["kg_sf"], "lives_in", memory_ids=(long_sf,)),
_kg_edge(
uid, "kg_edge_alice_works_omi_030", ids["kg_alice"], ids["kg_omi"], "works_at", memory_ids=(long_work,)
),
_kg_edge(
uid,
"kg_edge_alice_partner_jordan_030",
ids["kg_alice"],
ids["kg_jordan"],
"partner",
memory_ids=(long_partner,),
),
_kg_edge(
uid, "kg_edge_alice_sister_mia_030", ids["kg_alice"], ids["kg_mia"], "sibling", memory_ids=(long_sister,)
),
_kg_edge(uid, "kg_edge_alice_uses_warp_030", ids["kg_alice"], ids["kg_warp"], "uses", memory_ids=(long_warp,)),
_kg_edge(uid, "kg_edge_alice_pet_pixel_030", ids["kg_alice"], ids["kg_pixel"], "owns", memory_ids=(long_pet,)),
_kg_edge(
uid,
"kg_edge_alice_from_portland_030",
ids["kg_alice"],
ids["kg_portland"],
"grew_up_in",
memory_ids=(long_birthplace,),
),
]
def _base_firestore(
ctx: DeterministicContext, *, global_enabled: bool = True, kill: bool = False
) -> list[FirestoreSeed]:
uid = ALICE_USER_ID
alice_short = "Alice has a synthetic local standup at 09:00 in the lab room."
alice_long = "Alice prefers concise memory summaries for local QA."
alice_archive = "Alice archived an old synthetic project codename: Blue Acorn."
alice_stale = "Alice stale short memory that should not appear after expiry."
bob_long = "Bob keeps a separate synthetic notebook for isolation checks."
short_memories: tuple[tuple[str, str, str], ...] = (
("alice_short_active", alice_short, "2026-01-15T11:30:00Z"),
(
"alice_short_demo",
"Alice is presenting the memory platform demo to the team on Friday at 14:00.",
"2026-01-15T10:45:00Z",
),
(
"alice_short_dentist",
"Alice has a dentist appointment on Thursday at 14:30 downtown.",
"2026-01-15T09:15:00Z",
),
(
"alice_short_grocery",
"Alice needs to pick up oat milk and espresso beans after work.",
"2026-01-15T08:45:00Z",
),
(
"alice_short_call_mom",
"Alice promised to call her mom this weekend about summer travel plans.",
"2026-01-14T18:00:00Z",
),
(
"alice_short_pr_review",
"Alice needs to review PR #482 for the canonical memory adapter before end of day.",
"2026-01-14T16:00:00Z",
),
("alice_short_yoga", "Alice has yoga class Wednesday at 07:00 at Mission Yoga Studio.", "2026-01-13T06:30:00Z"),
(
"alice_short_presentation",
"Alice is preparing slides for next week's product review on Brain Map UX.",
"2026-01-12T13:20:00Z",
),
(
"alice_short_flights",
"Alice should check her SFO to Seattle flight status before Friday's trip to visit Mia.",
"2026-01-11T08:00:00Z",
),
)
promoted_short_to_long: tuple[tuple[str, str, str, str], ...] = (
(
"alice_short_yoga",
"Alice has yoga class Wednesday at 07:00 at Mission Yoga Studio.",
"2026-01-13T06:30:00Z",
"commitments",
),
(
"alice_short_presentation",
"Alice is preparing slides for next week's product review on Brain Map UX.",
"2026-01-12T13:20:00Z",
"work",
),
(
"alice_short_flights",
"Alice should check her SFO to Seattle flight status before Friday's trip to visit Mia.",
"2026-01-11T08:00:00Z",
"travel",
),
)
long_memories: tuple[tuple[str, str, str, str], ...] = (
("alice_long", alice_long, "2026-01-10T09:00:00Z", "preferences"),
(
"alice_long_birthplace",
"Alice grew up in Portland, Oregon and visits her parents there each winter.",
"2024-11-03T10:00:00Z",
"biographical",
),
(
"alice_long_partner",
"Alice's partner is Jordan Chen; they have been together since 2019.",
"2025-02-14T12:00:00Z",
"relationships",
),
(
"alice_long_work",
"Alice is a software engineer at Omi working on the memory platform and desktop sync.",
"2025-08-01T09:00:00Z",
"work",
),
(
"alice_long_tool_warp",
"Alice uses Warp as her primary terminal on macOS for local development.",
"2025-09-12T15:30:00Z",
"tools",
),
(
"alice_long_tool_obsidian",
"Alice keeps personal research notes in Obsidian with a daily journaling workflow.",
"2025-10-02T08:45:00Z",
"tools",
),
(
"alice_long_pref_coffee",
"Alice prefers oat milk lattes with no sugar, usually from local cafes in the Mission.",
"2025-05-20T07:30:00Z",
"preferences",
),
(
"alice_long_pref_sf",
"Alice lives in San Francisco's Mission District and bikes to work when weather allows.",
"2025-01-08T18:00:00Z",
"location",
),
(
"alice_long_family_sister",
"Alice's younger sister Mia lives in Seattle and works in UX research.",
"2025-03-22T19:00:00Z",
"relationships",
),
(
"alice_long_commit_rust",
"Alice is learning Rust to contribute to Omi's desktop backend components.",
"2026-02-01T10:00:00Z",
"commitments",
),
(
"alice_long_health_running",
"Alice runs a 5K three times per week, usually along the Embarcadero.",
"2025-07-15T06:00:00Z",
"health",
),
(
"alice_long_lang_spanish",
"Alice speaks conversational Spanish and is studying for professional fluency.",
"2025-11-11T20:00:00Z",
"skills",
),
(
"alice_long_pet",
"Alice has a tabby cat named Pixel who often sits on her desk during standups.",
"2025-04-18T21:00:00Z",
"relationships",
),
(
"alice_long_goal_marathon",
"Alice is training for the Oakland Marathon in fall 2026.",
"2026-01-05T07:00:00Z",
"commitments",
),
(
"alice_long_edu",
"Alice earned a BS in Computer Science from the University of Washington in 2018.",
"2024-09-01T12:00:00Z",
"biographical",
),
)
seeds: list[FirestoreSeed] = [
_global_gate(enabled=global_enabled, kill=kill),
_control(ALICE_USER_ID, default_grant=True, archive=True),
_control(BOB_USER_ID, default_grant=True, archive=False),
_memory_doc(
ALICE_USER_ID,
ctx.ids["alice_short_stale"],
"short_term",
alice_stale,
"2026-01-01T11:30:00Z",
"2026-01-02T11:30:00Z",
memory_key="alice_short_stale",
),
_memory_evidence_doc(ALICE_USER_ID, "alice_short_stale", alice_stale),
_memory_doc(ALICE_USER_ID, ctx.ids["alice_archive"], "archive", alice_archive, "2025-12-01T08:00:00Z"),
_memory_doc(BOB_USER_ID, ctx.ids["bob_long"], "long_term", bob_long, "2026-01-11T09:00:00Z"),
]
for key, content, captured in short_memories:
if any(key == promoted[0] for promoted in promoted_short_to_long):
continue
memory_id = ctx.ids[key]
_append_sourced_memory(seeds, uid, key, memory_id, "short_term", content, captured, SHORT_TERM_EXPIRES_AT)
for key, content, captured, category in promoted_short_to_long:
memory_id = ctx.ids[key]
_append_sourced_memory(seeds, uid, key, memory_id, "long_term", content, captured)
for key, content, captured, category in long_memories:
memory_id = ctx.ids[key]
_append_sourced_memory(seeds, uid, key, memory_id, "long_term", content, captured)
seeds.extend(_alice_knowledge_graph_seeds(uid, ctx))
return seeds
def _local_flags(ctx: DeterministicContext, *, enabled: bool = True) -> Mapping[str, object]:
return {
"MEMORY_V3_GET_ENABLED": "true" if enabled else "false",
"MEMORY_MODE": "read" if enabled else "off",
"MEMORY_ARCHIVE_OPT_IN_ENABLED": "true",
"MEMORY_V3_CURSOR_SECRET": ctx.cursor_secret,
"MEMORY_V3_CURSOR_POLICY_VERSION": ctx.cursor_policy_version,
"MEMORY_V3_CURSOR_SECRET_VERSION": ctx.cursor_secret_version,
"MEMORY_V3_CURSOR_TTL_SECONDS": str(ctx.cursor_ttl_seconds),
"LOCAL_EMULATOR_DEV": True,
"activation_eligible": False,
}
def _expected_protected() -> tuple[ExpectedProtectedCollectionChange, ...]:
return (
ExpectedProtectedCollectionChange("memory_control", ()),
ExpectedProtectedCollectionChange(f"users/{ALICE_USER_ID}/memory_items", ()),
ExpectedProtectedCollectionChange(f"users/{ALICE_USER_ID}/memory_evidence", ()),
ExpectedProtectedCollectionChange(f"users/{ALICE_USER_ID}/knowledge_nodes", ()),
ExpectedProtectedCollectionChange(f"users/{ALICE_USER_ID}/knowledge_edges", ()),
ExpectedProtectedCollectionChange(f"users/{BOB_USER_ID}/memory_items", ()),
)
def _scenario(
scenario_id: str,
description: str,
*,
selected_user: str = ALICE_USER_ID,
firestore: Sequence[FirestoreSeed] | None = None,
flags_enabled: bool = True,
cases: Sequence[RequestCase],
fail_closed: ExpectedFailClosedBehavior,
) -> MemoryScenario:
ctx = _clock()
return MemoryScenario(
schema_version=SCHEMA_VERSION,
scenario_id=scenario_id,
description=description,
deterministic=ctx,
users=USERS,
selected_user=selected_user,
local_flags=_local_flags(ctx, enabled=flags_enabled),
auth_seed=_auth_seed(USERS),
profile_seed=_profile_seeds(USERS),
firestore_seed=tuple(firestore if firestore is not None else _base_firestore(ctx)),
redis_seed=(RedisSeed(key=f"memory:scenario:{scenario_id}:selected_user", value=selected_user),),
file_seed=(
FileSeed(
relative_path=f"memory-scenarios/{scenario_id}/README.txt",
content=f"Synthetic local-only memory scenario: {scenario_id}\n",
),
),
request_cases=tuple(cases),
expected_protected_collection_changes=_expected_protected(),
expected_fail_closed=fail_closed,
)
def _build_scenarios() -> dict[str, MemoryScenario]:
ctx = _clock()
default_reads = _alice_default_memory_ids(ctx)
base_reads = (
GLOBAL_READ_GATE_PATH,
f"users/{ALICE_USER_ID}/memory_control/state",
)
happy = _scenario(
"happy_path",
"Enabled local memory /v3 read with synthetic Short-term and Long-term memories; Archive and stale Short-term are excluded by default.",
cases=(
RequestCase(
case_id="alice_default_read",
method="GET",
path="/v3/memories",
query={"limit": "10", "offset": "0"},
expected_status=200,
expected_route_decision="memory_read",
expected_memory_ids=default_reads,
expected_read_paths=base_reads,
),
),
fail_closed=ExpectedFailClosedBehavior(False, None),
)
default_off = _scenario(
"default_off",
"Legacy-safe default-off scenario: server env does not select memory reads and must perform zero memory adapter reads/writes.",
flags_enabled=False,
cases=(
RequestCase(
case_id="memory_route_disabled",
method="GET",
path="/v3/memories",
expected_route_decision="disabled",
expected_memory_ids=(),
),
),
fail_closed=ExpectedFailClosedBehavior(False, "memory_disabled", no_legacy_fallback=False),
)
kill = _scenario(
"kill_switch",
"Global memory read kill switch is active; Memory selection must fail closed with no legacy fallback after selection.",
firestore=_base_firestore(ctx, global_enabled=True, kill=True),
cases=(
RequestCase(
case_id="kill_switch_blocks",
method="GET",
path="/v3/memories",
expected_status=403,
expected_route_decision="fail_closed",
expected_fail_closed_reason="global_memory_read_kill_switch_active",
),
),
fail_closed=ExpectedFailClosedBehavior(True, "global_memory_read_kill_switch_active"),
)
malformed_cursor = _scenario(
"malformed_cursor",
"Malformed memory cursor must return a stable fail-closed client error and never disclose cross-user state.",
cases=(
RequestCase(
case_id="malformed_cursor",
method="GET",
path="/v3/memories",
query={"cursor": ctx.cursors["malformed"]},
expected_status=400,
expected_route_decision="fail_closed",
expected_fail_closed_reason="malformed_cursor",
),
),
fail_closed=ExpectedFailClosedBehavior(True, "malformed_cursor"),
)
stale = _scenario(
"stale_short_exclusion",
"Default read excludes expired Short-term records while keeping active Short-term and Long-term records visible.",
cases=(
RequestCase(
case_id="stale_short_excluded",
method="GET",
path="/memory/search",
expected_memory_ids=default_reads,
expected_route_decision="memory_read",
expected_read_paths=base_reads,
),
),
fail_closed=ExpectedFailClosedBehavior(False, None),
)
archive = _scenario(
"archive_default_exclusion",
"Archive memories exist but default reads exclude them unless an explicit archive-capable route is used.",
cases=(
RequestCase(
case_id="archive_not_in_default",
method="GET",
path="/v3/memories",
expected_memory_ids=default_reads,
expected_route_decision="memory_read",
expected_read_paths=base_reads,
),
RequestCase(
case_id="archive_explicit",
method="GET",
path="/memory/archive/search",
query={"include_archive": "true"},
expected_memory_ids=(ctx.ids["alice_archive"],),
expected_route_decision="memory_read",
),
),
fail_closed=ExpectedFailClosedBehavior(False, None),
)
isolation = _scenario(
"cross_user_isolation",
"Alice and Bob are both seeded; Alice requests must never return Bob's synthetic memory even with a cross-user cursor.",
cases=(
RequestCase(
case_id="alice_default_no_bob",
method="GET",
path="/v3/memories",
authenticated_user=ALICE_USER_ID,
expected_memory_ids=default_reads,
expected_route_decision="memory_read",
),
RequestCase(
case_id="alice_with_bob_cursor",
method="GET",
path="/v3/memories",
authenticated_user=ALICE_USER_ID,
query={"cursor": ctx.cursors["cross_user_bob"]},
expected_status=400,
expected_route_decision="fail_closed",
expected_fail_closed_reason="cursor_subject_mismatch",
),
),
fail_closed=ExpectedFailClosedBehavior(True, "cursor_subject_mismatch"),
)
return {s.scenario_id: s for s in (happy, default_off, kill, malformed_cursor, stale, archive, isolation)}
SCENARIOS = _build_scenarios()
def _jsonable(value: object) -> object:
if is_dataclass(value):
return {k: _jsonable(v) for k, v in asdict(value).items()} # type: ignore[arg-type]
if isinstance(value, Mapping):
return {str(k): _jsonable(v) for k, v in value.items()}
if isinstance(value, tuple | list):
return [_jsonable(v) for v in value]
return value
def scenario_digest(scenario: MemoryScenario) -> str:
payload = json.dumps(_jsonable(scenario), sort_keys=True, separators=(",", ":"))
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
def list_scenarios() -> tuple[MemoryScenario, ...]:
return tuple(SCENARIOS[name] for name in sorted(SCENARIOS))
def get_scenario(scenario_id: str) -> MemoryScenario:
try:
return SCENARIOS[scenario_id]
except KeyError as exc:
raise ValueError(
f"Unknown memory scenario {scenario_id!r}; choose one of {', '.join(sorted(SCENARIOS))}"
) from exc
def validate_scenario(scenario: MemoryScenario) -> None:
if scenario.schema_version != SCHEMA_VERSION:
raise ValueError(f"Unsupported scenario schema_version={scenario.schema_version}")
if scenario.scenario_id not in SCENARIOS:
raise ValueError("Scenario ID must be registered")
user_ids = {user.uid for user in scenario.users}
required = {
DEFAULT_LOCAL_USER_ID,
ALICE_USER_ID,
BOB_USER_ID,
CHAT_FIRST_E2E_ENABLED_USER_ID,
CHAT_FIRST_E2E_DISABLED_CONTROL_USER_ID,
}
if not required.issubset(user_ids):
raise ValueError(f"Scenario users must include {sorted(required)}")
if scenario.selected_user not in user_ids:
raise ValueError("selected_user must be one of scenario.users")
if scenario.report_metadata.evidence_class != EVIDENCE_CLASS or scenario.report_metadata.activation_eligible:
raise ValueError("Local scenario report metadata must remain LOCAL_EMULATOR_DEV and activation_eligible=false")
for seed in (*scenario.profile_seed, *scenario.firestore_seed):
if not seed.path or seed.path.startswith("/") or ".." in seed.path.split("/"):
raise ValueError(f"Unsafe Firestore seed path {seed.path!r}")
if "evidence_class" in seed.data or "activation_eligible" in seed.data:
raise ValueError("Fixture seed documents cannot select evidence/report labels")
for request in scenario.request_cases:
if request.method != "GET":
raise ValueError("Local memory scenario request cases are read-only GET paths in this slice")
if request.expected_no_write is not True:
raise ValueError("GET request cases must assert no memory writes")
if request.authenticated_user not in user_ids:
raise ValueError("Request authenticated_user must be a synthetic scenario user")
if scenario.local_flags.get("activation_eligible") is not False:
raise ValueError("local_flags must hard-code activation_eligible=false")
def validate_all_scenarios() -> None:
for scenario in SCENARIOS.values():
validate_scenario(scenario)
def _now() -> str:
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def _metadata_operation(scenario: MemoryScenario) -> SeedOperation:
return SeedOperation(
kind="metadata",
action="write",
target=f"scenario:{scenario.scenario_id}",
payload={
"scenario_id": scenario.scenario_id,
"scenario_digest": scenario_digest(scenario),
"selected_user": scenario.selected_user,
"report_metadata": _jsonable(scenario.report_metadata),
},
)
def _lookup_auth_uid(cfg: config.HarnessConfig, email: str, password: str) -> str:
url = f"http://{cfg.auth_host}/identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=local-dev-harness"
status, body = _request_json(
"POST",
url,
{"email": email, "password": password, "returnSecureToken": True},