@geravant/sinain 1.11.0 → 1.13.0

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.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/sinain-core/package-lock.json +963 -0
  3. package/sinain-core/package.json +1 -0
  4. package/sinain-core/src/buffers/feed-buffer.ts +32 -0
  5. package/sinain-core/src/embedding/service.ts +66 -0
  6. package/sinain-core/src/escalation/escalator.ts +1 -0
  7. package/sinain-core/src/escalation/message-builder.ts +45 -118
  8. package/sinain-core/src/index.ts +19 -2
  9. package/sinain-core/src/learning/local-curation.ts +137 -7
  10. package/sinain-core/src/overlay/commands.ts +16 -3
  11. package/sinain-core/src/overlay/ws-handler.ts +4 -1
  12. package/sinain-core/src/server.ts +31 -0
  13. package/sinain-core/src/types.ts +3 -0
  14. package/sinain-memory/README.md +105 -0
  15. package/sinain-memory/__pycache__/common.cpython-312.pyc +0 -0
  16. package/sinain-memory/__pycache__/embed_client.cpython-312.pyc +0 -0
  17. package/sinain-memory/__pycache__/graph_query.cpython-312.pyc +0 -0
  18. package/sinain-memory/__pycache__/knowledge_integrator.cpython-312.pyc +0 -0
  19. package/sinain-memory/__pycache__/session_distiller.cpython-312.pyc +0 -0
  20. package/sinain-memory/__pycache__/triplestore.cpython-312.pyc +0 -0
  21. package/sinain-memory/embed_client.py +117 -0
  22. package/sinain-memory/eval/__pycache__/__init__.cpython-312.pyc +0 -0
  23. package/sinain-memory/eval/benchmarks/__init__.py +0 -0
  24. package/sinain-memory/eval/benchmarks/__pycache__/__init__.cpython-312.pyc +0 -0
  25. package/sinain-memory/eval/benchmarks/__pycache__/base_adapter.cpython-312.pyc +0 -0
  26. package/sinain-memory/eval/benchmarks/__pycache__/config.cpython-312.pyc +0 -0
  27. package/sinain-memory/eval/benchmarks/__pycache__/evaluate.cpython-312.pyc +0 -0
  28. package/sinain-memory/eval/benchmarks/__pycache__/ingest.cpython-312.pyc +0 -0
  29. package/sinain-memory/eval/benchmarks/__pycache__/longmemeval_adapter.cpython-312.pyc +0 -0
  30. package/sinain-memory/eval/benchmarks/__pycache__/meeting_adapter.cpython-312.pyc +0 -0
  31. package/sinain-memory/eval/benchmarks/__pycache__/meeting_runner.cpython-312.pyc +0 -0
  32. package/sinain-memory/eval/benchmarks/__pycache__/query.cpython-312.pyc +0 -0
  33. package/sinain-memory/eval/benchmarks/__pycache__/report.cpython-312.pyc +0 -0
  34. package/sinain-memory/eval/benchmarks/__pycache__/runner.cpython-312.pyc +0 -0
  35. package/sinain-memory/eval/benchmarks/base_adapter.py +43 -0
  36. package/sinain-memory/eval/benchmarks/config.py +23 -0
  37. package/sinain-memory/eval/benchmarks/evaluate.py +146 -0
  38. package/sinain-memory/eval/benchmarks/ingest.py +152 -0
  39. package/sinain-memory/eval/benchmarks/judges/__init__.py +0 -0
  40. package/sinain-memory/eval/benchmarks/judges/__pycache__/__init__.cpython-312.pyc +0 -0
  41. package/sinain-memory/eval/benchmarks/judges/__pycache__/qa_judge.cpython-312.pyc +0 -0
  42. package/sinain-memory/eval/benchmarks/judges/qa_judge.py +81 -0
  43. package/sinain-memory/eval/benchmarks/longmemeval_adapter.py +177 -0
  44. package/sinain-memory/eval/benchmarks/meeting_adapter.py +81 -0
  45. package/sinain-memory/eval/benchmarks/meeting_runner.py +230 -0
  46. package/sinain-memory/eval/benchmarks/query.py +193 -0
  47. package/sinain-memory/eval/benchmarks/report.py +87 -0
  48. package/sinain-memory/eval/benchmarks/run_meeting_bench.sh +318 -0
  49. package/sinain-memory/eval/benchmarks/runner.py +283 -0
  50. package/sinain-memory/graph_query.py +257 -15
  51. package/sinain-memory/knowledge_integrator.py +365 -72
  52. package/sinain-memory/koog-config.json +11 -0
  53. package/sinain-memory/memory-config.json +1 -1
  54. package/sinain-memory/session_distiller.py +43 -19
  55. package/sinain-memory/triplestore.py +60 -0
@@ -129,27 +129,269 @@ def query_top_facts(db_path: str, limit: int = 30) -> list[dict]:
129
129
  return []
130
130
 
131
131
 
132
+ def query_facts_fts(db_path: str, query: str, max_facts: int = 10) -> list[dict]:
133
+ """Full-text search on fact values via FTS5 index.
134
+
135
+ Returns facts whose value field matches the query keywords.
136
+ Falls back to LIKE search if FTS5 is not available.
137
+ """
138
+ if not Path(db_path).exists():
139
+ return []
140
+
141
+ try:
142
+ from triplestore import TripleStore
143
+ store = TripleStore(db_path)
144
+
145
+ # Try FTS5 first
146
+ try:
147
+ rows = store._conn.execute(
148
+ """SELECT DISTINCT t.entity_id
149
+ FROM triples_fts fts
150
+ JOIN triples t ON fts.rowid = t.id
151
+ WHERE triples_fts MATCH ?
152
+ AND t.attribute = 'value'
153
+ AND NOT t.retracted
154
+ LIMIT ?""",
155
+ (query, max_facts),
156
+ ).fetchall()
157
+ except Exception:
158
+ # FTS5 not available — fall back to LIKE search
159
+ keywords = [w.lower() for w in query.split() if len(w) > 2]
160
+ if not keywords:
161
+ store.close()
162
+ return []
163
+ # Match any keyword in value
164
+ conditions = " OR ".join(["LOWER(value) LIKE ?"] * len(keywords))
165
+ params = [f"%{k}%" for k in keywords] + [max_facts]
166
+ rows = store._conn.execute(
167
+ f"""SELECT DISTINCT entity_id
168
+ FROM triples
169
+ WHERE attribute = 'value'
170
+ AND NOT retracted
171
+ AND ({conditions})
172
+ LIMIT ?""",
173
+ params,
174
+ ).fetchall()
175
+
176
+ entity_ids = [r["entity_id"] for r in rows]
177
+ if not entity_ids:
178
+ store.close()
179
+ return []
180
+
181
+ # Fetch full attributes for matched entities
182
+ facts = []
183
+ for eid in entity_ids:
184
+ attrs = store.entity(eid)
185
+ fact = {"entity_id": eid, "entity": eid.split(":")[-1].rsplit("-", 1)[0] if ":" in eid else eid}
186
+ for attr, values in attrs.items():
187
+ if attr == "tag":
188
+ continue
189
+ fact[attr] = values[0] if len(values) == 1 else values
190
+ facts.append(fact)
191
+
192
+ store.close()
193
+ return facts[:max_facts]
194
+ except Exception:
195
+ return []
196
+
197
+
198
+ def query_facts_by_entity_graph(
199
+ db_path: str,
200
+ entity_name: str,
201
+ max_facts: int = 10,
202
+ ) -> list[dict]:
203
+ """Find facts about an entity via VAET backref traversal.
204
+
205
+ Uses the entity graph layer: entity:* nodes linked to fact:* nodes
206
+ via 'about' ref edges. Also follows 'mentions' ref edges for
207
+ cross-entity context.
208
+ """
209
+ if not Path(db_path).exists():
210
+ return []
211
+
212
+ try:
213
+ from triplestore import TripleStore
214
+ store = TripleStore(db_path)
215
+
216
+ entity_node_id = f"entity:{entity_name.lower().replace(' ', '-')}"
217
+ if not store.entity(entity_node_id):
218
+ store.close()
219
+ return []
220
+
221
+ # Get all facts linked to this entity via "about" ref edge
222
+ fact_refs = store.backrefs(entity_node_id, attribute="about")
223
+ # Also get facts that "mention" this entity
224
+ mention_refs = store.backrefs(entity_node_id, attribute="mentions")
225
+ all_refs = fact_refs + mention_refs
226
+
227
+ # Load fact details
228
+ seen = set()
229
+ facts = []
230
+ for fact_eid, _ in all_refs:
231
+ if fact_eid in seen or not fact_eid.startswith("fact:"):
232
+ continue
233
+ seen.add(fact_eid)
234
+ attrs = store.entity(fact_eid)
235
+ if attrs and "value" in attrs:
236
+ fact = {"entity_id": fact_eid}
237
+ for attr, values in attrs.items():
238
+ if attr == "tag":
239
+ continue
240
+ fact[attr] = values[0] if len(values) == 1 else values
241
+ facts.append(fact)
242
+
243
+ store.close()
244
+ return facts[:max_facts]
245
+ except Exception:
246
+ return []
247
+
248
+
249
+ def query_facts_hybrid(
250
+ db_path: str,
251
+ query: str,
252
+ max_facts: int = 10,
253
+ ) -> list[dict]:
254
+ """Hybrid retrieval with Reciprocal Rank Fusion (Graphiti pattern).
255
+
256
+ Runs three independent retrieval methods, fuses via RRF, then
257
+ expands top results with 1-hop graph neighbors.
258
+ """
259
+ import re
260
+ keywords = [w.lower() for w in re.findall(r"[a-zA-Z][a-zA-Z0-9-]+", query) if len(w) > 2]
261
+
262
+ # Entity graph pre-filter: find facts linked to mentioned entities via backrefs.
263
+ # Used to BOOST relevant facts in RRF, not as a separate tier (avoids dilution).
264
+ graph_fact_ids: set[str] = set()
265
+ for kw in keywords:
266
+ for f in query_facts_by_entity_graph(db_path, kw, max_facts=50):
267
+ eid = f.get("entity_id", "")
268
+ if eid:
269
+ graph_fact_ids.add(eid)
270
+
271
+ # Run three retrieval methods independently
272
+ candidate_limit = max_facts * 3
273
+ fts_results = query_facts_fts(db_path, query, max_facts=candidate_limit)
274
+ tag_results = query_facts_by_entities(db_path, keywords, max_facts=candidate_limit) if keywords else []
275
+ top_results = query_top_facts(db_path, limit=candidate_limit)
276
+
277
+ # Build ranked lists by entity_id
278
+ def _ranked_ids(facts: list[dict]) -> list[str]:
279
+ seen = set()
280
+ out = []
281
+ for f in facts:
282
+ eid = f.get("entity_id", "")
283
+ if eid and eid not in seen:
284
+ seen.add(eid)
285
+ out.append(eid)
286
+ return out
287
+
288
+ fts_ranked = _ranked_ids(fts_results)
289
+ tag_ranked = _ranked_ids(tag_results)
290
+ top_ranked = _ranked_ids(top_results)
291
+
292
+ # Reciprocal Rank Fusion: RRF(d) = Σ 1/(k + rank_i(d))
293
+ K = 60 # standard RRF constant
294
+ rrf_scores: dict[str, float] = {}
295
+ for ranked_list in [fts_ranked, tag_ranked, top_ranked]:
296
+ for rank, eid in enumerate(ranked_list):
297
+ rrf_scores[eid] = rrf_scores.get(eid, 0.0) + 1.0 / (K + rank)
298
+
299
+ # Graph boost: facts linked to mentioned entities via backrefs get priority
300
+ if graph_fact_ids:
301
+ for eid in rrf_scores:
302
+ if eid in graph_fact_ids:
303
+ rrf_scores[eid] += 0.02 # significant boost — graph-linked facts rank higher
304
+
305
+ # Apply confidence decay as secondary signal (fresh facts rank above stale ones)
306
+ from triplestore import decayed_confidence
307
+ for facts_list in [fts_results, tag_results, top_results]:
308
+ for f in facts_list:
309
+ eid = f.get("entity_id", "")
310
+ if eid in rrf_scores:
311
+ conf = 0.5
312
+ created = ""
313
+ try:
314
+ conf = float(f.get("confidence", 0.5))
315
+ created = str(f.get("first_seen", ""))
316
+ except (ValueError, TypeError):
317
+ pass
318
+ if created:
319
+ effective = decayed_confidence(conf, created)
320
+ rrf_scores[eid] += effective * 0.01 # small boost, preserves RRF rank
321
+
322
+ # Sort by RRF score descending
323
+ sorted_ids = sorted(rrf_scores, key=rrf_scores.get, reverse=True)
324
+
325
+ # Build fact lookup from all candidates
326
+ fact_map: dict[str, dict] = {}
327
+ for facts in [fts_results, tag_results, top_results]:
328
+ for f in facts:
329
+ eid = f.get("entity_id", "")
330
+ if eid and eid not in fact_map:
331
+ fact_map[eid] = f
332
+
333
+ results = [fact_map[eid] for eid in sorted_ids[:max_facts] if eid in fact_map]
334
+
335
+ # Expand top results with 1-hop graph neighbors
336
+ if results and len(results) < max_facts:
337
+ seen_ids = {f.get("entity_id", "") for f in results}
338
+ try:
339
+ from triplestore import TripleStore
340
+ store = TripleStore(db_path)
341
+ for fact in list(results):
342
+ eid = fact.get("entity_id", "")
343
+ if not eid:
344
+ continue
345
+ neighbors = store.neighbors(eid, depth=1)
346
+ for nid, nattrs in neighbors.items():
347
+ if nid not in seen_ids and len(results) < max_facts:
348
+ seen_ids.add(nid)
349
+ nfact = {"entity_id": nid, "entity": nid.split(":")[-1].rsplit("-", 1)[0] if ":" in nid else nid}
350
+ for attr, values in nattrs.items():
351
+ if attr != "tag":
352
+ nfact[attr] = values[0] if len(values) == 1 else values
353
+ results.append(nfact)
354
+ store.close()
355
+ except Exception:
356
+ pass
357
+
358
+ return results[:max_facts]
359
+
360
+
132
361
  def format_facts_text(facts: list[dict], max_chars: int = 500) -> str:
133
- """Format facts as human-readable text for escalation message injection."""
362
+ """Format facts grouped by entity for better cross-fact reasoning.
363
+
364
+ Groups related facts under entity headers so the QA model sees
365
+ connected context (e.g., all Citibank facts together).
366
+ """
134
367
  if not facts:
135
368
  return ""
136
369
 
137
- lines = []
138
- total = 0
370
+ # Group by entity name (strip fact: prefix and hash suffix)
371
+ from collections import OrderedDict
372
+ groups: OrderedDict[str, list[dict]] = OrderedDict()
139
373
  for f in facts:
140
- value = f.get("value", "")
141
- conf = f.get("confidence", "?")
142
- count = f.get("reinforce_count", "1")
143
- domain = f.get("domain", "")
144
-
145
- line = f"- {value} (confidence: {conf}, confirmed {count}x)"
146
- if domain:
147
- line = f"- [{domain}] {value} (confidence: {conf}, confirmed {count}x)"
374
+ entity = f.get("entity", "")
375
+ if isinstance(entity, list):
376
+ entity = entity[0] if entity else ""
377
+ if not entity:
378
+ eid = str(f.get("entity_id", ""))
379
+ entity = eid.split(":")[-1].rsplit("-", 1)[0] if ":" in eid else eid
380
+ groups.setdefault(str(entity), []).append(f)
148
381
 
149
- if total + len(line) > max_chars:
150
- break
151
- lines.append(line)
152
- total += len(line)
382
+ lines = []
383
+ total = 0
384
+ for entity, group_facts in groups.items():
385
+ for f in group_facts:
386
+ value = f.get("value", "")
387
+ conf = f.get("confidence", "?")
388
+ count = f.get("reinforce_count", "1")
389
+
390
+ line = f"- [{entity}] {value} (conf: {conf}, {count}x)"
391
+ if total + len(line) > max_chars:
392
+ return "\n".join(lines)
393
+ lines.append(line)
394
+ total += len(line)
153
395
 
154
396
  return "\n".join(lines)
155
397