ltcai 9.9.4 → 9.9.9
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.
- package/README.md +43 -42
- package/docs/CHANGELOG.md +228 -0
- package/docs/COMMUNITY_AND_PLUGINS.md +1 -1
- package/docs/DEVELOPMENT.md +1 -1
- package/docs/ONBOARDING.md +1 -1
- package/docs/OPERATIONS.md +3 -1
- package/docs/PERMISSION_MODE.md +107 -0
- package/docs/SURFACE_PARITY.md +45 -9
- package/docs/TRUST_MODEL.md +1 -1
- package/docs/WHY_LATTICE.md +1 -1
- package/docs/kg-schema.md +1 -1
- package/lattice_brain/__init__.py +1 -1
- package/lattice_brain/context.py +39 -4
- package/lattice_brain/graph/_kg_common.py +189 -14
- package/lattice_brain/graph/curator.py +62 -0
- package/lattice_brain/graph/discovery.py +76 -0
- package/lattice_brain/graph/ingest.py +37 -7
- package/lattice_brain/graph/rerank.py +160 -0
- package/lattice_brain/graph/retrieval.py +28 -442
- package/lattice_brain/graph/retrieval_reads.py +459 -0
- package/lattice_brain/graph/retrieval_vector.py +10 -0
- package/lattice_brain/graph/store.py +2 -0
- package/lattice_brain/ingestion.py +9 -106
- package/lattice_brain/ingestion_jobs.py +133 -0
- package/lattice_brain/quality.py +26 -6
- package/lattice_brain/runtime/multi_agent.py +1 -1
- package/latticeai/__init__.py +1 -1
- package/latticeai/api/brain_intelligence.py +8 -0
- package/latticeai/api/chat.py +9 -0
- package/latticeai/api/chat_agent_http.py +206 -48
- package/latticeai/api/chat_contracts.py +10 -1
- package/latticeai/api/chat_documents.py +16 -0
- package/latticeai/api/evidence_actions.py +48 -0
- package/latticeai/api/permission_mode.py +61 -0
- package/latticeai/api/project_sessions.py +112 -0
- package/latticeai/api/voice_capture.py +89 -0
- package/latticeai/app_factory.py +53 -0
- package/latticeai/core/agent.py +536 -60
- package/latticeai/core/agent_permission.py +160 -0
- package/latticeai/core/agent_profiles.py +110 -0
- package/latticeai/core/artifact_ledger.py +109 -0
- package/latticeai/core/context_builder.py +101 -2
- package/latticeai/core/legacy_compatibility.py +1 -1
- package/latticeai/core/marketplace.py +1 -1
- package/latticeai/core/permission_mode.py +296 -0
- package/latticeai/core/project_sessions.py +337 -0
- package/latticeai/core/run_explain.py +421 -0
- package/latticeai/core/run_store.py +7 -0
- package/latticeai/core/workspace_os.py +15 -80
- package/latticeai/core/workspace_review_items.py +107 -0
- package/latticeai/integrations/telegram_bot.py +270 -23
- package/latticeai/runtime/chat_wiring.py +8 -0
- package/latticeai/runtime/context_runtime.py +11 -0
- package/latticeai/runtime/permission_mode_wiring.py +116 -0
- package/latticeai/runtime/router_registration.py +9 -0
- package/latticeai/services/app_context.py +3 -0
- package/latticeai/services/architecture_readiness.py +1 -1
- package/latticeai/services/brain_intelligence.py +105 -0
- package/latticeai/services/evidence_actions.py +254 -0
- package/latticeai/services/funnel_metrics.py +111 -16
- package/latticeai/services/local_knowledge.py +26 -0
- package/latticeai/services/memory_service.py +12 -0
- package/latticeai/services/permission_mode_service.py +170 -0
- package/latticeai/services/product_readiness.py +1 -1
- package/latticeai/services/tool_dispatch.py +129 -4
- package/latticeai/services/voice_capture.py +189 -0
- package/package.json +6 -3
- package/scripts/check_bundle_budget.mjs +11 -0
- package/scripts/check_current_release_docs.mjs +1 -1
- package/scripts/check_i18n_namespace_coverage.mjs +148 -0
- package/scripts/run_sidecar_e2e.mjs +159 -0
- package/skills/meeting_notes/SKILL.md +82 -0
- package/skills/meeting_notes/examples.md +41 -0
- package/skills/meeting_notes/risk.json +9 -0
- package/skills/meeting_notes/schema.json +55 -0
- package/skills/weekly_review/SKILL.md +75 -0
- package/skills/weekly_review/examples.md +39 -0
- package/skills/weekly_review/risk.json +9 -0
- package/skills/weekly_review/schema.json +55 -0
- package/src-tauri/Cargo.lock +1 -1
- package/src-tauri/Cargo.toml +1 -1
- package/src-tauri/tauri.conf.json +1 -1
- package/static/app/asset-manifest.json +37 -29
- package/static/app/assets/Act-BFbpl2_Y.js +1 -0
- package/static/app/assets/AdminConsole-DaZPha9Y.js +1 -0
- package/static/app/assets/Brain-DGrV0heZ.js +321 -0
- package/static/app/assets/BrainHome-Re6Zxh_W.js +2 -0
- package/static/app/assets/BrainSignals-BQ11jDpJ.js +1 -0
- package/static/app/assets/Capture-DRaf1zLH.js +1 -0
- package/static/app/assets/CommandPalette-DAKPm4uJ.js +1 -0
- package/static/app/assets/LanguageSwitcher-BgTwHoWv.js +1 -0
- package/static/app/assets/Library-BVtrSt12.js +1 -0
- package/static/app/assets/LivingBrain-7glOmK0R.js +1 -0
- package/static/app/assets/ProductFlow-cB3EFinZ.js +1 -0
- package/static/app/assets/ReviewCard-CShhHS-w.js +3 -0
- package/static/app/assets/System-B4nQDy8a.js +1 -0
- package/static/app/assets/{bot-nB_buEZD.js → bot-DtKkLfXj.js} +1 -1
- package/static/app/assets/brain-wVV63_1z.js +1 -0
- package/static/app/assets/button-BTxZDMFJ.js +1 -0
- package/static/app/assets/{circle-pause-DLNw6Ucp.js → circle-pause--qxF9-EO.js} +1 -1
- package/static/app/assets/{circle-play-B-IsFL1y.js → circle-play-89x3S6jm.js} +1 -1
- package/static/app/assets/{cpu-CEPBHaBl.js → cpu-DTUI63vo.js} +1 -1
- package/static/app/assets/download-EJS5_O0f.js +1 -0
- package/static/app/assets/{folder-open-hmN0N9cX.js → folder-open-BL9zYTnc.js} +1 -1
- package/static/app/assets/{hard-drive-CBV_B_Yd.js → hard-drive-BFnwi1Lu.js} +1 -1
- package/static/app/assets/index-BFtDYI6l.js +10 -0
- package/static/app/assets/index-BY9bpxyx.css +2 -0
- package/static/app/assets/input-DEz5UjBz.js +1 -0
- package/static/app/assets/{network-jE42eKfT.js → network-zKa3jAwl.js} +1 -1
- package/static/app/assets/primitives-jNrZm2O9.js +1 -0
- package/static/app/assets/search-ku6-_6wY.js +1 -0
- package/static/app/assets/shield-alert-CpHeCsaF.js +1 -0
- package/static/app/assets/textarea-DpcQkn75.js +1 -0
- package/static/app/assets/{useFocusTrap-B7RPGfFy.js → useFocusTrap-58TNCONM.js} +1 -1
- package/static/app/assets/{navigation-Bot0hvuv.js → useQuery-CcVlXlBd.js} +1 -1
- package/static/app/assets/users-C0cFMj6o.js +1 -0
- package/static/app/assets/utils-DYf7pqrR.js +7 -0
- package/static/app/assets/workspace-CjthHsLN.js +1 -0
- package/static/app/index.html +4 -4
- package/static/sw.js +1 -1
- package/static/app/assets/Act-BCmTU0E2.js +0 -1
- package/static/app/assets/Brain-CTnjox7w.js +0 -321
- package/static/app/assets/BrainHome-BJ3sFNX0.js +0 -2
- package/static/app/assets/BrainSignals-C52lwZVD.js +0 -1
- package/static/app/assets/Capture-B6vBhFa3.js +0 -1
- package/static/app/assets/CommandPalette-90u9FWFH.js +0 -1
- package/static/app/assets/Library-pKCK0_tk.js +0 -1
- package/static/app/assets/LivingBrain-Jlf2wFqI.js +0 -1
- package/static/app/assets/ProductFlow-yg1fKP1P.js +0 -1
- package/static/app/assets/ReviewCard-DWvD7n9h.js +0 -3
- package/static/app/assets/System-BAEuHqNY.js +0 -1
- package/static/app/assets/index-7FAfYm4v.css +0 -2
- package/static/app/assets/index-DrmOCySv.js +0 -10
- package/static/app/assets/input-gtVCg-ll.js +0 -1
- package/static/app/assets/primitives-CX2Komon.js +0 -1
- package/static/app/assets/shield-alert-BftATuAA.js +0 -1
- package/static/app/assets/textarea-CiMJfOSI.js +0 -1
- package/static/app/assets/utils-SJUNVOj5.js +0 -7
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Optional cross-encoder rerank for hybrid retrieval (v9.9.5).
|
|
2
|
+
|
|
3
|
+
Default path is identity (fused score preserved) — no model download, no
|
|
4
|
+
latency tax, no unearned claims. Opt in with::
|
|
5
|
+
|
|
6
|
+
LATTICEAI_CROSS_ENCODER_RERANK=1
|
|
7
|
+
# optional model id (sentence-transformers CrossEncoder):
|
|
8
|
+
LATTICEAI_CROSS_ENCODER_MODEL=cross-encoder/ms-marco-MiniLM-L-6-v2
|
|
9
|
+
|
|
10
|
+
When the env kill-switch is off, or ``sentence_transformers`` / the model is
|
|
11
|
+
unavailable, :func:`rerank_matches` returns the candidates unchanged and
|
|
12
|
+
reports ``mode="identity"``. Failures never raise into the search path.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import logging
|
|
18
|
+
import os
|
|
19
|
+
from typing import Any, Dict, List, Optional
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
CROSS_ENCODER_RERANK_ENV = "LATTICEAI_CROSS_ENCODER_RERANK"
|
|
24
|
+
CROSS_ENCODER_MODEL_ENV = "LATTICEAI_CROSS_ENCODER_MODEL"
|
|
25
|
+
DEFAULT_CROSS_ENCODER_MODEL = "cross-encoder/ms-marco-MiniLM-L-6-v2"
|
|
26
|
+
|
|
27
|
+
_model_cache: Dict[str, Any] = {}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _rerank_enabled() -> bool:
|
|
31
|
+
raw = os.getenv(CROSS_ENCODER_RERANK_ENV, "").strip().lower()
|
|
32
|
+
return raw in {"1", "true", "yes", "on"}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _model_id() -> str:
|
|
36
|
+
raw = os.getenv(CROSS_ENCODER_MODEL_ENV, "").strip()
|
|
37
|
+
return raw or DEFAULT_CROSS_ENCODER_MODEL
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _candidate_text(match: Dict[str, Any]) -> str:
|
|
41
|
+
parts = [
|
|
42
|
+
str(match.get("title") or ""),
|
|
43
|
+
str(match.get("summary") or ""),
|
|
44
|
+
str((match.get("metadata") or {}).get("snippet") or ""),
|
|
45
|
+
]
|
|
46
|
+
return " ".join(p for p in parts if p).strip() or str(match.get("node_id") or "")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _load_cross_encoder(model_id: str) -> Any:
|
|
50
|
+
if model_id in _model_cache:
|
|
51
|
+
return _model_cache[model_id]
|
|
52
|
+
from sentence_transformers import CrossEncoder # type: ignore
|
|
53
|
+
|
|
54
|
+
model = CrossEncoder(model_id)
|
|
55
|
+
_model_cache[model_id] = model
|
|
56
|
+
return model
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def identity_rerank(
|
|
60
|
+
query: str,
|
|
61
|
+
candidates: List[Dict[str, Any]],
|
|
62
|
+
*,
|
|
63
|
+
top_k: Optional[int] = None,
|
|
64
|
+
) -> Dict[str, Any]:
|
|
65
|
+
"""Preserve fused ordering; stamp identity scores for an honest contract."""
|
|
66
|
+
del query # identity path does not use the query text
|
|
67
|
+
ranked = list(candidates)
|
|
68
|
+
for item in ranked:
|
|
69
|
+
item["rerank_score"] = float(item.get("score") or item.get("fused_score") or 0.0)
|
|
70
|
+
if top_k is not None:
|
|
71
|
+
ranked = ranked[: max(1, int(top_k))]
|
|
72
|
+
return {
|
|
73
|
+
"matches": ranked,
|
|
74
|
+
"mode": "identity",
|
|
75
|
+
"model": None,
|
|
76
|
+
"detail": None,
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def cross_encoder_rerank(
|
|
81
|
+
query: str,
|
|
82
|
+
candidates: List[Dict[str, Any]],
|
|
83
|
+
*,
|
|
84
|
+
top_k: Optional[int] = None,
|
|
85
|
+
model_id: Optional[str] = None,
|
|
86
|
+
) -> Dict[str, Any]:
|
|
87
|
+
"""Score (query, candidate) pairs with a CrossEncoder when available."""
|
|
88
|
+
if not candidates:
|
|
89
|
+
return {
|
|
90
|
+
"matches": [],
|
|
91
|
+
"mode": "cross_encoder",
|
|
92
|
+
"model": model_id or _model_id(),
|
|
93
|
+
"detail": None,
|
|
94
|
+
}
|
|
95
|
+
mid = model_id or _model_id()
|
|
96
|
+
try:
|
|
97
|
+
model = _load_cross_encoder(mid)
|
|
98
|
+
except Exception as exc: # noqa: BLE001 — never break search
|
|
99
|
+
logger.info("cross-encoder unavailable (%s); falling back to identity", exc)
|
|
100
|
+
result = identity_rerank(query, candidates, top_k=top_k)
|
|
101
|
+
result["detail"] = f"cross_encoder_unavailable: {exc}"
|
|
102
|
+
return result
|
|
103
|
+
|
|
104
|
+
pairs = [[str(query or ""), _candidate_text(c)] for c in candidates]
|
|
105
|
+
try:
|
|
106
|
+
scores = model.predict(pairs)
|
|
107
|
+
except Exception as exc: # noqa: BLE001
|
|
108
|
+
logger.warning("cross-encoder predict failed: %s", exc)
|
|
109
|
+
result = identity_rerank(query, candidates, top_k=top_k)
|
|
110
|
+
result["detail"] = f"cross_encoder_predict_failed: {exc}"
|
|
111
|
+
return result
|
|
112
|
+
|
|
113
|
+
ranked = list(candidates)
|
|
114
|
+
for item, score in zip(ranked, scores):
|
|
115
|
+
item["rerank_score"] = float(score)
|
|
116
|
+
# Surface the rerank score as the primary ranking key while keeping
|
|
117
|
+
# the pre-rerank fused score under scores.fused for audit.
|
|
118
|
+
scores_map = item.setdefault("scores", {})
|
|
119
|
+
if isinstance(scores_map, dict):
|
|
120
|
+
scores_map.setdefault("fused", float(item.get("score") or 0.0))
|
|
121
|
+
scores_map["rerank"] = float(score)
|
|
122
|
+
item["score"] = float(score)
|
|
123
|
+
ranked.sort(key=lambda m: (-float(m.get("rerank_score") or 0.0), str(m.get("node_id") or "")))
|
|
124
|
+
if top_k is not None:
|
|
125
|
+
ranked = ranked[: max(1, int(top_k))]
|
|
126
|
+
for rank, match in enumerate(ranked, start=1):
|
|
127
|
+
match["rank"] = rank
|
|
128
|
+
return {
|
|
129
|
+
"matches": ranked,
|
|
130
|
+
"mode": "cross_encoder",
|
|
131
|
+
"model": mid,
|
|
132
|
+
"detail": None,
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def rerank_matches(
|
|
137
|
+
query: str,
|
|
138
|
+
candidates: List[Dict[str, Any]],
|
|
139
|
+
*,
|
|
140
|
+
top_k: Optional[int] = None,
|
|
141
|
+
force: Optional[bool] = None,
|
|
142
|
+
) -> Dict[str, Any]:
|
|
143
|
+
"""Public entry: cross-encoder when enabled, else identity.
|
|
144
|
+
|
|
145
|
+
``force=True/False`` overrides the env kill-switch (tests only).
|
|
146
|
+
"""
|
|
147
|
+
enabled = _rerank_enabled() if force is None else bool(force)
|
|
148
|
+
if not enabled:
|
|
149
|
+
return identity_rerank(query, candidates, top_k=top_k)
|
|
150
|
+
return cross_encoder_rerank(query, candidates, top_k=top_k)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
__all__ = [
|
|
154
|
+
"CROSS_ENCODER_MODEL_ENV",
|
|
155
|
+
"CROSS_ENCODER_RERANK_ENV",
|
|
156
|
+
"DEFAULT_CROSS_ENCODER_MODEL",
|
|
157
|
+
"cross_encoder_rerank",
|
|
158
|
+
"identity_rerank",
|
|
159
|
+
"rerank_matches",
|
|
160
|
+
]
|
|
@@ -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,
|
|
@@ -679,7 +574,25 @@ class KnowledgeGraphRetrievalMixin:
|
|
|
679
574
|
match["score"] = round(float(match["score"]) * multiplier, 6)
|
|
680
575
|
|
|
681
576
|
matches.sort(key=lambda item: (-item["score"], item["node_id"]))
|
|
682
|
-
|
|
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)}
|
|
683
596
|
for rank, match in enumerate(matches, start=1):
|
|
684
597
|
match["rank"] = rank
|
|
685
598
|
result = {
|
|
@@ -691,6 +604,7 @@ class KnowledgeGraphRetrievalMixin:
|
|
|
691
604
|
"sources": {"lexical": len(lexical_matches), "vector": len(vector_matches)},
|
|
692
605
|
"matches": matches,
|
|
693
606
|
"policy": {"search_query": search_query, "rewrite_rules": rewrite_rules},
|
|
607
|
+
"rerank": rerank_meta,
|
|
694
608
|
"detail": detail,
|
|
695
609
|
}
|
|
696
610
|
if vector_degraded is not None:
|
|
@@ -847,293 +761,6 @@ class KnowledgeGraphRetrievalMixin:
|
|
|
847
761
|
with_meta=True,
|
|
848
762
|
)
|
|
849
763
|
|
|
850
|
-
def neighbors(
|
|
851
|
-
self,
|
|
852
|
-
node_id: str,
|
|
853
|
-
*,
|
|
854
|
-
allowed_workspaces=None,
|
|
855
|
-
include_legacy_global: bool = False,
|
|
856
|
-
) -> Dict[str, Any]:
|
|
857
|
-
"""Return direct neighbors (1-hop) of a node."""
|
|
858
|
-
if allowed_workspaces is not None and not self.filter_scoped_nodes(
|
|
859
|
-
[{"id": node_id}],
|
|
860
|
-
allowed_workspaces,
|
|
861
|
-
include_legacy_global=include_legacy_global,
|
|
862
|
-
):
|
|
863
|
-
raise ValueError(f"graph node not found: {node_id}")
|
|
864
|
-
nt, et = self._read_tables()
|
|
865
|
-
with self._connect() as conn:
|
|
866
|
-
edge_rows = conn.execute(
|
|
867
|
-
f"SELECT from_node, to_node, type, weight FROM {et} WHERE from_node=? OR to_node=? ORDER BY id ASC",
|
|
868
|
-
(node_id, node_id),
|
|
869
|
-
).fetchall()
|
|
870
|
-
neighbor_ids: set = set()
|
|
871
|
-
edges = []
|
|
872
|
-
for row in edge_rows:
|
|
873
|
-
neighbor_ids.add(row["from_node"])
|
|
874
|
-
neighbor_ids.add(row["to_node"])
|
|
875
|
-
edges.append(
|
|
876
|
-
{
|
|
877
|
-
"from": row["from_node"],
|
|
878
|
-
"to": row["to_node"],
|
|
879
|
-
"type": row["type"],
|
|
880
|
-
"weight": row["weight"],
|
|
881
|
-
}
|
|
882
|
-
)
|
|
883
|
-
neighbor_ids.discard(node_id)
|
|
884
|
-
nodes = []
|
|
885
|
-
if neighbor_ids:
|
|
886
|
-
placeholders = ",".join("?" * len(neighbor_ids))
|
|
887
|
-
nodes = [
|
|
888
|
-
{
|
|
889
|
-
"id": row["id"],
|
|
890
|
-
"type": row["type"],
|
|
891
|
-
"title": row["title"],
|
|
892
|
-
"summary": row["summary"],
|
|
893
|
-
"metadata": _safe_loads(row["metadata_json"]),
|
|
894
|
-
}
|
|
895
|
-
for row in conn.execute(
|
|
896
|
-
f"SELECT id, type, title, summary, metadata_json FROM {nt} WHERE id IN ({placeholders}) ORDER BY id ASC",
|
|
897
|
-
list(neighbor_ids),
|
|
898
|
-
)
|
|
899
|
-
]
|
|
900
|
-
if allowed_workspaces is not None:
|
|
901
|
-
nodes = self.filter_scoped_nodes(
|
|
902
|
-
nodes,
|
|
903
|
-
allowed_workspaces,
|
|
904
|
-
include_legacy_global=include_legacy_global,
|
|
905
|
-
)
|
|
906
|
-
kept = {node.get("id") for node in nodes}
|
|
907
|
-
edges = [
|
|
908
|
-
edge for edge in edges
|
|
909
|
-
if (edge.get("from") == node_id or edge.get("from") in kept)
|
|
910
|
-
and (edge.get("to") == node_id or edge.get("to") in kept)
|
|
911
|
-
]
|
|
912
|
-
return {"node_id": node_id, "neighbors": nodes, "edges": edges}
|
|
913
|
-
|
|
914
|
-
def get_node(
|
|
915
|
-
self,
|
|
916
|
-
node_id: str,
|
|
917
|
-
*,
|
|
918
|
-
allowed_workspaces=None,
|
|
919
|
-
include_legacy_global: bool = False,
|
|
920
|
-
) -> Dict[str, Any]:
|
|
921
|
-
node_id = str(node_id or "").strip()
|
|
922
|
-
if not node_id:
|
|
923
|
-
raise ValueError("node_id required")
|
|
924
|
-
nt, et = self._read_tables()
|
|
925
|
-
with self._connect() as conn:
|
|
926
|
-
row = conn.execute(
|
|
927
|
-
f"""
|
|
928
|
-
SELECT id, type, title, summary, metadata_json, updated_at
|
|
929
|
-
FROM {nt}
|
|
930
|
-
WHERE id=?
|
|
931
|
-
""",
|
|
932
|
-
(node_id,),
|
|
933
|
-
).fetchone()
|
|
934
|
-
if not row:
|
|
935
|
-
raise ValueError(f"graph node not found: {node_id}")
|
|
936
|
-
degree = conn.execute(
|
|
937
|
-
f"SELECT COUNT(*) AS c FROM {et} WHERE from_node=? OR to_node=?",
|
|
938
|
-
(node_id, node_id),
|
|
939
|
-
).fetchone()["c"]
|
|
940
|
-
node = {
|
|
941
|
-
"id": row["id"],
|
|
942
|
-
"type": row["type"],
|
|
943
|
-
"title": row["title"],
|
|
944
|
-
"summary": row["summary"],
|
|
945
|
-
"metadata": _safe_loads(row["metadata_json"]),
|
|
946
|
-
"updated_at": row["updated_at"],
|
|
947
|
-
"degree": degree,
|
|
948
|
-
}
|
|
949
|
-
if allowed_workspaces is not None and not self.filter_scoped_nodes(
|
|
950
|
-
[node],
|
|
951
|
-
allowed_workspaces,
|
|
952
|
-
include_legacy_global=include_legacy_global,
|
|
953
|
-
):
|
|
954
|
-
raise ValueError(f"graph node not found: {node_id}")
|
|
955
|
-
return node
|
|
956
|
-
|
|
957
|
-
def relationship_search(
|
|
958
|
-
self,
|
|
959
|
-
*,
|
|
960
|
-
query: str = "",
|
|
961
|
-
node_id: str = "",
|
|
962
|
-
relationship_type: str = "",
|
|
963
|
-
limit: int = 30,
|
|
964
|
-
allowed_workspaces=None,
|
|
965
|
-
include_legacy_global: bool = False,
|
|
966
|
-
) -> Dict[str, Any]:
|
|
967
|
-
query = str(query or "").strip()
|
|
968
|
-
node_id = str(node_id or "").strip()
|
|
969
|
-
relationship_type = str(relationship_type or "").strip()
|
|
970
|
-
limit = max(1, min(int(limit or 30), 200))
|
|
971
|
-
nt, et = self._read_tables()
|
|
972
|
-
where = []
|
|
973
|
-
params: List[Any] = []
|
|
974
|
-
if node_id:
|
|
975
|
-
where.append("(e.from_node=? OR e.to_node=?)")
|
|
976
|
-
params.extend([node_id, node_id])
|
|
977
|
-
if relationship_type:
|
|
978
|
-
where.append("e.type LIKE ?")
|
|
979
|
-
params.append(f"%{relationship_type}%")
|
|
980
|
-
if query:
|
|
981
|
-
where.append(
|
|
982
|
-
"(e.type LIKE ? OR e.metadata_json LIKE ? OR src.title LIKE ? OR dst.title LIKE ? OR src.summary LIKE ? OR dst.summary LIKE ?)"
|
|
983
|
-
)
|
|
984
|
-
params.extend([f"%{query}%"] * 6)
|
|
985
|
-
where_sql = "WHERE " + " AND ".join(where) if where else ""
|
|
986
|
-
with self._connect() as conn:
|
|
987
|
-
rows = conn.execute(
|
|
988
|
-
f"""
|
|
989
|
-
SELECT
|
|
990
|
-
e.id, e.from_node, e.to_node, e.type, e.weight, e.metadata_json, e.created_at,
|
|
991
|
-
src.type AS source_type, src.title AS source_title, src.summary AS source_summary,
|
|
992
|
-
src.metadata_json AS source_metadata,
|
|
993
|
-
dst.type AS target_type, dst.title AS target_title, dst.summary AS target_summary,
|
|
994
|
-
dst.metadata_json AS target_metadata
|
|
995
|
-
FROM {et} e
|
|
996
|
-
JOIN {nt} src ON src.id=e.from_node
|
|
997
|
-
JOIN {nt} dst ON dst.id=e.to_node
|
|
998
|
-
{where_sql}
|
|
999
|
-
ORDER BY e.weight DESC, e.created_at DESC, e.id ASC
|
|
1000
|
-
LIMIT ?
|
|
1001
|
-
""",
|
|
1002
|
-
(*params, limit),
|
|
1003
|
-
).fetchall()
|
|
1004
|
-
relationships = [
|
|
1005
|
-
{
|
|
1006
|
-
"id": row["id"],
|
|
1007
|
-
"type": row["type"],
|
|
1008
|
-
"weight": row["weight"],
|
|
1009
|
-
"metadata": _safe_loads(row["metadata_json"]),
|
|
1010
|
-
"created_at": row["created_at"],
|
|
1011
|
-
"source": {
|
|
1012
|
-
"id": row["from_node"],
|
|
1013
|
-
"type": row["source_type"],
|
|
1014
|
-
"title": row["source_title"],
|
|
1015
|
-
"summary": row["source_summary"],
|
|
1016
|
-
"metadata": _safe_loads(row["source_metadata"]),
|
|
1017
|
-
},
|
|
1018
|
-
"target": {
|
|
1019
|
-
"id": row["to_node"],
|
|
1020
|
-
"type": row["target_type"],
|
|
1021
|
-
"title": row["target_title"],
|
|
1022
|
-
"summary": row["target_summary"],
|
|
1023
|
-
"metadata": _safe_loads(row["target_metadata"]),
|
|
1024
|
-
},
|
|
1025
|
-
}
|
|
1026
|
-
for row in rows
|
|
1027
|
-
]
|
|
1028
|
-
if allowed_workspaces is not None:
|
|
1029
|
-
kept = []
|
|
1030
|
-
for rel in relationships:
|
|
1031
|
-
endpoints = [
|
|
1032
|
-
{"id": (rel.get("source") or {}).get("id")},
|
|
1033
|
-
{"id": (rel.get("target") or {}).get("id")},
|
|
1034
|
-
]
|
|
1035
|
-
if len(
|
|
1036
|
-
self.filter_scoped_nodes(
|
|
1037
|
-
endpoints,
|
|
1038
|
-
allowed_workspaces,
|
|
1039
|
-
include_legacy_global=include_legacy_global,
|
|
1040
|
-
)
|
|
1041
|
-
) == 2:
|
|
1042
|
-
kept.append(rel)
|
|
1043
|
-
relationships = kept
|
|
1044
|
-
return {
|
|
1045
|
-
"query": query,
|
|
1046
|
-
"node_id": node_id,
|
|
1047
|
-
"relationship_type": relationship_type,
|
|
1048
|
-
"relationships": relationships,
|
|
1049
|
-
}
|
|
1050
|
-
|
|
1051
|
-
def traverse(
|
|
1052
|
-
self,
|
|
1053
|
-
node_id: str,
|
|
1054
|
-
*,
|
|
1055
|
-
depth: int = 1,
|
|
1056
|
-
limit: int = 100,
|
|
1057
|
-
allowed_workspaces=None,
|
|
1058
|
-
include_legacy_global: bool = False,
|
|
1059
|
-
) -> Dict[str, Any]:
|
|
1060
|
-
node_id = str(node_id or "").strip()
|
|
1061
|
-
if not node_id:
|
|
1062
|
-
raise ValueError("node_id required")
|
|
1063
|
-
if allowed_workspaces is not None and not self.filter_scoped_nodes(
|
|
1064
|
-
[{"id": node_id}],
|
|
1065
|
-
allowed_workspaces,
|
|
1066
|
-
include_legacy_global=include_legacy_global,
|
|
1067
|
-
):
|
|
1068
|
-
raise ValueError(f"graph node not found: {node_id}")
|
|
1069
|
-
depth = max(0, min(int(depth or 1), 4))
|
|
1070
|
-
limit = max(1, min(int(limit or 100), 500))
|
|
1071
|
-
nt, et = self._read_tables()
|
|
1072
|
-
visited = {node_id}
|
|
1073
|
-
frontier = {node_id}
|
|
1074
|
-
edges_by_id: Dict[str, Dict[str, Any]] = {}
|
|
1075
|
-
with self._connect() as conn:
|
|
1076
|
-
for _ in range(depth):
|
|
1077
|
-
if not frontier or len(visited) >= limit:
|
|
1078
|
-
break
|
|
1079
|
-
placeholders = ",".join("?" * len(frontier))
|
|
1080
|
-
rows = conn.execute(
|
|
1081
|
-
f"""
|
|
1082
|
-
SELECT id, from_node, to_node, type, weight, metadata_json
|
|
1083
|
-
FROM {et}
|
|
1084
|
-
WHERE from_node IN ({placeholders}) OR to_node IN ({placeholders})
|
|
1085
|
-
ORDER BY weight DESC, id ASC
|
|
1086
|
-
LIMIT ?
|
|
1087
|
-
""",
|
|
1088
|
-
(*frontier, *frontier, limit * 3),
|
|
1089
|
-
).fetchall()
|
|
1090
|
-
next_frontier = set()
|
|
1091
|
-
for row in rows:
|
|
1092
|
-
edges_by_id[row["id"]] = {
|
|
1093
|
-
"id": row["id"],
|
|
1094
|
-
"from": row["from_node"],
|
|
1095
|
-
"to": row["to_node"],
|
|
1096
|
-
"type": row["type"],
|
|
1097
|
-
"weight": row["weight"],
|
|
1098
|
-
"metadata": _safe_loads(row["metadata_json"]),
|
|
1099
|
-
}
|
|
1100
|
-
for candidate in (row["from_node"], row["to_node"]):
|
|
1101
|
-
if candidate not in visited and len(visited) < limit:
|
|
1102
|
-
visited.add(candidate)
|
|
1103
|
-
next_frontier.add(candidate)
|
|
1104
|
-
frontier = next_frontier
|
|
1105
|
-
placeholders = ",".join("?" * len(visited))
|
|
1106
|
-
node_rows = conn.execute(
|
|
1107
|
-
f"""
|
|
1108
|
-
SELECT id, type, title, summary, metadata_json, updated_at
|
|
1109
|
-
FROM {nt}
|
|
1110
|
-
WHERE id IN ({placeholders})
|
|
1111
|
-
ORDER BY updated_at DESC, id ASC
|
|
1112
|
-
""",
|
|
1113
|
-
list(visited),
|
|
1114
|
-
).fetchall()
|
|
1115
|
-
nodes = [
|
|
1116
|
-
{
|
|
1117
|
-
"id": row["id"],
|
|
1118
|
-
"type": row["type"],
|
|
1119
|
-
"title": row["title"],
|
|
1120
|
-
"summary": row["summary"],
|
|
1121
|
-
"metadata": _safe_loads(row["metadata_json"]),
|
|
1122
|
-
"updated_at": row["updated_at"],
|
|
1123
|
-
}
|
|
1124
|
-
for row in node_rows
|
|
1125
|
-
]
|
|
1126
|
-
edges = list(edges_by_id.values())
|
|
1127
|
-
if allowed_workspaces is not None:
|
|
1128
|
-
nodes = self.filter_scoped_nodes(
|
|
1129
|
-
nodes,
|
|
1130
|
-
allowed_workspaces,
|
|
1131
|
-
include_legacy_global=include_legacy_global,
|
|
1132
|
-
)
|
|
1133
|
-
kept = {node.get("id") for node in nodes}
|
|
1134
|
-
edges = [edge for edge in edges if edge.get("from") in kept and edge.get("to") in kept]
|
|
1135
|
-
return {"root": node_id, "depth": depth, "nodes": nodes, "edges": edges}
|
|
1136
|
-
|
|
1137
764
|
def delete_conversation(self, conversation_id: str) -> Dict[str, Any]:
|
|
1138
765
|
conversation_id = str(conversation_id or "").strip()
|
|
1139
766
|
if not conversation_id:
|
|
@@ -1228,44 +855,3 @@ class KnowledgeGraphRetrievalMixin:
|
|
|
1228
855
|
shutil.rmtree(self.blob_dir, ignore_errors=True)
|
|
1229
856
|
self.blob_dir.mkdir(parents=True, exist_ok=True)
|
|
1230
857
|
return {"status": "ok", "removed": counts}
|
|
1231
|
-
|
|
1232
|
-
def stats(self) -> Dict[str, Any]:
|
|
1233
|
-
nt, et = self._read_tables()
|
|
1234
|
-
with self._connect() as conn:
|
|
1235
|
-
node_counts = {
|
|
1236
|
-
row["type"]: row["count"]
|
|
1237
|
-
for row in conn.execute(
|
|
1238
|
-
f"SELECT type, COUNT(*) AS count FROM {nt} GROUP BY type"
|
|
1239
|
-
)
|
|
1240
|
-
}
|
|
1241
|
-
edge_counts = {
|
|
1242
|
-
row["type"]: row["count"]
|
|
1243
|
-
for row in conn.execute(
|
|
1244
|
-
f"SELECT type, COUNT(*) AS count FROM {et} GROUP BY type"
|
|
1245
|
-
)
|
|
1246
|
-
}
|
|
1247
|
-
local_sources = conn.execute(
|
|
1248
|
-
"SELECT COUNT(*) AS c FROM knowledge_sources"
|
|
1249
|
-
).fetchone()["c"]
|
|
1250
|
-
local_file_status = {
|
|
1251
|
-
row["status"]: row["count"]
|
|
1252
|
-
for row in conn.execute(
|
|
1253
|
-
"SELECT status, COUNT(*) AS count FROM local_file_index GROUP BY status"
|
|
1254
|
-
)
|
|
1255
|
-
}
|
|
1256
|
-
v2 = None
|
|
1257
|
-
if KGStoreV2 is not None:
|
|
1258
|
-
try:
|
|
1259
|
-
v2 = KGStoreV2(self.db_path).stats()
|
|
1260
|
-
except Exception as e:
|
|
1261
|
-
v2 = {"available": False, "error": str(e)}
|
|
1262
|
-
return {
|
|
1263
|
-
"db_path": str(self.db_path),
|
|
1264
|
-
"schema_version": GRAPH_SCHEMA_VERSION,
|
|
1265
|
-
"v2_schema_available": KGStoreV2 is not None,
|
|
1266
|
-
"nodes": node_counts,
|
|
1267
|
-
"edges": edge_counts,
|
|
1268
|
-
"local_sources": local_sources,
|
|
1269
|
-
"local_file_status": local_file_status,
|
|
1270
|
-
"v2": v2,
|
|
1271
|
-
}
|