ltcai 9.9.3 → 9.9.5

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 (89) hide show
  1. package/README.md +39 -38
  2. package/docs/CHANGELOG.md +100 -0
  3. package/docs/COMMUNITY_AND_PLUGINS.md +1 -1
  4. package/docs/DEVELOPMENT.md +1 -1
  5. package/docs/ONBOARDING.md +1 -1
  6. package/docs/OPERATIONS.md +1 -1
  7. package/docs/SURFACE_PARITY.md +53 -0
  8. package/docs/TRUST_MODEL.md +1 -1
  9. package/docs/WHY_LATTICE.md +1 -1
  10. package/docs/kg-schema.md +1 -1
  11. package/lattice_brain/__init__.py +1 -1
  12. package/lattice_brain/graph/_kg_common.py +335 -0
  13. package/lattice_brain/graph/discovery_index.py +8 -1
  14. package/lattice_brain/graph/ingest.py +43 -9
  15. package/lattice_brain/graph/projection.py +221 -37
  16. package/lattice_brain/graph/rerank.py +160 -0
  17. package/lattice_brain/graph/retrieval.py +90 -455
  18. package/lattice_brain/graph/retrieval_policy.py +174 -0
  19. package/lattice_brain/graph/retrieval_reads.py +459 -0
  20. package/lattice_brain/graph/retrieval_vector.py +122 -2
  21. package/lattice_brain/graph/store.py +2 -0
  22. package/lattice_brain/portability.py +41 -12
  23. package/lattice_brain/quality.py +26 -6
  24. package/lattice_brain/runtime/multi_agent.py +1 -1
  25. package/latticeai/__init__.py +1 -1
  26. package/latticeai/api/chat.py +6 -0
  27. package/latticeai/api/chat_agent_http.py +262 -52
  28. package/latticeai/api/chat_contracts.py +1 -1
  29. package/latticeai/api/chat_intents.py +37 -18
  30. package/latticeai/api/chat_stream.py +76 -2
  31. package/latticeai/api/knowledge_graph.py +35 -1
  32. package/latticeai/core/agent.py +420 -27
  33. package/latticeai/core/enterprise.py +5 -0
  34. package/latticeai/core/file_generation.py +130 -5
  35. package/latticeai/core/legacy_compatibility.py +1 -1
  36. package/latticeai/core/marketplace.py +1 -1
  37. package/latticeai/core/run_store.py +245 -0
  38. package/latticeai/core/workspace_os.py +1 -1
  39. package/latticeai/integrations/telegram_bot.py +82 -23
  40. package/latticeai/models/router.py +25 -12
  41. package/latticeai/services/architecture_readiness.py +1 -1
  42. package/latticeai/services/command_center.py +90 -1
  43. package/latticeai/services/folder_watch.py +5 -0
  44. package/latticeai/services/funnel_metrics.py +9 -1
  45. package/latticeai/services/product_readiness.py +1 -1
  46. package/latticeai/services/search_service.py +43 -13
  47. package/latticeai/services/tool_dispatch.py +56 -0
  48. package/package.json +2 -1
  49. package/scripts/bench_agent_smoke.py +410 -0
  50. package/scripts/check_current_release_docs.mjs +1 -1
  51. package/scripts/funnel_soft_gate.py +192 -0
  52. package/scripts/run_sidecar_e2e.mjs +159 -0
  53. package/src-tauri/Cargo.lock +1 -1
  54. package/src-tauri/Cargo.toml +1 -1
  55. package/src-tauri/tauri.conf.json +1 -1
  56. package/static/app/asset-manifest.json +29 -28
  57. package/static/app/assets/Act-DmxfbqBp.js +1 -0
  58. package/static/app/assets/{Brain-DEY9jLVt.js → Brain-DK_zKCda.js} +2 -2
  59. package/static/app/assets/BrainHome-CCE_0hni.js +2 -0
  60. package/static/app/assets/BrainSignals-r_J68_zh.js +1 -0
  61. package/static/app/assets/{Capture-CVZ09QXi.js → Capture-CvxwzpJZ.js} +1 -1
  62. package/static/app/assets/{CommandPalette-DepwOQFv.js → CommandPalette-CVLiFIQC.js} +1 -1
  63. package/static/app/assets/{Library-Bp0n-HlW.js → Library-4As9VUvy.js} +1 -1
  64. package/static/app/assets/{LivingBrain-DxP4efJF.js → LivingBrain-BVWk58MW.js} +1 -1
  65. package/static/app/assets/{ProductFlow-DRbm7NEq.js → ProductFlow-B-Tz0Um4.js} +1 -1
  66. package/static/app/assets/{ReviewCard-C4HAO7A3.js → ReviewCard-Va3fPQuj.js} +1 -1
  67. package/static/app/assets/{System-ByQcmJW-.js → System-DSR2zKWd.js} +1 -1
  68. package/static/app/assets/{bot-BNDyZLR7.js → bot-VmP0kkeA.js} +1 -1
  69. package/static/app/assets/circle-pause-T9POo4qy.js +1 -0
  70. package/static/app/assets/{circle-play-BkhdcHgd.js → circle-play-Bz5iTD0p.js} +1 -1
  71. package/static/app/assets/{cpu-C6jjYm6i.js → cpu-CJhjRtNq.js} +1 -1
  72. package/static/app/assets/{folder-open-DjGIvDBQ.js → folder-open-B2K_22VI.js} +1 -1
  73. package/static/app/assets/{hard-drive-BlSbwSaT.js → hard-drive-CjJtYqHf.js} +1 -1
  74. package/static/app/assets/{index-Bge3DXW7.css → index-7FAfYm4v.css} +1 -1
  75. package/static/app/assets/{index-CHu7cgj3.js → index-CEu0Wqjl.js} +3 -3
  76. package/static/app/assets/{input-DVDI0YR3.js → input-CSi6OBJ9.js} +1 -1
  77. package/static/app/assets/{navigation-BddhEWA0.js → navigation-BPQqEQwr.js} +1 -1
  78. package/static/app/assets/{network-pYQt5oBu.js → network-Ck1nqc-v.js} +1 -1
  79. package/static/app/assets/{primitives-D7gCdEvS.js → primitives-B2f9N7Dh.js} +1 -1
  80. package/static/app/assets/{shield-alert-K9RKGQeg.js → shield-alert-yA_Y8lOB.js} +1 -1
  81. package/static/app/assets/{textarea-sqQmoBKL.js → textarea-C4wM0D-Z.js} +1 -1
  82. package/static/app/assets/{useFocusTrap-7EV9dFP2.js → useFocusTrap-CsnIhsDJ.js} +1 -1
  83. package/static/app/assets/utils-BqoznzGP.js +7 -0
  84. package/static/app/index.html +4 -4
  85. package/static/sw.js +1 -1
  86. package/static/app/assets/Act-DmdruVKV.js +0 -1
  87. package/static/app/assets/BrainHome-CeNaxjP1.js +0 -2
  88. package/static/app/assets/BrainSignals-CStjIqYi.js +0 -1
  89. package/static/app/assets/utils-uQYKXNeq.js +0 -7
@@ -4,6 +4,14 @@ from __future__ import annotations
4
4
 
5
5
  from ._kg_common import * # noqa: F403,F401
6
6
 
7
+ # --- Compat seam (v9.9.5 decomposition) -------------------------------------
8
+ # The non-search read surface (list_documents / workspaces_of /
9
+ # filter_scoped_nodes / neighbors / get_node / relationship_search /
10
+ # traverse / stats) moved byte-identically to .retrieval_reads as
11
+ # KnowledgeGraphReadsMixin. Re-exported here so any legacy
12
+ # ``from lattice_brain.graph.retrieval import ...`` site keeps resolving.
13
+ from .retrieval_reads import KnowledgeGraphReadsMixin # noqa: F401
14
+
7
15
 
8
16
  def context_quality_signal(
9
17
  mode: str,
@@ -68,119 +76,6 @@ class KnowledgeGraphRetrievalMixin:
68
76
  "Agent", # 에이전트
69
77
  )
70
78
 
71
- def list_documents(self, limit: int = 200) -> Dict[str, Any]:
72
- """List ingested ``Document`` nodes with their ingest + index state.
73
-
74
- Powers the Files view: every accepted upload and every indexed local
75
- document becomes a ``Document`` node. A document is reported ``indexed``
76
- once its retrieval chunks exist (searchable in Chat / Hybrid Search).
77
- """
78
- limit = max(1, min(int(limit or 200), 1000))
79
- nt, _ = self._read_tables()
80
- documents: List[Dict[str, Any]] = []
81
- with self._connect() as conn:
82
- rows = conn.execute(
83
- f"SELECT id, title, summary, metadata_json, created_at, updated_at "
84
- f"FROM {nt} WHERE type='Document' ORDER BY updated_at DESC, id ASC LIMIT ?",
85
- (limit,),
86
- ).fetchall()
87
- for row in rows:
88
- meta = _safe_loads(row["metadata_json"]) or {}
89
- extracted = meta.get("extracted") or {}
90
- node_id = row["id"]
91
- chunk_count = conn.execute(
92
- "SELECT COUNT(*) AS c FROM chunks WHERE source_node=?",
93
- (node_id,),
94
- ).fetchone()["c"]
95
- if not chunk_count:
96
- # Legacy projections represented chunks as graph nodes and
97
- # linked them only through metadata_json. Keep read
98
- # compatibility without making the fragile LIKE path the
99
- # primary query.
100
- chunk_count = conn.execute(
101
- f"SELECT COUNT(*) AS c FROM {nt} WHERE type='Chunk' AND metadata_json LIKE ?",
102
- (f"%{node_id}%",),
103
- ).fetchone()["c"]
104
- documents.append(
105
- {
106
- "id": node_id,
107
- "filename": meta.get("filename") or row["title"],
108
- "ext": meta.get("ext"),
109
- "mime_type": meta.get("mime_type"),
110
- "bytes": meta.get("bytes"),
111
- "sha256": meta.get("sha256"),
112
- "uploader": meta.get("uploader"),
113
- "chars": extracted.get("chars"),
114
- "chunks": int(chunk_count or 0),
115
- "indexed": int(chunk_count or 0) > 0,
116
- "ingest_state": "indexed"
117
- if int(chunk_count or 0) > 0
118
- else "ingested",
119
- "created_at": row["created_at"],
120
- "updated_at": row["updated_at"],
121
- }
122
- )
123
- return {
124
- "documents": documents,
125
- "total": len(documents),
126
- "generated_at": datetime.now().isoformat(timespec="seconds"),
127
- }
128
-
129
- def workspaces_of(self, node_ids) -> Dict[str, Optional[str]]:
130
- """Map known node ids to their workspace scope.
131
-
132
- ``None`` is returned only for a row that is explicitly present in the
133
- authoritative v2 projection with a NULL workspace. Missing ids remain
134
- missing, and projection/query failures propagate so callers can fail
135
- closed instead of mistaking every candidate for legacy-global data.
136
- """
137
- ids = [str(i) for i in node_ids if i]
138
- if not ids:
139
- return {}
140
- placeholders = ",".join("?" for _ in ids)
141
- with self._connect() as conn:
142
- return {
143
- row["id"]: row["workspace_id"]
144
- for row in conn.execute(
145
- f"SELECT id, workspace_id FROM nodes_v2 WHERE id IN ({placeholders})",
146
- ids,
147
- ).fetchall()
148
- }
149
-
150
- def filter_scoped_nodes(
151
- self,
152
- items,
153
- allowed_workspaces,
154
- *,
155
- id_key: str = "id",
156
- include_legacy_global: bool = False,
157
- ):
158
- """Drop items scoped to a workspace the caller is not a member of.
159
-
160
- ``allowed_workspaces=None`` means no scoping (single-user / no-auth
161
- mode). In scoped/multi-user mode, unknown ids are private and
162
- legacy-global rows require the explicit ``include_legacy_global=True``
163
- compatibility opt-in.
164
- """
165
- candidates = list(items)
166
- if allowed_workspaces is None:
167
- return candidates
168
- allowed = {str(workspace_id) for workspace_id in allowed_workspaces if workspace_id}
169
- scopes = self.workspaces_of([item.get(id_key) for item in candidates])
170
- visible = []
171
- for item in candidates:
172
- node_id = str(item.get(id_key) or "")
173
- if not node_id or node_id not in scopes:
174
- # Unknown/unprojected rows are never treated as public.
175
- continue
176
- workspace_id = scopes[node_id]
177
- if workspace_id is None:
178
- if include_legacy_global:
179
- visible.append(item)
180
- elif str(workspace_id) in allowed:
181
- visible.append(item)
182
- return visible
183
-
184
79
  def graph(
185
80
  self,
186
81
  limit: int = 300,
@@ -478,10 +373,16 @@ class KnowledgeGraphRetrievalMixin:
478
373
  richer ``allowed_workspaces`` set wins when both are provided.
479
374
 
480
375
  ``alpha=None`` (the default) resolves the vector share from the
481
- query-class fusion table (:mod:`lattice_brain.graph.fusion`):
482
- fact 0.6 (the historical default) / code 0.35 / person 0.45 /
483
- recency 0.5, config-overridable via ``LATTICEAI_FUSION_WEIGHTS``.
484
- Passing an explicit ``alpha`` pins it exactly as before.
376
+ single retrieval policy (:mod:`lattice_brain.graph.retrieval_policy`,
377
+ which wraps the query-class fusion table): fact 0.6 (the historical
378
+ default) / code 0.35 / person 0.45 / recency 0.5, config-overridable
379
+ via ``LATTICEAI_FUSION_WEIGHTS``. The policy also supplies a
380
+ deterministic rule-based query rewrite (echoed additively under
381
+ ``"policy"``; the response ``"query"`` stays the original) and, for
382
+ the ``recency`` class only, an age-decay half-life that dampens each
383
+ fused score into the ``[0.5, 1.0]`` band (``scores.age_decay``).
384
+ Passing an explicit ``alpha`` pins it exactly as before and disables
385
+ rewrite + decay.
485
386
  """
486
387
  query = str(query or "").strip()
487
388
  try:
@@ -490,14 +391,24 @@ class KnowledgeGraphRetrievalMixin:
490
391
  top_k = 20
491
392
  top_k = max(1, min(top_k, 100))
492
393
  query_class: Optional[str] = None
394
+ search_query = query
395
+ rewrite_rules: List[str] = []
396
+ recency_half_life_days: Optional[float] = None
493
397
  if alpha is None:
494
398
  try:
495
- from .fusion import fusion_profile
496
-
497
- profile = fusion_profile(query)
498
- query_class = profile["query_class"]
499
- alpha = float(profile["alpha"])
500
- except Exception: # noqa: BLE001 — fusion table must never break search
399
+ from .retrieval_policy import resolve_policy
400
+
401
+ policy = resolve_policy(query)
402
+ query_class = policy["query_class"]
403
+ alpha = float(policy["alpha"])
404
+ rewrite_rules = list(policy.get("rewrite_rules") or [])
405
+ rewritten = str(policy.get("search_query") or "")
406
+ if rewritten and rewritten != query:
407
+ search_query = rewritten
408
+ half_life = policy.get("recency_half_life_days")
409
+ if half_life is not None:
410
+ recency_half_life_days = float(half_life)
411
+ except Exception: # noqa: BLE001 — policy resolution must never break search
501
412
  alpha = 0.6
502
413
  try:
503
414
  alpha = float(alpha)
@@ -516,6 +427,7 @@ class KnowledgeGraphRetrievalMixin:
516
427
  "top_k": top_k,
517
428
  "sources": {"lexical": 0, "vector": 0},
518
429
  "matches": [],
430
+ "policy": {"search_query": search_query, "rewrite_rules": rewrite_rules},
519
431
  "detail": None,
520
432
  }
521
433
 
@@ -523,7 +435,7 @@ class KnowledgeGraphRetrievalMixin:
523
435
  vec_fetch = max(1, min(int(vector_limit or max(top_k * 2, 20)), 100))
524
436
 
525
437
  lexical_matches = self.search(
526
- query,
438
+ search_query,
527
439
  lex_fetch,
528
440
  allowed_workspaces=allowed_workspaces,
529
441
  include_legacy_global=include_legacy_global,
@@ -539,7 +451,7 @@ class KnowledgeGraphRetrievalMixin:
539
451
  else:
540
452
  try:
541
453
  vector_matches = list(
542
- (vector_fn(query, limit=vec_fetch, min_score=min_vector_score) or {}).get(
454
+ (vector_fn(search_query, limit=vec_fetch, min_score=min_vector_score) or {}).get(
543
455
  "matches", []
544
456
  )
545
457
  )
@@ -547,6 +459,17 @@ class KnowledgeGraphRetrievalMixin:
547
459
  mode = "lexical_only"
548
460
  detail = f"vector index unavailable: {exc}"
549
461
  vector_matches = []
462
+ # An embedder swap makes the vector channel silently return zero rows
463
+ # (vector_search filters on the CURRENT model/dim). Surface the honest
464
+ # cause additively without changing the mode string.
465
+ vector_degraded: Optional[str] = None
466
+ if mode == "hybrid" and not vector_matches:
467
+ try:
468
+ fingerprint_fn = getattr(self, "embedder_fingerprint_status", None)
469
+ if callable(fingerprint_fn) and fingerprint_fn().get("stale_embedder"):
470
+ vector_degraded = "stale_embedder"
471
+ except Exception: # noqa: BLE001 — fingerprint status must never break search
472
+ vector_degraded = None
550
473
  if vector_matches and allowed_workspaces is not None:
551
474
  vector_matches = self.filter_scoped_nodes(
552
475
  vector_matches,
@@ -633,11 +556,46 @@ class KnowledgeGraphRetrievalMixin:
633
556
  entry["fusion"] = "lexical"
634
557
  matches.append(entry)
635
558
 
559
+ # Recency-class age decay (retrieval_policy): dampen each fused score
560
+ # into the [0.5, 1.0] band so old-but-relevant items sink without ever
561
+ # being zeroed. Other classes skip this block byte-identically.
562
+ if recency_half_life_days is not None:
563
+ decay_now = datetime.now()
564
+ for match in matches:
565
+ stamp = match.get("updated_at")
566
+ if _parse_iso(stamp):
567
+ multiplier = 0.5 + 0.5 * _recency_score(
568
+ stamp, now=decay_now, half_life_days=recency_half_life_days
569
+ )
570
+ else:
571
+ # Unknown age is not evidence of staleness — never dampen.
572
+ multiplier = 1.0
573
+ match["scores"]["age_decay"] = round(multiplier, 6)
574
+ match["score"] = round(float(match["score"]) * multiplier, 6)
575
+
636
576
  matches.sort(key=lambda item: (-item["score"], item["node_id"]))
637
- matches = matches[:top_k]
577
+ # Optional cross-encoder rerank (v9.9.5). Off by default; when the
578
+ # env kill-switch is set and the model loads, pair scores reorder the
579
+ # fused list. Failures degrade to identity and never break search.
580
+ rerank_meta: Dict[str, Any]
581
+ try:
582
+ from .rerank import rerank_matches
583
+
584
+ # Rerank a slightly wider window, then cut to top_k.
585
+ window = matches[: max(top_k * 2, top_k)]
586
+ reranked = rerank_matches(search_query, window, top_k=top_k)
587
+ matches = list(reranked.get("matches") or matches[:top_k])
588
+ rerank_meta = {
589
+ "mode": reranked.get("mode") or "identity",
590
+ "model": reranked.get("model"),
591
+ "detail": reranked.get("detail"),
592
+ }
593
+ except Exception as exc: # noqa: BLE001 — rerank must never break search
594
+ matches = matches[:top_k]
595
+ rerank_meta = {"mode": "identity", "model": None, "detail": str(exc)}
638
596
  for rank, match in enumerate(matches, start=1):
639
597
  match["rank"] = rank
640
- return {
598
+ result = {
641
599
  "query": query,
642
600
  "mode": mode,
643
601
  "alpha": alpha,
@@ -645,8 +603,13 @@ class KnowledgeGraphRetrievalMixin:
645
603
  "top_k": top_k,
646
604
  "sources": {"lexical": len(lexical_matches), "vector": len(vector_matches)},
647
605
  "matches": matches,
606
+ "policy": {"search_query": search_query, "rewrite_rules": rewrite_rules},
607
+ "rerank": rerank_meta,
648
608
  "detail": detail,
649
609
  }
610
+ if vector_degraded is not None:
611
+ result["vector_degraded"] = vector_degraded
612
+ return result
650
613
 
651
614
  def context_for_query(
652
615
  self,
@@ -798,293 +761,6 @@ class KnowledgeGraphRetrievalMixin:
798
761
  with_meta=True,
799
762
  )
800
763
 
801
- def neighbors(
802
- self,
803
- node_id: str,
804
- *,
805
- allowed_workspaces=None,
806
- include_legacy_global: bool = False,
807
- ) -> Dict[str, Any]:
808
- """Return direct neighbors (1-hop) of a node."""
809
- if allowed_workspaces is not None and not self.filter_scoped_nodes(
810
- [{"id": node_id}],
811
- allowed_workspaces,
812
- include_legacy_global=include_legacy_global,
813
- ):
814
- raise ValueError(f"graph node not found: {node_id}")
815
- nt, et = self._read_tables()
816
- with self._connect() as conn:
817
- edge_rows = conn.execute(
818
- f"SELECT from_node, to_node, type, weight FROM {et} WHERE from_node=? OR to_node=? ORDER BY id ASC",
819
- (node_id, node_id),
820
- ).fetchall()
821
- neighbor_ids: set = set()
822
- edges = []
823
- for row in edge_rows:
824
- neighbor_ids.add(row["from_node"])
825
- neighbor_ids.add(row["to_node"])
826
- edges.append(
827
- {
828
- "from": row["from_node"],
829
- "to": row["to_node"],
830
- "type": row["type"],
831
- "weight": row["weight"],
832
- }
833
- )
834
- neighbor_ids.discard(node_id)
835
- nodes = []
836
- if neighbor_ids:
837
- placeholders = ",".join("?" * len(neighbor_ids))
838
- nodes = [
839
- {
840
- "id": row["id"],
841
- "type": row["type"],
842
- "title": row["title"],
843
- "summary": row["summary"],
844
- "metadata": _safe_loads(row["metadata_json"]),
845
- }
846
- for row in conn.execute(
847
- f"SELECT id, type, title, summary, metadata_json FROM {nt} WHERE id IN ({placeholders}) ORDER BY id ASC",
848
- list(neighbor_ids),
849
- )
850
- ]
851
- if allowed_workspaces is not None:
852
- nodes = self.filter_scoped_nodes(
853
- nodes,
854
- allowed_workspaces,
855
- include_legacy_global=include_legacy_global,
856
- )
857
- kept = {node.get("id") for node in nodes}
858
- edges = [
859
- edge for edge in edges
860
- if (edge.get("from") == node_id or edge.get("from") in kept)
861
- and (edge.get("to") == node_id or edge.get("to") in kept)
862
- ]
863
- return {"node_id": node_id, "neighbors": nodes, "edges": edges}
864
-
865
- def get_node(
866
- self,
867
- node_id: str,
868
- *,
869
- allowed_workspaces=None,
870
- include_legacy_global: bool = False,
871
- ) -> Dict[str, Any]:
872
- node_id = str(node_id or "").strip()
873
- if not node_id:
874
- raise ValueError("node_id required")
875
- nt, et = self._read_tables()
876
- with self._connect() as conn:
877
- row = conn.execute(
878
- f"""
879
- SELECT id, type, title, summary, metadata_json, updated_at
880
- FROM {nt}
881
- WHERE id=?
882
- """,
883
- (node_id,),
884
- ).fetchone()
885
- if not row:
886
- raise ValueError(f"graph node not found: {node_id}")
887
- degree = conn.execute(
888
- f"SELECT COUNT(*) AS c FROM {et} WHERE from_node=? OR to_node=?",
889
- (node_id, node_id),
890
- ).fetchone()["c"]
891
- node = {
892
- "id": row["id"],
893
- "type": row["type"],
894
- "title": row["title"],
895
- "summary": row["summary"],
896
- "metadata": _safe_loads(row["metadata_json"]),
897
- "updated_at": row["updated_at"],
898
- "degree": degree,
899
- }
900
- if allowed_workspaces is not None and not self.filter_scoped_nodes(
901
- [node],
902
- allowed_workspaces,
903
- include_legacy_global=include_legacy_global,
904
- ):
905
- raise ValueError(f"graph node not found: {node_id}")
906
- return node
907
-
908
- def relationship_search(
909
- self,
910
- *,
911
- query: str = "",
912
- node_id: str = "",
913
- relationship_type: str = "",
914
- limit: int = 30,
915
- allowed_workspaces=None,
916
- include_legacy_global: bool = False,
917
- ) -> Dict[str, Any]:
918
- query = str(query or "").strip()
919
- node_id = str(node_id or "").strip()
920
- relationship_type = str(relationship_type or "").strip()
921
- limit = max(1, min(int(limit or 30), 200))
922
- nt, et = self._read_tables()
923
- where = []
924
- params: List[Any] = []
925
- if node_id:
926
- where.append("(e.from_node=? OR e.to_node=?)")
927
- params.extend([node_id, node_id])
928
- if relationship_type:
929
- where.append("e.type LIKE ?")
930
- params.append(f"%{relationship_type}%")
931
- if query:
932
- where.append(
933
- "(e.type LIKE ? OR e.metadata_json LIKE ? OR src.title LIKE ? OR dst.title LIKE ? OR src.summary LIKE ? OR dst.summary LIKE ?)"
934
- )
935
- params.extend([f"%{query}%"] * 6)
936
- where_sql = "WHERE " + " AND ".join(where) if where else ""
937
- with self._connect() as conn:
938
- rows = conn.execute(
939
- f"""
940
- SELECT
941
- e.id, e.from_node, e.to_node, e.type, e.weight, e.metadata_json, e.created_at,
942
- src.type AS source_type, src.title AS source_title, src.summary AS source_summary,
943
- src.metadata_json AS source_metadata,
944
- dst.type AS target_type, dst.title AS target_title, dst.summary AS target_summary,
945
- dst.metadata_json AS target_metadata
946
- FROM {et} e
947
- JOIN {nt} src ON src.id=e.from_node
948
- JOIN {nt} dst ON dst.id=e.to_node
949
- {where_sql}
950
- ORDER BY e.weight DESC, e.created_at DESC, e.id ASC
951
- LIMIT ?
952
- """,
953
- (*params, limit),
954
- ).fetchall()
955
- relationships = [
956
- {
957
- "id": row["id"],
958
- "type": row["type"],
959
- "weight": row["weight"],
960
- "metadata": _safe_loads(row["metadata_json"]),
961
- "created_at": row["created_at"],
962
- "source": {
963
- "id": row["from_node"],
964
- "type": row["source_type"],
965
- "title": row["source_title"],
966
- "summary": row["source_summary"],
967
- "metadata": _safe_loads(row["source_metadata"]),
968
- },
969
- "target": {
970
- "id": row["to_node"],
971
- "type": row["target_type"],
972
- "title": row["target_title"],
973
- "summary": row["target_summary"],
974
- "metadata": _safe_loads(row["target_metadata"]),
975
- },
976
- }
977
- for row in rows
978
- ]
979
- if allowed_workspaces is not None:
980
- kept = []
981
- for rel in relationships:
982
- endpoints = [
983
- {"id": (rel.get("source") or {}).get("id")},
984
- {"id": (rel.get("target") or {}).get("id")},
985
- ]
986
- if len(
987
- self.filter_scoped_nodes(
988
- endpoints,
989
- allowed_workspaces,
990
- include_legacy_global=include_legacy_global,
991
- )
992
- ) == 2:
993
- kept.append(rel)
994
- relationships = kept
995
- return {
996
- "query": query,
997
- "node_id": node_id,
998
- "relationship_type": relationship_type,
999
- "relationships": relationships,
1000
- }
1001
-
1002
- def traverse(
1003
- self,
1004
- node_id: str,
1005
- *,
1006
- depth: int = 1,
1007
- limit: int = 100,
1008
- allowed_workspaces=None,
1009
- include_legacy_global: bool = False,
1010
- ) -> Dict[str, Any]:
1011
- node_id = str(node_id or "").strip()
1012
- if not node_id:
1013
- raise ValueError("node_id required")
1014
- if allowed_workspaces is not None and not self.filter_scoped_nodes(
1015
- [{"id": node_id}],
1016
- allowed_workspaces,
1017
- include_legacy_global=include_legacy_global,
1018
- ):
1019
- raise ValueError(f"graph node not found: {node_id}")
1020
- depth = max(0, min(int(depth or 1), 4))
1021
- limit = max(1, min(int(limit or 100), 500))
1022
- nt, et = self._read_tables()
1023
- visited = {node_id}
1024
- frontier = {node_id}
1025
- edges_by_id: Dict[str, Dict[str, Any]] = {}
1026
- with self._connect() as conn:
1027
- for _ in range(depth):
1028
- if not frontier or len(visited) >= limit:
1029
- break
1030
- placeholders = ",".join("?" * len(frontier))
1031
- rows = conn.execute(
1032
- f"""
1033
- SELECT id, from_node, to_node, type, weight, metadata_json
1034
- FROM {et}
1035
- WHERE from_node IN ({placeholders}) OR to_node IN ({placeholders})
1036
- ORDER BY weight DESC, id ASC
1037
- LIMIT ?
1038
- """,
1039
- (*frontier, *frontier, limit * 3),
1040
- ).fetchall()
1041
- next_frontier = set()
1042
- for row in rows:
1043
- edges_by_id[row["id"]] = {
1044
- "id": row["id"],
1045
- "from": row["from_node"],
1046
- "to": row["to_node"],
1047
- "type": row["type"],
1048
- "weight": row["weight"],
1049
- "metadata": _safe_loads(row["metadata_json"]),
1050
- }
1051
- for candidate in (row["from_node"], row["to_node"]):
1052
- if candidate not in visited and len(visited) < limit:
1053
- visited.add(candidate)
1054
- next_frontier.add(candidate)
1055
- frontier = next_frontier
1056
- placeholders = ",".join("?" * len(visited))
1057
- node_rows = conn.execute(
1058
- f"""
1059
- SELECT id, type, title, summary, metadata_json, updated_at
1060
- FROM {nt}
1061
- WHERE id IN ({placeholders})
1062
- ORDER BY updated_at DESC, id ASC
1063
- """,
1064
- list(visited),
1065
- ).fetchall()
1066
- nodes = [
1067
- {
1068
- "id": row["id"],
1069
- "type": row["type"],
1070
- "title": row["title"],
1071
- "summary": row["summary"],
1072
- "metadata": _safe_loads(row["metadata_json"]),
1073
- "updated_at": row["updated_at"],
1074
- }
1075
- for row in node_rows
1076
- ]
1077
- edges = list(edges_by_id.values())
1078
- if allowed_workspaces is not None:
1079
- nodes = self.filter_scoped_nodes(
1080
- nodes,
1081
- allowed_workspaces,
1082
- include_legacy_global=include_legacy_global,
1083
- )
1084
- kept = {node.get("id") for node in nodes}
1085
- edges = [edge for edge in edges if edge.get("from") in kept and edge.get("to") in kept]
1086
- return {"root": node_id, "depth": depth, "nodes": nodes, "edges": edges}
1087
-
1088
764
  def delete_conversation(self, conversation_id: str) -> Dict[str, Any]:
1089
765
  conversation_id = str(conversation_id or "").strip()
1090
766
  if not conversation_id:
@@ -1179,44 +855,3 @@ class KnowledgeGraphRetrievalMixin:
1179
855
  shutil.rmtree(self.blob_dir, ignore_errors=True)
1180
856
  self.blob_dir.mkdir(parents=True, exist_ok=True)
1181
857
  return {"status": "ok", "removed": counts}
1182
-
1183
- def stats(self) -> Dict[str, Any]:
1184
- nt, et = self._read_tables()
1185
- with self._connect() as conn:
1186
- node_counts = {
1187
- row["type"]: row["count"]
1188
- for row in conn.execute(
1189
- f"SELECT type, COUNT(*) AS count FROM {nt} GROUP BY type"
1190
- )
1191
- }
1192
- edge_counts = {
1193
- row["type"]: row["count"]
1194
- for row in conn.execute(
1195
- f"SELECT type, COUNT(*) AS count FROM {et} GROUP BY type"
1196
- )
1197
- }
1198
- local_sources = conn.execute(
1199
- "SELECT COUNT(*) AS c FROM knowledge_sources"
1200
- ).fetchone()["c"]
1201
- local_file_status = {
1202
- row["status"]: row["count"]
1203
- for row in conn.execute(
1204
- "SELECT status, COUNT(*) AS count FROM local_file_index GROUP BY status"
1205
- )
1206
- }
1207
- v2 = None
1208
- if KGStoreV2 is not None:
1209
- try:
1210
- v2 = KGStoreV2(self.db_path).stats()
1211
- except Exception as e:
1212
- v2 = {"available": False, "error": str(e)}
1213
- return {
1214
- "db_path": str(self.db_path),
1215
- "schema_version": GRAPH_SCHEMA_VERSION,
1216
- "v2_schema_available": KGStoreV2 is not None,
1217
- "nodes": node_counts,
1218
- "edges": edge_counts,
1219
- "local_sources": local_sources,
1220
- "local_file_status": local_file_status,
1221
- "v2": v2,
1222
- }