omp-memory 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,309 @@
1
+ """Experience layer: cross-trajectory abstraction & pattern detection.
2
+
3
+ Covers the survey's Storage->Reflection->Experience arc: capture already
4
+ stores trajectories (Wave F); reflect evaluates them into PROCEDURAL,
5
+ REFLECTIVE and RULE knowledge, pairs each stored failure with its successful
6
+ counterpart (ReasoningBank, arXiv 2509.25140), and links episodes that
7
+ describe the same recurring situation across sessions and projects.
8
+ """
9
+ import math
10
+ import re
11
+ import sqlite3
12
+
13
+ from omp_memory import db
14
+
15
+ # A topic cluster is a group of records whose TF-IDF vectors clear this
16
+ # cosine. idf is log(1 + n/df): a token shared by every document in the
17
+ # pool (df == n) keeps positive weight, because shared topic vocabulary is
18
+ # exactly what should pull records together. The threshold sits below
19
+ # web.py's record-record edge threshold on purpose: a cluster has to
20
+ # survive paraphrase, an edge only has to suggest.
21
+ _TOPIC_SIMILARITY = 0.15
22
+ # A pattern needs repeated evidence, not a single coincidence.
23
+ _MIN_GROUP = 3
24
+ _MIN_PROJECTS = 2
25
+ _MIN_REINFORCE = 2
26
+ _EXPERIENCE_SOURCE = "experience"
27
+
28
+
29
+ def _tokens(text: str) -> list:
30
+ return [w for w in re.split(r"[^a-z0-9]+", text.lower()) if len(w) > 4]
31
+
32
+
33
+ def _tfidf(docs: list) -> list:
34
+ n = len(docs)
35
+ df: dict = {}
36
+ tokenized = [_tokens(doc) for doc in docs]
37
+ for toks in tokenized:
38
+ for w in set(toks):
39
+ df[w] = df.get(w, 0) + 1
40
+ out = []
41
+ for toks in tokenized:
42
+ tf: dict = {}
43
+ for w in toks:
44
+ tf[w] = tf.get(w, 0) + 1
45
+ out.append({w: (1 + math.log(c)) * math.log(1 + n / df[w])
46
+ for w, c in tf.items()})
47
+ return out
48
+
49
+
50
+ def _cosine(a: dict, b: dict) -> float:
51
+ if not a or not b:
52
+ return 0.0
53
+ common = set(a) & set(b)
54
+ dot = sum(a[w] * b[w] for w in common)
55
+ na = math.sqrt(sum(v * v for v in a.values()))
56
+ nb = math.sqrt(sum(v * v for v in b.values()))
57
+ if na == 0 or nb == 0:
58
+ return 0.0
59
+ return dot / (na * nb)
60
+
61
+
62
+ def _top_terms(vec: dict, k: int = 6) -> str:
63
+ return ", ".join(w for w, _ in
64
+ sorted(vec.items(), key=lambda kv: -kv[1])[:k])
65
+
66
+
67
+ def _topic_clusters(conn: sqlite3.Connection) -> list:
68
+ """Greedy single-pass clustering of every record by topic.
69
+
70
+ A record joins the first cluster whose representative vector it
71
+ resembles, otherwise it opens a new cluster. Returns clusters in
72
+ discovery order, each with its representative vec and member rows.
73
+ """
74
+ rows = conn.execute(
75
+ "SELECT id, type, content, project_id, session_id, tags, source FROM records"
76
+ " ORDER BY created_at").fetchall()
77
+ if len(rows) < _MIN_GROUP:
78
+ return []
79
+ vecs = _tfidf([r["content"] for r in rows])
80
+ clusters = []
81
+ for row, vec in zip(rows, vecs):
82
+ target = None
83
+ for c in clusters:
84
+ if _cosine(vec, c["vec"]) >= _TOPIC_SIMILARITY:
85
+ target = c
86
+ break
87
+ if target is None:
88
+ target = {"vec": vec, "rows": []}
89
+ clusters.append(target)
90
+ target["rows"].append(row)
91
+ return clusters
92
+
93
+
94
+ def _reinforce_counts(conn: sqlite3.Connection) -> dict:
95
+ try:
96
+ rows = conn.execute(
97
+ "SELECT record_id, signal FROM reinforcement").fetchall()
98
+ except sqlite3.OperationalError:
99
+ return {}
100
+ counts: dict = {}
101
+ for r in rows:
102
+ if r["signal"] == "success":
103
+ counts[r["record_id"]] = counts.get(r["record_id"], 0) + 1
104
+ return counts
105
+
106
+
107
+ def _existing_pattern_event_ids(conn: sqlite3.Connection) -> set:
108
+ rows = conn.execute(
109
+ "SELECT event_id FROM records WHERE source=?", (_EXPERIENCE_SOURCE,)
110
+ ).fetchall()
111
+ return {r["event_id"] for r in rows if r["event_id"]}
112
+
113
+
114
+ def detect_patterns(conn: sqlite3.Connection) -> list:
115
+ """Scan the whole store for cross-trajectory knowledge candidates.
116
+
117
+ Returns candidate dicts (not written): one per detected pattern, each
118
+ with rtype, content, evidence, confidence, tags, member_ids and a
119
+ deterministic event_id so re-running reflect is idempotent via
120
+ upsert_record. Failure-majority clusters are flagged by pattern_flags
121
+ instead: they mark a recurring mistake, not a working pattern.
122
+ """
123
+ reinforces = _reinforce_counts(conn)
124
+ out = []
125
+ for cluster in _topic_clusters(conn):
126
+ members = cluster["rows"]
127
+ projects = {r["project_id"] for r in members if r["project_id"]}
128
+ if len(members) < _MIN_GROUP or len(projects) < _MIN_PROJECTS:
129
+ continue
130
+ failures = [r for r in members if "failure" in (r["tags"] or "")]
131
+ if len(failures) * 2 > len(members):
132
+ continue
133
+ types = {r["type"] for r in members}
134
+ top = _top_terms(cluster["vec"])
135
+ # event_id from non-experience members only: a written pattern
136
+ # joins its own cluster on the next pass, which would otherwise
137
+ # change the id and break idempotency.
138
+ ids = sorted(r["id"] for r in members
139
+ if r["source"] != _EXPERIENCE_SOURCE) or \
140
+ sorted(r["id"] for r in members)
141
+ eid = "exp:" + db.sha(",".join(ids))[:16]
142
+
143
+ # ReasoningBank contrastive induction: corrections next to facts
144
+ # on the same topic teach what actually works.
145
+ if "CORRECTION" in types and ("FACT" in types or "RULE" in types):
146
+ corr = next(r for r in members if r["type"] == "CORRECTION")
147
+ content = (f"Correction pattern: {corr['content']} "
148
+ f"applies to topic '{top}'")
149
+ out.append({"rtype": "REFLECTIVE", "content": content,
150
+ "evidence": f"{len(members)} records on '{top}' "
151
+ f"across {len(projects)} projects",
152
+ "confidence": 0.5, "source": _EXPERIENCE_SOURCE,
153
+ "tags": "pattern,experience", "event_id": eid,
154
+ "member_ids": ids})
155
+ continue
156
+
157
+ success = sum(reinforces.get(rid, 0) for rid in ids)
158
+ if success >= _MIN_REINFORCE or "RULE" in types:
159
+ content = (f"Working pattern for '{top}': "
160
+ f"{_top_terms(cluster['vec'], 8)}")
161
+ out.append({"rtype": "PROCEDURAL", "content": content,
162
+ "evidence": f"{len(members)} records on '{top}' "
163
+ f"across {len(projects)} projects, "
164
+ f"{success} reinforcement successes",
165
+ "confidence": 0.55, "source": _EXPERIENCE_SOURCE,
166
+ "tags": "pattern,experience", "event_id": eid,
167
+ "member_ids": ids})
168
+ return out
169
+
170
+
171
+ def pattern_flags(conn: sqlite3.Connection) -> list:
172
+ """Flag recurring situations: repeated failures, repeated rules.
173
+
174
+ Flags are observations for the operator, not records to write: a
175
+ recurring failure says something is still broken somewhere.
176
+ """
177
+ flags = []
178
+ for cluster in _topic_clusters(conn):
179
+ members = cluster["rows"]
180
+ projects = {r["project_id"] for r in members if r["project_id"]}
181
+ if len(members) < _MIN_GROUP or len(projects) < _MIN_PROJECTS:
182
+ continue
183
+ top = _top_terms(cluster["vec"])
184
+ failures = [r for r in members if "failure" in (r["tags"] or "")]
185
+ failure_projects = {r["project_id"] for r in failures
186
+ if r["project_id"]}
187
+ if (len(failures) >= _MIN_GROUP
188
+ and len(failure_projects) >= _MIN_PROJECTS):
189
+ flags.append({"kind": "recurring_failure", "topic": top,
190
+ "members": len(failures),
191
+ "projects": len(failure_projects)})
192
+ if "RULE" in {r["type"] for r in members}:
193
+ flags.append({"kind": "recurring_rule", "topic": top,
194
+ "members": len(members),
195
+ "projects": len(projects)})
196
+ return flags
197
+
198
+
199
+ def contrastive_pairs(conn: sqlite3.Connection) -> list:
200
+ """Pair each stored failure with the verified success on its topic.
201
+
202
+ A failure record only pairs when it carries the failure tag (captured
203
+ failures, not every record mentioning an error word). Success must be
204
+ verified: an unverified guess is not a lesson, it is a second guess.
205
+ """
206
+ failures = conn.execute(
207
+ "SELECT id, content FROM records WHERE tags LIKE '%failure%'"
208
+ " ORDER BY created_at").fetchall()
209
+ if not failures:
210
+ return []
211
+ successes = conn.execute(
212
+ "SELECT id, content, type FROM records"
213
+ " WHERE verified=1 AND type IN ('FACT','RULE')"
214
+ " ORDER BY created_at").fetchall()
215
+ if not successes:
216
+ return []
217
+ pairs = []
218
+ for f in failures:
219
+ best, best_sim = None, 0.0
220
+ for s in successes:
221
+ sim = db.similarity(f["content"], s["content"])
222
+ if sim > best_sim:
223
+ best, best_sim = s, sim
224
+ if best is not None and best_sim >= _TOPIC_SIMILARITY:
225
+ pairs.append({"failure_id": f["id"], "success_id": best["id"],
226
+ "similarity": round(best_sim, 4),
227
+ "failure": f["content"], "success": best["content"]})
228
+ return pairs
229
+
230
+
231
+ def event_links(conn: sqlite3.Connection) -> list:
232
+ """Link event episodes across sessions that describe the same situation.
233
+
234
+ Events are grouped by the event_id capture wrote (session#eN). Two
235
+ events link when their pooled contents are similar enough; the link
236
+ itself is symmetric and deduplicated by construction (each pair is
237
+ visited once from the lower index).
238
+ """
239
+ rows = conn.execute(
240
+ "SELECT event_id, content FROM records"
241
+ " WHERE event_id != '' ORDER BY created_at").fetchall()
242
+ if not rows:
243
+ return []
244
+ by_event: dict = {}
245
+ order: list = []
246
+ for r in rows:
247
+ if r["event_id"] not in by_event:
248
+ by_event[r["event_id"]] = []
249
+ order.append(r["event_id"])
250
+ by_event[r["event_id"]].append(r["content"])
251
+ if len(order) < 2:
252
+ return []
253
+ vecs = _tfidf([" ".join(by_event[e]) for e in order])
254
+ links = []
255
+ for i in range(len(order)):
256
+ for j in range(i + 1, len(order)):
257
+ sim = _cosine(vecs[i], vecs[j])
258
+ if sim >= _TOPIC_SIMILARITY:
259
+ links.append({"a": order[i], "b": order[j],
260
+ "similarity": round(sim, 4)})
261
+ return links
262
+
263
+
264
+ def reflect(conn: sqlite3.Connection, apply: bool = False) -> dict:
265
+ """Run the full experience pass: patterns, flags, pairs, links.
266
+
267
+ Returns a summary. With apply=True the candidates are written through
268
+ db.upsert_record, whose content-identity dedup plus the deterministic
269
+ event_id makes re-running reflect a no-op on an unchanged store.
270
+ Candidates whose event_id is already in the store are neither counted
271
+ nor written, so the summary describes what this pass changed.
272
+ """
273
+ candidates = detect_patterns(conn)
274
+ flags = pattern_flags(conn)
275
+ pairs = contrastive_pairs(conn)
276
+ links = event_links(conn)
277
+ have = _existing_pattern_event_ids(conn)
278
+ fresh = [c for c in candidates if c["event_id"] not in have]
279
+ written = 0
280
+ reflective = sum(1 for c in fresh if c["rtype"] == "REFLECTIVE")
281
+ if apply:
282
+ for c in fresh:
283
+ db.upsert_record(conn, c["rtype"], c["content"],
284
+ evidence=c["evidence"], verified=0,
285
+ confidence=c["confidence"], source=c["source"],
286
+ tags=c["tags"], event_id=c["event_id"],
287
+ parent_id=",".join(c["member_ids"]))
288
+ have.add(c["event_id"])
289
+ written += 1
290
+ for p in pairs:
291
+ content = (f"Lesson from failure: {p['failure']} "
292
+ f"-> worked instead: {p['success']}")
293
+ rid = db.upsert_record(conn, "REFLECTIVE", content,
294
+ evidence=f"paired records "
295
+ f"{p['failure_id']} and "
296
+ f"{p['success_id']}",
297
+ verified=0, confidence=0.5,
298
+ source=_EXPERIENCE_SOURCE,
299
+ tags="reflective,experience",
300
+ parent_id=f"{p['failure_id']},"
301
+ f"{p['success_id']}")
302
+ if rid:
303
+ written += 1
304
+ reflective += 1
305
+ return {"procedural": sum(1 for c in fresh
306
+ if c["rtype"] == "PROCEDURAL"),
307
+ "reflective": reflective,
308
+ "pairs": len(pairs), "links": len(links),
309
+ "patterns": flags, "written": written}