-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory.py
More file actions
1885 lines (1604 loc) · 69.1 KB
/
Copy pathmemory.py
File metadata and controls
1885 lines (1604 loc) · 69.1 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
# Friday memory. Made by me, 01/JUN/2026 <3
import argparse
import contextlib
import hashlib
import json
import math
import os
import re
import shutil
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
MEMORY_DIR = Path.home() / ".config" / "friday" / "memory"
DATA_DIR = MEMORY_DIR / "data"
FACTS_FILE = DATA_DIR / "facts.json"
CONVERSATIONS_FILE = DATA_DIR / "conversations.json"
AUDIT_LOG = DATA_DIR / "audit.json"
EMBEDDINGS_FILE = DATA_DIR / "embeddings.json"
WORKING_MEMORY_FILE = DATA_DIR / "working_memory.json"
TFIDF_CACHE_FILE = DATA_DIR / "tfidf_cache.json"
_EMBEDDING_CACHE = None
_WRITE_LOCK_DIR = None
CONFIDENCE_THRESHOLD_GENERAL = 0.5
CONFIDENCE_THRESHOLD_STRICT = 0.7
STALE_DAYS = 180
ARCHIVE_DAYS = 365
INFERRED_CONFIDENCE_CAP = 0.69
MIN_CONFIDENCE_THRESHOLD = 0.15
LOW_QUALITY_CONFIDENCE = 0.2
LOW_QUALITY_DAYS = 30
IDENTITY_DRIFT_DAYS = 90
IDENTITY_CONFIRM_DAYS = 60
REDUNDANCY_THRESHOLD = 0.95
MAX_AUTO_EXTRACT = 5
DEFAULT_CONFIDENCE = 0.5
SCHEMA_VERSION = 1
PLURAL_PREDICATES = {
'likes', 'dislikes', 'loves', 'hates', 'prefers', 'enjoys',
'plays', 'uses', 'owns', 'has', 'wants', 'needs',
'knows', 'speaks', 'codes_in', 'works_on',
'visits', 'has_visited', 'has_played', 'has_read', 'has_watched', 'has_worked_on',
'listens_to',
}
STOPWORDS = {
'a', 'an', 'the', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',
'of', 'with', 'by', 'from', 'is', 'are', 'was', 'were', 'be', 'been',
'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would',
'could', 'should', 'may', 'might', 'shall', 'can', 'need', 'dare',
'ought', 'used', 'it', 'its', "it's", 'i', 'you', 'he', 'she', 'we',
'they', 'me', 'him', 'her', 'us', 'them', 'my', 'your', 'his', 'her',
'our', 'their', 'this', 'that', 'these', 'those', 'what', 'which',
'who', 'whom', 'when', 'where', 'why', 'how', 'all', 'each', 'every',
'both', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'not',
'only', 'own', 'same', 'so', 'than', 'too', 'very', 'just', 'because',
'as', 'until', 'while', 'about', 'between', 'through', 'during',
'before', 'after', 'above', 'below', 'up', 'down', 'out', 'off',
'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there',
"didn't", "don't", "doesn't", "isn't", "aren't", "wasn't",
"weren't", "haven't", "hasn't", "hadn't", "won't", "wouldn't",
"couldn't", "shouldn't", 'let', 'get', 'got', 'gotten', 'make',
'made', 'said', 'say', 'says', 'going', 'go', 'went', 'gone', 'come',
'came', 'take', 'took', 'taken', 'like', 'want', 'know', 'think',
'see', 'use', 'used', 'using', 'done', 'doing', 'does', 'got',
'well', 'back', 'also', 'ever', 'much', 'still', 'even', 'yet',
'already', 'though', 'although', 'since', 'any', 'anything',
'something', 'nothing', 'everything', 'thing', 'things', 'way',
'many', 'lot', 'really', 'quite', 'actually', 'basically', 'pretty',
'probably', 'maybe', 'perhaps', 'anyway', 'though', 'however',
'therefore', 'thus', 'hence', 'indeed', 'instead', 'either',
'neither', 'whether', 'whatever', 'whoever', 'whenever', 'wherever',
'however', 'forever', 'always', 'never', 'sometimes', 'often',
'rarely', 'usually', 'typically', 'generally', 'especially',
}
_EMBEDDER = None
def _now():
return datetime.now(timezone.utc).isoformat()
def _ts():
return int(time.time())
@contextlib.contextmanager
def _write_lock(timeout=5):
global _WRITE_LOCK_DIR
lock_dir = DATA_DIR / ".write_lock"
start = time.time()
while True:
try:
lock_dir.mkdir(parents=True, exist_ok=False)
_WRITE_LOCK_DIR = lock_dir
break
except FileExistsError:
if time.time() - start > timeout:
raise TimeoutError("Could not acquire write lock — another process may be writing")
time.sleep(0.1)
try:
yield
finally:
try:
lock_dir.rmdir()
except Exception:
pass
_WRITE_LOCK_DIR = None
def _load_json(path):
if not path.exists():
return []
with open(path, 'r', encoding='utf-8') as f:
obj = json.load(f)
if isinstance(obj, dict) and 'items' in obj:
return obj['items']
return obj
def _save_json(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
backup_dir = path.parent / 'backups'
if path.name == 'facts.json':
backup_dir.mkdir(exist_ok=True)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
bpath = backup_dir / f'facts_{timestamp}.json.backup'
try:
if path.exists():
shutil.copy2(path, bpath)
except: pass
try:
backups = sorted([p for p in backup_dir.iterdir() if p.suffix == '.backup'])
while len(backups) > 20:
backups[0].unlink()
backups.pop(0)
except: pass
tmp = path.with_suffix('.tmp')
with open(tmp, 'w', encoding='utf-8') as f:
json.dump({"schema_version": SCHEMA_VERSION, "items": data}, f, indent=2, ensure_ascii=False)
tmp.replace(path)
def _load_embeddings():
global _EMBEDDING_CACHE
if _EMBEDDING_CACHE is not None:
return _EMBEDDING_CACHE
if not EMBEDDINGS_FILE.exists():
_EMBEDDING_CACHE = {}
return _EMBEDDING_CACHE
with open(EMBEDDINGS_FILE, 'r', encoding='utf-8') as f:
_EMBEDDING_CACHE = json.load(f)
return _EMBEDDING_CACHE
def _save_embeddings(data):
global _EMBEDDING_CACHE
EMBEDDINGS_FILE.parent.mkdir(parents=True, exist_ok=True)
tmp = EMBEDDINGS_FILE.with_suffix('.tmp')
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(data, f, separators=(',', ':'), ensure_ascii=False)
tmp.replace(EMBEDDINGS_FILE)
_EMBEDDING_CACHE = data
def _get_embedding(fact_id):
store = _load_embeddings()
return store.get(fact_id)
def _set_embedding(fact_id, vector):
store = _load_embeddings()
store[fact_id] = vector
_save_embeddings(store)
def _delete_embedding(fact_id):
store = _load_embeddings()
store.pop(fact_id, None)
_save_embeddings(store)
# --- working memory: what's on the table right now, session-scoped ---
SESSION_IDLE_MINUTES = 30
def _load_working_memory():
if not WORKING_MEMORY_FILE.exists():
return _new_session()
with open(WORKING_MEMORY_FILE, 'r', encoding='utf-8') as f:
data = json.load(f)
now = datetime.now(timezone.utc)
if not data.get('session_id'):
return _new_session()
last_time = data.get('last_query_time')
if last_time:
try:
idle = (now - datetime.fromisoformat(last_time)).total_seconds() / 60
if idle > SESSION_IDLE_MINUTES:
return _new_session()
except Exception:
pass
data.setdefault('session_start', data.get('session_id', _now()))
data.setdefault('recent_queries', [])
data.setdefault('active', [])
return data
def _new_session():
now = _now()
return {
"session_id": f"sess_{_ts()}",
"session_start": now,
"last_query_time": now,
"active": [],
"recent_queries": [],
}
def _save_working_memory(data):
data['last_query_time'] = _now()
WORKING_MEMORY_FILE.parent.mkdir(parents=True, exist_ok=True)
tmp = WORKING_MEMORY_FILE.with_suffix('.tmp')
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
tmp.replace(WORKING_MEMORY_FILE)
def _bump_topic(data, topic, entities=None):
now_str = _now()
for t in data['active']:
if t['topic'].lower() == topic.lower():
t['last_bumped'] = now_str
t['bump_count'] = t['bump_count'] + 1
t['decay_count'] = 0
increment = 0.2 * (0.7 ** (t['bump_count'] - 1))
t['relevance'] = min(0.9, t['relevance'] + increment)
if entities:
existing = set(e.lower() for e in t.get('entities', []))
for e in entities:
if e.lower() not in existing:
t['entities'].append(e)
existing.add(e.lower())
return
data['active'].append({
"topic": topic,
"entities": [e for e in (entities or [])],
"last_bumped": now_str,
"bump_count": 1,
"decay_count": 0,
"relevance": 0.8,
})
def _decay_working_memory(data):
kept = []
for t in data['active']:
t['decay_count'] = t.get('decay_count', 0) + 1
if t['decay_count'] >= 10:
t['relevance'] = 0.0
else:
t['relevance'] = round(max(0.0, t['relevance'] - 0.2), 2)
if t['relevance'] >= 0.1:
kept.append(t)
data['active'] = kept
def _get_active_context(data):
parts = []
for t in data['active']:
if t['relevance'] < 0.3:
continue
parts.append(t['topic'])
parts.extend(t.get('entities', []))
return ' '.join(parts) if parts else ''
def _add_recent_query(data, query):
data.setdefault('recent_queries', [])
data['recent_queries'].append(query)
data['recent_queries'] = data['recent_queries'][-5:]
PROMOTE_BUMP_THRESHOLD = 5
PROMOTE_RELEVANCE_THRESHOLD = 0.6
def _promote_working_memory(wm, facts, embeddings):
promoted = 0
now_str = _now()
for t in wm['active']:
if t['bump_count'] < PROMOTE_BUMP_THRESHOLD:
continue
if t['relevance'] < PROMOTE_RELEVANCE_THRESHOLD:
continue
topic = t['topic']
entities = t.get('entities', [])
obj_parts = [topic]
obj_parts.extend(e for e in entities if e.lower() not in topic.lower())
obj_str = ', '.join(obj_parts)
candidate = {
"id": f"fact_{time.time_ns()}",
"type": "concept",
"category": "auto",
"subject": "user",
"predicate": "related_to",
"object": obj_str,
"summary": f"Auto-promoted: {topic}",
"details": {"promoted_from": topic, "entities": entities},
"source": {"origin": "inferred", "timestamp": now_str},
"memory_properties": {
"confidence": 0.3,
"importance": 0.3,
"stability": "quarantine",
},
"retrieval": {"tags": ["auto-promoted", topic]},
"last_updated": now_str,
"update_count": 1,
}
_init_salience(candidate['memory_properties'], 0.3)
emb = _compute_embedding(candidate['summary'])
dup, match_type = _find_duplicate(candidate, facts, emb)
if dup:
t['bump_count'] = 0
continue
facts.append(candidate)
if emb:
embeddings[candidate['id']] = emb
_log_operation('created', f'auto-promoted from working memory topic: {topic}', [candidate['id']])
promoted += 1
t['bump_count'] = 0
return promoted
def _get_embedder():
global _EMBEDDER
if _EMBEDDER is None:
try:
from sentence_transformers import SentenceTransformer
_EMBEDDER = SentenceTransformer('all-MiniLM-L6-v2')
except Exception:
_EMBEDDER = False
return _EMBEDDER if _EMBEDDER is not False else None
def _compute_embedding(text):
model = _get_embedder()
if model is None:
return None
emb = model.encode(text, normalize_embeddings=True)
return emb.tolist()
def _cosine_sim_vec(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(x * x for x in b))
return dot / (na * nb) if na and nb else 0
def _tokenize(text):
text = text.lower()
tokens = re.findall(r"[a-z0-9]+(?:'[a-z0-9]+)*", text)
return [t for t in tokens if t not in STOPWORDS and len(t) > 1]
def _compute_tf(tokens):
tf = {}
for t in tokens:
tf[t] = tf.get(t, 0) + 1
length = len(tokens)
if length > 0:
for t in tf:
tf[t] /= length
return tf
def _compute_idf(documents):
n = len(documents)
idf = {}
for doc in documents:
seen = set(doc)
for term in seen:
idf[term] = idf.get(term, 0) + 1
for term, count in idf.items():
idf[term] = math.log((n + 1) / (count + 1)) + 1
return idf
def _cosine_similarity(vec1, vec2):
dot = 0
for term, val in vec1.items():
if term in vec2:
dot += val * vec2[term]
norm1 = math.sqrt(sum(v * v for v in vec1.values()))
norm2 = math.sqrt(sum(v * v for v in vec2.values()))
if norm1 == 0 or norm2 == 0:
return 0
return dot / (norm1 * norm2)
def _get_search_text(item):
if 'content' in item:
return item['content']
if 'summary' in item:
title = item.get('title', item.get('type', ''))
decisions = item.get('decisions', [])
obj_val = item.get('object', '')
if isinstance(obj_val, list):
obj_text = ' '.join(obj_val)
else:
obj_text = obj_val
extra = ' '.join([item.get('subject', ''), item.get('predicate', ''), obj_text])
return f"{title} {item['summary']} {extra} {' '.join(decisions)}"
return ''
# audit trail. every mutation gets logged so you can trace where a belief came from, or see where the AI fucked up.
def _log_operation(operation, reason, source_ids):
log = _load_json(AUDIT_LOG)
entry = {
"operation": operation,
"reason": reason,
"source_ids": source_ids,
"timestamp": _now(),
}
log.append(entry)
_save_json(AUDIT_LOG, log)
#
# retrieval = tfidf + embeddings, because either one alone misses stuff
#
_TFIDF_CACHE = None
def _tfidf_cache_valid(items):
if _TFIDF_CACHE is None:
return False
h = hashlib.md5('|'.join(
item['id'] + str(item.get('update_count', item.get('message_count', 0)))
for item in items
).encode()).hexdigest()
return _TFIDF_CACHE.get('hash') == h
def _build_tfidf_cache(items):
global _TFIDF_CACHE
docs = [_tokenize(_get_search_text(item)) for item in items]
idf = _compute_idf(docs)
doc_tokens = docs
h = hashlib.md5('|'.join(
item['id'] + str(item.get('update_count', item.get('message_count', 0)))
for item in items
).encode()).hexdigest()
cache = {'hash': h, 'idf': idf, 'doc_tokens': doc_tokens}
try:
with _write_lock():
tmp = TFIDF_CACHE_FILE.with_suffix('.tmp')
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(cache, f, ensure_ascii=False)
tmp.replace(TFIDF_CACHE_FILE)
except Exception:
pass
_TFIDF_CACHE = cache
def _load_tfidf_cache(items):
global _TFIDF_CACHE
if _tfidf_cache_valid(items):
return _TFIDF_CACHE
if TFIDF_CACHE_FILE.exists():
try:
with open(TFIDF_CACHE_FILE, 'r', encoding='utf-8') as f:
cached = json.load(f)
h = hashlib.md5('|'.join(
item['id'] + str(item.get('update_count', item.get('message_count', 0)))
for item in items
).encode()).hexdigest()
if cached.get('hash') == h:
_TFIDF_CACHE = cached
return _TFIDF_CACHE
except Exception:
pass
_build_tfidf_cache(items)
return _TFIDF_CACHE
def _invalidate_tfidf_cache():
global _TFIDF_CACHE
_TFIDF_CACHE = None
try:
TFIDF_CACHE_FILE.unlink(missing_ok=True)
except Exception:
pass
def _score_tfidf(items, query):
if not items or not query:
return [0.0] * len(items)
query_tokens = _tokenize(query)
if not query_tokens:
return [0.0] * len(items)
cache = _load_tfidf_cache(items)
idf = cache['idf']
doc_tokens = cache['doc_tokens']
query_tf = _compute_tf(query_tokens)
query_vec = {t: query_tf.get(t, 0) * idf.get(t, 0) for t in query_tf}
scores = []
for tokens in doc_tokens:
doc_tf = _compute_tf(tokens)
doc_vec = {t: doc_tf.get(t, 0) * idf.get(t, 0) for t in doc_tf}
scores.append(_cosine_similarity(query_vec, doc_vec))
return scores
def _score_embeddings(items, query):
q_emb = _compute_embedding(query)
if q_emb is None:
return [0.0] * len(items)
embed_store = _load_embeddings()
scores = []
for item in items:
d_emb = embed_store.get(item.get('id'))
if d_emb:
scores.append(_cosine_sim_vec(q_emb, d_emb))
else:
scores.append(0.0)
return scores
def search(items, query, limit=5):
if not items or not query:
return []
tfidf = _score_tfidf(items, query)
emb = _score_embeddings(items, query)
now = datetime.now(timezone.utc)
scored = []
for i, item in enumerate(items):
ts_str = item.get('source', {}).get('timestamp', item.get('date', ''))
if ts_str:
try:
age_days = (now - datetime.fromisoformat(ts_str)).total_seconds() / 86400
except Exception:
age_days = 0
else:
age_days = 0
recency = math.exp(-age_days / 90)
importance = _compute_effective_importance(item)
score = tfidf[i] * 0.25 + emb[i] * 0.55 + recency * 0.15 + importance * 0.05
confidence = item.get('memory_properties', {}).get('confidence', 0)
score *= (0.5 + confidence * 0.5)
if score > 0:
scored.append((score, item))
scored.sort(key=lambda x: -x[0])
return [item for _, item in scored[:limit]]
# filter pass after scoring (confidence and freshness)
def _filter_retrieval(items, include_archived=False, include_stale=False, include_historical=False, strict=False):
now = datetime.now(timezone.utc)
threshold = CONFIDENCE_THRESHOLD_STRICT if strict else CONFIDENCE_THRESHOLD_GENERAL
filtered = []
for item in items:
props = item.get('memory_properties', {})
stability = props.get('stability', 'temporary')
if stability in ('archived', 'quarantine') and not include_archived:
continue
if props.get('historical') and not include_historical:
continue
confidence = props.get('confidence', 0.0)
if confidence < threshold:
continue
ts_str = item.get('source', {}).get('timestamp', '')
if ts_str:
try:
age_days = (now - datetime.fromisoformat(ts_str)).total_seconds() / 86400
except Exception:
age_days = 0
else:
age_days = 0
update_count = item.get('update_count', 1)
if update_count == 1 and age_days > STALE_DAYS and not include_stale:
continue
importance = _compute_effective_importance(item)
filtered.append((importance, item))
filtered.sort(key=lambda x: -x[0])
return [item for _, item in filtered]
# dedupe. if it's basically the same fact again, merge instead of stacking copies.
DEDUP_THRESHOLD = 0.75
def _find_duplicate(new_fact, facts, new_embedding=None):
new_subj = new_fact.get('subject', '')
new_pred = new_fact.get('predicate', '')
new_obj = new_fact.get('object', '')
new_emb = new_embedding or _get_embedding(new_fact.get('id'))
for existing in facts:
existing_emb = _get_embedding(existing.get('id'))
if new_subj and new_pred and new_obj:
existing_obj = existing.get('object')
if existing.get('subject') == new_subj and existing.get('predicate') == new_pred:
if isinstance(existing_obj, list):
if new_obj in existing_obj:
return existing, 'exact'
elif existing_obj == new_obj:
return existing, 'exact'
if new_emb and existing_emb:
sim = _cosine_sim_vec(new_emb, existing_emb)
if sim >= REDUNDANCY_THRESHOLD:
return existing, 'redundant'
if sim >= DEDUP_THRESHOLD:
return existing, 'semantic'
if not new_emb and not existing_emb:
ns = _get_search_text(new_fact)
es = _get_search_text(existing)
if ns and es:
tok_n = set(_tokenize(ns))
tok_e = set(_tokenize(es))
if tok_n and tok_e:
jaccard = len(tok_n & tok_e) / len(tok_n | tok_e)
if jaccard >= 0.80:
return existing, 'fuzzy'
return None, None
def _merge_fact(target, incoming):
target['update_count'] = target.get('update_count', 0) + 1
target['last_updated'] = _now()
existing_tags = set(target.get('retrieval', {}).get('tags', []))
new_tags = set(incoming.get('retrieval', {}).get('tags', []))
merged_tags = sorted(existing_tags | new_tags)
target.setdefault('retrieval', {})['tags'] = merged_tags
props = target.setdefault('memory_properties', {})
in_props = incoming.get('memory_properties', {})
props['confidence'] = round(min(1.0, max(props.get('confidence', 0), in_props.get('confidence', 0)) + 0.05), 2)
props['importance'] = round(max(props.get('importance', 0), in_props.get('importance', 0)), 2)
stability_order = {'quarantine': -1, 'temporary': 0, 'evolving': 1, 'stable': 2, 'permanent': 3}
cur_stab = props.get('stability', 'temporary')
in_stab = in_props.get('stability', 'temporary')
if stability_order.get(in_stab, 0) > stability_order.get(cur_stab, 0):
props['stability'] = in_stab
if target.get('update_count', 0) >= 3 and props.get('stability') == 'temporary':
props['stability'] = 'evolving'
if target.get('update_count', 0) >= 5 and props.get('stability') == 'evolving':
props['stability'] = 'stable'
if target.get('update_count', 0) >= 10 and props.get('stability') == 'stable':
props['stability'] = 'permanent'
if incoming.get('details') and not target.get('details'):
target['details'] = incoming['details']
if target.get('type') == 'identity':
target.setdefault('memory_properties', {}).setdefault('salience', {})['last_confirmed'] = _now()
target_sal = target.get('memory_properties', {}).get('salience')
in_sal = incoming.get('memory_properties', {}).get('salience')
if target_sal and in_sal:
target_sal['retrieval_count'] = max(target_sal.get('retrieval_count', 0), in_sal.get('retrieval_count', 0))
if in_sal.get('last_retrieved'):
if not target_sal.get('last_retrieved') or in_sal['last_retrieved'] > target_sal['last_retrieved']:
target_sal['last_retrieved'] = in_sal['last_retrieved']
target_sal['conversation_references'] = max(target_sal.get('conversation_references', 0), in_sal.get('conversation_references', 0))
# conflicting facts on the same (subject, predicate) can't both sit there quietly.
# one of them has to lose...
_STAB_ORDER = {'quarantine': -1, 'temporary': 0, 'evolving': 1, 'stable': 2, 'permanent': 3}
def _fact_strength(fact):
props = fact.get('memory_properties', {})
conf = props.get('confidence', 0.0)
origin = fact.get('source', {}).get('origin', 'inferred')
stab = _STAB_ORDER.get(props.get('stability', 'temporary'), 0)
return conf + (0.2 if origin == 'conversation' else 0) + stab * 0.1
def _is_plural(predicate, incoming_fact):
if predicate in PLURAL_PREDICATES:
return True
if incoming_fact.get('memory_properties', {}).get('plural'):
return True
return False
def _resolve_conflict(incoming, facts):
subj = incoming.get('subject', '')
pred = incoming.get('predicate', '')
if not subj or not pred:
return None, None, None
obj = incoming.get('object', '')
for existing in facts:
if (existing.get('subject') == subj
and existing.get('predicate') == pred
and existing.get('memory_properties', {}).get('stability') != 'archived'):
existing_obj = existing.get('object')
if isinstance(existing_obj, list):
if obj in existing_obj:
return None, None, None
elif existing_obj == obj:
return None, None, None
if _is_plural(pred, incoming) or existing.get('memory_properties', {}).get('plural'):
return 'plural_merge', existing['id'], f"plural predicate — appending '{obj}' to existing"
existing_score = _fact_strength(existing)
incoming_score = _fact_strength(incoming)
diff = abs(existing_score - incoming_score)
existing_origin = existing.get('source', {}).get('origin', 'inferred')
incoming_origin = incoming.get('source', {}).get('origin', 'inferred')
if diff >= 0.3:
if existing_score > incoming_score:
_merge_fact(existing, incoming)
msg = f"conflict: existing subsumed incoming ({existing_score:.2f} vs {incoming_score:.2f})"
return 'merged', existing['id'], msg
else:
incoming['update_count'] = existing.get('update_count', 0) + 1
incoming['last_updated'] = _now()
_merge_fact(incoming, existing)
for i, f in enumerate(facts):
if f['id'] == existing['id']:
facts[i] = incoming
break
msg = f"conflict: incoming subsumed existing ({incoming_score:.2f} vs {existing_score:.2f})"
return 'absorbed', incoming.get('id', existing['id']), msg
elif existing_origin == 'inferred' and incoming_origin != 'inferred':
existing['memory_properties']['stability'] = 'archived'
msg = f"conflict: archived weaker inferred fact (conf {existing_score:.2f})"
return 'archived', existing['id'], msg
elif incoming_origin == 'inferred' and existing_origin != 'inferred':
msg = f"conflict: rejected lower-confidence inferred fact (conf {incoming_score:.2f})"
return 'rejected', existing['id'], msg
else:
incoming_id = incoming.get('id')
existing['memory_properties']['historical'] = True
existing['memory_properties']['superseded_by'] = incoming_id
incoming['memory_properties']['supersedes'] = existing.get('id')
if existing.get('type') == 'identity':
existing.setdefault('details', {})['drift'] = True
facts.append(incoming)
drift_tag = ' (identity drift)' if existing.get('type') == 'identity' else ''
msg = f"preference evolution: {existing.get('id')} superseded by {incoming_id}{drift_tag}"
return 'superseded', existing['id'], msg
return None, None, None
# salience = how much a fact actually matters, separate from raw importance.
# not every stored fact is equally worth surfacing.
def _init_salience(props, importance):
props.setdefault('salience', {
"base_importance": importance,
"retrieval_count": 0,
"last_retrieved": None,
"last_confirmed": _now(),
"conversation_references": 0,
"decay_rate": 1.0,
})
def _bump_salience(fact):
props = fact.get('memory_properties', {})
sal = props.get('salience')
if sal:
sal['retrieval_count'] = sal.get('retrieval_count', 0) + 1
sal['last_retrieved'] = _now()
if fact.get('type') == 'identity':
sal['last_confirmed'] = _now()
def _compute_effective_importance(fact):
props = fact.get('memory_properties', {})
sal = props.get('salience')
if not sal:
return props.get('importance', 0.0)
base = sal.get('base_importance', props.get('importance', 0.0))
rc = sal.get('retrieval_count', 0)
bonus = min(0.2, rc * 0.01)
return round(base + bonus, 2)
# ---- aging. memory that's never used slowly like gets forgot, then gets archived. ----
def _apply_aging(facts):
now = datetime.now(timezone.utc)
changed = False
to_delete = set()
for f in facts:
props = f.get('memory_properties', {})
stability = props.get('stability', 'temporary')
ts_str = f.get('source', {}).get('timestamp', f.get('created'))
if not ts_str:
continue
try:
age_days = (now - datetime.fromisoformat(ts_str)).total_seconds() / 86400
except Exception:
age_days = 0
if stability in ('temporary', 'evolving'):
sal = props.get('salience', {})
rc = sal.get('retrieval_count', 0) if sal else 0
salience_factor = max(0.2, 1.0 - (rc * 0.01))
decay = max(0.1, 1.0 - (age_days * 0.002 * salience_factor))
new_conf = round(props.get('confidence', 0.0) * decay, 2)
if new_conf != props.get('confidence', 0.0):
props['confidence'] = new_conf
changed = True
if f.get('type') == 'identity' and stability in ('temporary', 'evolving', 'stable'):
sal = props.get('salience', {})
confirmed_str = sal.get('last_confirmed', ts_str) if sal else ts_str
try:
confirmed_age = (now - datetime.fromisoformat(confirmed_str)).total_seconds() / 86400
except Exception:
confirmed_age = 0
if confirmed_age > IDENTITY_CONFIRM_DAYS:
identity_decay = max(0.5, 1.0 - (confirmed_age - IDENTITY_CONFIRM_DAYS) * 0.002)
new_conf = round(props.get('confidence', 0.0) * identity_decay, 2)
if new_conf != props.get('confidence', 0.0):
props['confidence'] = new_conf
changed = True
conf = props.get('confidence', 0.0)
if stability == 'temporary' and conf < 0.15:
props['stability'] = 'archived'
_log_operation('archived', f'auto-archived (confidence {conf:.2f} below threshold)', [f['id']])
changed = True
if stability not in ('permanent', 'archived') and f.get('update_count', 1) <= 1:
if f.get('type') != 'identity':
if age_days > ARCHIVE_DAYS:
props['stability'] = 'archived'
_log_operation('archived', f'auto-archived after {int(age_days)} days without update', [f['id']])
changed = True
elif stability == 'temporary' and age_days > 90:
props['stability'] = 'archived'
_log_operation('archived', f'auto-archived after {int(age_days)} days (unconfirmed temporary)', [f['id']])
changed = True
old_stab = stability
update_count = f.get('update_count', 0)
if update_count >= 3 and stability == 'temporary':
props['stability'] = 'evolving'
if update_count >= 5 and stability == 'evolving':
props['stability'] = 'stable'
if update_count >= 10 and stability == 'stable':
props['stability'] = 'permanent'
if props.get('stability') != old_stab:
changed = True
if conf < LOW_QUALITY_CONFIDENCE and age_days > LOW_QUALITY_DAYS:
to_delete.add(f['id'])
if to_delete:
facts[:] = [f for f in facts if f['id'] not in to_delete]
for fid in to_delete:
_delete_embedding(fid)
_log_operation('deleted', f'low-quality fact pruned (conf < {LOW_QUALITY_CONFIDENCE} for > {LOW_QUALITY_DAYS} days)', [fid])
changed = True
return changed
# integrity, validation shi like that. cheap checks to keep the store from drifting into garbage.
VALID_TYPES = {'preference', 'project', 'relationship', 'workflow', 'event', 'identity', 'goal', 'habit', 'general', 'concept'}
VALID_STABILITIES = {'temporary', 'evolving', 'stable', 'permanent', 'archived', 'quarantine'}
VALID_ORIGINS = {'conversation', 'system', 'user_import', 'inferred'}
def _validate_fact(fact):
errors = []
for field in ['id', 'type', 'summary']:
if not fact.get(field):
errors.append(f"missing required field: {field}")
if fact.get('type') and fact['type'] not in VALID_TYPES:
errors.append(f"invalid type: {fact['type']}")
props = fact.get('memory_properties', {})
if props:
conf = props.get('confidence')
if conf is not None and not isinstance(conf, (int, float)):
errors.append("confidence must be a number")
elif conf is not None and (conf < 0 or conf > 1):
errors.append(f"confidence out of range [0-1]: {conf}")
stab = props.get('stability')
if stab and stab not in VALID_STABILITIES:
errors.append(f"invalid stability: {stab}")
source = fact.get('source', {})
if source:
origin = source.get('origin')
if origin and origin not in VALID_ORIGINS:
errors.append(f"invalid origin: {origin}")
if not source.get('timestamp'):
errors.append("missing source.timestamp")
return errors
def _find_orphan_embeddings(facts, embeddings):
fact_ids = {f['id'] for f in facts}
return [eid for eid in embeddings if eid not in fact_ids]
def _find_missing_embeddings(facts, embeddings):
return [f['id'] for f in facts if f['id'] not in embeddings]
def _find_orphan_audit_entries(audit, fact_ids, conv_ids):
valid_ids = fact_ids | conv_ids
orphans = []
for entry in audit:
for sid in entry.get('source_ids', []):
if sid not in valid_ids:
orphans.append((entry, sid))
return orphans
def _find_duplicate_ids(facts):
seen = set()
dups = []
for f in facts:
fid = f.get('id')
if fid:
if fid in seen:
dups.append(fid)
seen.add(fid)
return dups
# consolidation: find groups of similar facts, synthesize a higher-level concept out of them. cool idea right?
def _cluster_facts(facts, embeddings, threshold=0.75):
n = len(facts)
adj = [[] for _ in range(n)]
for i in range(n):
ei = embeddings.get(facts[i]['id'])
if ei is None:
continue
for j in range(i + 1, n):
ej = embeddings.get(facts[j]['id'])
if ej is None:
continue
sim = _cosine_sim_vec(ei, ej)
if sim >= threshold:
adj[i].append(j)
adj[j].append(i)
visited = [False] * n
clusters = []
for i in range(n):
if not visited[i]:
stack = [i]
cluster = []
while stack:
v = stack.pop()
if not visited[v]:
visited[v] = True
cluster.append(v)
for nb in adj[v]:
if not visited[nb]:
stack.append(nb)