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.
- package/README.md +39 -38
- package/docs/CHANGELOG.md +100 -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 +1 -1
- package/docs/SURFACE_PARITY.md +53 -0
- 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/graph/_kg_common.py +335 -0
- package/lattice_brain/graph/discovery_index.py +8 -1
- package/lattice_brain/graph/ingest.py +43 -9
- package/lattice_brain/graph/projection.py +221 -37
- package/lattice_brain/graph/rerank.py +160 -0
- package/lattice_brain/graph/retrieval.py +90 -455
- package/lattice_brain/graph/retrieval_policy.py +174 -0
- package/lattice_brain/graph/retrieval_reads.py +459 -0
- package/lattice_brain/graph/retrieval_vector.py +122 -2
- package/lattice_brain/graph/store.py +2 -0
- package/lattice_brain/portability.py +41 -12
- 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/chat.py +6 -0
- package/latticeai/api/chat_agent_http.py +262 -52
- package/latticeai/api/chat_contracts.py +1 -1
- package/latticeai/api/chat_intents.py +37 -18
- package/latticeai/api/chat_stream.py +76 -2
- package/latticeai/api/knowledge_graph.py +35 -1
- package/latticeai/core/agent.py +420 -27
- package/latticeai/core/enterprise.py +5 -0
- package/latticeai/core/file_generation.py +130 -5
- package/latticeai/core/legacy_compatibility.py +1 -1
- package/latticeai/core/marketplace.py +1 -1
- package/latticeai/core/run_store.py +245 -0
- package/latticeai/core/workspace_os.py +1 -1
- package/latticeai/integrations/telegram_bot.py +82 -23
- package/latticeai/models/router.py +25 -12
- package/latticeai/services/architecture_readiness.py +1 -1
- package/latticeai/services/command_center.py +90 -1
- package/latticeai/services/folder_watch.py +5 -0
- package/latticeai/services/funnel_metrics.py +9 -1
- package/latticeai/services/product_readiness.py +1 -1
- package/latticeai/services/search_service.py +43 -13
- package/latticeai/services/tool_dispatch.py +56 -0
- package/package.json +2 -1
- package/scripts/bench_agent_smoke.py +410 -0
- package/scripts/check_current_release_docs.mjs +1 -1
- package/scripts/funnel_soft_gate.py +192 -0
- package/scripts/run_sidecar_e2e.mjs +159 -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 +29 -28
- package/static/app/assets/Act-DmxfbqBp.js +1 -0
- package/static/app/assets/{Brain-DEY9jLVt.js → Brain-DK_zKCda.js} +2 -2
- package/static/app/assets/BrainHome-CCE_0hni.js +2 -0
- package/static/app/assets/BrainSignals-r_J68_zh.js +1 -0
- package/static/app/assets/{Capture-CVZ09QXi.js → Capture-CvxwzpJZ.js} +1 -1
- package/static/app/assets/{CommandPalette-DepwOQFv.js → CommandPalette-CVLiFIQC.js} +1 -1
- package/static/app/assets/{Library-Bp0n-HlW.js → Library-4As9VUvy.js} +1 -1
- package/static/app/assets/{LivingBrain-DxP4efJF.js → LivingBrain-BVWk58MW.js} +1 -1
- package/static/app/assets/{ProductFlow-DRbm7NEq.js → ProductFlow-B-Tz0Um4.js} +1 -1
- package/static/app/assets/{ReviewCard-C4HAO7A3.js → ReviewCard-Va3fPQuj.js} +1 -1
- package/static/app/assets/{System-ByQcmJW-.js → System-DSR2zKWd.js} +1 -1
- package/static/app/assets/{bot-BNDyZLR7.js → bot-VmP0kkeA.js} +1 -1
- package/static/app/assets/circle-pause-T9POo4qy.js +1 -0
- package/static/app/assets/{circle-play-BkhdcHgd.js → circle-play-Bz5iTD0p.js} +1 -1
- package/static/app/assets/{cpu-C6jjYm6i.js → cpu-CJhjRtNq.js} +1 -1
- package/static/app/assets/{folder-open-DjGIvDBQ.js → folder-open-B2K_22VI.js} +1 -1
- package/static/app/assets/{hard-drive-BlSbwSaT.js → hard-drive-CjJtYqHf.js} +1 -1
- package/static/app/assets/{index-Bge3DXW7.css → index-7FAfYm4v.css} +1 -1
- package/static/app/assets/{index-CHu7cgj3.js → index-CEu0Wqjl.js} +3 -3
- package/static/app/assets/{input-DVDI0YR3.js → input-CSi6OBJ9.js} +1 -1
- package/static/app/assets/{navigation-BddhEWA0.js → navigation-BPQqEQwr.js} +1 -1
- package/static/app/assets/{network-pYQt5oBu.js → network-Ck1nqc-v.js} +1 -1
- package/static/app/assets/{primitives-D7gCdEvS.js → primitives-B2f9N7Dh.js} +1 -1
- package/static/app/assets/{shield-alert-K9RKGQeg.js → shield-alert-yA_Y8lOB.js} +1 -1
- package/static/app/assets/{textarea-sqQmoBKL.js → textarea-C4wM0D-Z.js} +1 -1
- package/static/app/assets/{useFocusTrap-7EV9dFP2.js → useFocusTrap-CsnIhsDJ.js} +1 -1
- package/static/app/assets/utils-BqoznzGP.js +7 -0
- package/static/app/index.html +4 -4
- package/static/sw.js +1 -1
- package/static/app/assets/Act-DmdruVKV.js +0 -1
- package/static/app/assets/BrainHome-CeNaxjP1.js +0 -2
- package/static/app/assets/BrainSignals-CStjIqYi.js +0 -1
- package/static/app/assets/utils-uQYKXNeq.js +0 -7
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Single retrieval policy consulted by both hybrid fusion layers.
|
|
2
|
+
|
|
3
|
+
Review 2026-07-25 (UX/harness/loop/KG-RAG), Wave 0.2 — "RetrievalPolicy
|
|
4
|
+
단일화" + "query rewrite" + "recency age decay". Before this module the two
|
|
5
|
+
hybrid entry points (``KnowledgeGraphStore.hybrid_search`` two-channel
|
|
6
|
+
alpha fusion and ``SearchService.hybrid_search`` three-channel weight
|
|
7
|
+
fusion) each resolved :func:`lattice_brain.graph.fusion.fusion_profile`
|
|
8
|
+
independently and had no shared place to hang retrieval-wide behavior.
|
|
9
|
+
This module is that single place:
|
|
10
|
+
|
|
11
|
+
* :func:`rewrite_query` — deterministic, rule-based ko/en normalization
|
|
12
|
+
(NO LLM). Strips a conservative fixed list of leading/trailing politeness
|
|
13
|
+
fillers ("~좀 알려줘", "궁금해", "뭐였지", "what is", "please", …) and
|
|
14
|
+
collapses repeated whitespace. Code-class queries pass through untouched
|
|
15
|
+
(except whitespace collapse) because exact identifiers/filenames ARE the
|
|
16
|
+
retrieval signal. ``LATTICEAI_QUERY_REWRITE=0`` disables rewriting.
|
|
17
|
+
* :func:`resolve_policy` — composes the rewrite with
|
|
18
|
+
:func:`~lattice_brain.graph.fusion.fusion_profile` (the weight table is
|
|
19
|
+
NOT duplicated here) and adds ``recency_half_life_days``, which is
|
|
20
|
+
non-``None`` ONLY for the ``recency`` query class — the honest signal
|
|
21
|
+
that age decay applies exactly where the fusion layers wire it.
|
|
22
|
+
|
|
23
|
+
Both functions are pure, deterministic, and never raise; the ``fact``
|
|
24
|
+
query class resolves to the historical default weights, so fact-class
|
|
25
|
+
behavior stays byte-compatible. Scores are never combined with ``or``
|
|
26
|
+
(score ``0.0`` is falsy but valid).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
from __future__ import annotations
|
|
30
|
+
|
|
31
|
+
import os
|
|
32
|
+
import re
|
|
33
|
+
from typing import Any, Dict, List, Mapping, Optional
|
|
34
|
+
|
|
35
|
+
from .fusion import classify_query, fusion_profile
|
|
36
|
+
|
|
37
|
+
QUERY_REWRITE_ENV = "LATTICEAI_QUERY_REWRITE"
|
|
38
|
+
|
|
39
|
+
# Half-life (days) for the recency-class age decay. Matches the default of
|
|
40
|
+
# lattice_brain.graph._kg_fsutil._recency_score, which the fusion layers use
|
|
41
|
+
# to compute the actual multiplier — this module only declares the policy.
|
|
42
|
+
RECENCY_HALF_LIFE_DAYS = 14.0
|
|
43
|
+
|
|
44
|
+
# A filler strip is applied only when the remaining query keeps at least this
|
|
45
|
+
# many characters — never rewrite a query down to (near-)nothing.
|
|
46
|
+
_MIN_REMAINDER_CHARS = 4
|
|
47
|
+
|
|
48
|
+
_WS_RE = re.compile(r"\s+")
|
|
49
|
+
|
|
50
|
+
# Conservative trailing Korean politeness/filler phrases ("… 좀 알려줘",
|
|
51
|
+
# "… 궁금해", "… 뭐였지"). Anchored at end-of-string, must start the query or
|
|
52
|
+
# follow whitespace so word interiors are never clipped.
|
|
53
|
+
_KO_FILLER_TAIL_RE = re.compile(
|
|
54
|
+
r"(?:^|(?<=\s))(?:좀\s+)?"
|
|
55
|
+
r"(?:알려\s*줘요?|알려\s*주세요|알려\s*줄래요?"
|
|
56
|
+
r"|말해\s*줘요?|말해\s*주세요"
|
|
57
|
+
r"|설명해\s*줘요?|설명해\s*주세요"
|
|
58
|
+
r"|궁금해요?|궁금합니다"
|
|
59
|
+
r"|뭐였지|뭐였더라|뭐더라|뭐지|뭐야"
|
|
60
|
+
r")\s*[?!.…~]*\s*$"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
# Conservative leading English filler ("what is …", "tell me about …",
|
|
64
|
+
# optionally prefixed with "please").
|
|
65
|
+
_EN_FILLER_LEAD_RE = re.compile(
|
|
66
|
+
r"^(?:please\s+)?(?:tell\s+me\s+about|what\s+is|what\s+was|what\s+are|what's)\s+",
|
|
67
|
+
re.IGNORECASE,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
# Conservative trailing English politeness ("…, please?").
|
|
71
|
+
_EN_FILLER_TAIL_RE = re.compile(r"[,\s]*\bplease\b\s*[?!.]*\s*$", re.IGNORECASE)
|
|
72
|
+
|
|
73
|
+
_FILLER_RULES = (
|
|
74
|
+
("strip_filler_ko", _KO_FILLER_TAIL_RE),
|
|
75
|
+
("strip_filler_en_leading", _EN_FILLER_LEAD_RE),
|
|
76
|
+
("strip_filler_en_trailing", _EN_FILLER_TAIL_RE),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _rewrite_enabled() -> bool:
|
|
81
|
+
raw = os.getenv(QUERY_REWRITE_ENV, "").strip().lower()
|
|
82
|
+
return raw not in {"0", "false", "no", "off"}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def rewrite_query(query: Any) -> Dict[str, Any]:
|
|
86
|
+
"""Deterministic rule-based ko/en query normalization (never raises).
|
|
87
|
+
|
|
88
|
+
Returns ``{"original": str, "rewritten": str, "rules": [rule names]}``.
|
|
89
|
+
Only three conservative rules exist: whitespace collapse, trailing
|
|
90
|
+
Korean filler strip, and leading/trailing English filler strip — each
|
|
91
|
+
filler strip applies only when the remainder keeps >= 4 characters.
|
|
92
|
+
Code-class queries (exact identifiers/filenames are the signal) are
|
|
93
|
+
returned unchanged apart from whitespace collapse. The
|
|
94
|
+
``LATTICEAI_QUERY_REWRITE=0`` kill-switch disables rewriting entirely
|
|
95
|
+
(``rewritten == original``). Empty input yields empty output.
|
|
96
|
+
"""
|
|
97
|
+
try:
|
|
98
|
+
text = str(query or "").strip()
|
|
99
|
+
except Exception: # noqa: BLE001 — rewrite must never raise
|
|
100
|
+
return {"original": "", "rewritten": "", "rules": []}
|
|
101
|
+
if not text:
|
|
102
|
+
return {"original": "", "rewritten": "", "rules": []}
|
|
103
|
+
original = text
|
|
104
|
+
if not _rewrite_enabled():
|
|
105
|
+
return {"original": original, "rewritten": original, "rules": []}
|
|
106
|
+
|
|
107
|
+
rules: List[str] = []
|
|
108
|
+
rewritten = _WS_RE.sub(" ", text).strip()
|
|
109
|
+
if rewritten != original:
|
|
110
|
+
rules.append("collapse_whitespace")
|
|
111
|
+
|
|
112
|
+
if classify_query(original) == "code":
|
|
113
|
+
# Exact identifiers/filenames are the retrieval signal — never touch
|
|
114
|
+
# them (whitespace collapse is the only permitted normalization).
|
|
115
|
+
return {"original": original, "rewritten": rewritten, "rules": rules}
|
|
116
|
+
|
|
117
|
+
for name, pattern in _FILLER_RULES:
|
|
118
|
+
candidate = pattern.sub("", rewritten).strip()
|
|
119
|
+
if candidate != rewritten and len(candidate) >= _MIN_REMAINDER_CHARS:
|
|
120
|
+
rewritten = candidate
|
|
121
|
+
rules.append(name)
|
|
122
|
+
return {"original": original, "rewritten": rewritten, "rules": rules}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def resolve_policy(
|
|
126
|
+
query: Any,
|
|
127
|
+
*,
|
|
128
|
+
overrides: Optional[Mapping[str, Mapping[str, float]]] = None,
|
|
129
|
+
) -> Dict[str, Any]:
|
|
130
|
+
"""Resolve the full retrieval policy for ``query`` (never raises).
|
|
131
|
+
|
|
132
|
+
Composes :func:`rewrite_query` with
|
|
133
|
+
:func:`~lattice_brain.graph.fusion.fusion_profile` (classification runs
|
|
134
|
+
on the ORIGINAL query, so ``query_class`` / ``weights`` / ``alpha`` are
|
|
135
|
+
byte-identical to calling ``fusion_profile`` directly, as both hybrid
|
|
136
|
+
layers did before this module). Returns::
|
|
137
|
+
|
|
138
|
+
{
|
|
139
|
+
"query_class": "fact" | "code" | "person" | "recency",
|
|
140
|
+
"weights": {"keyword", "vector", "graph"}, # service fusion
|
|
141
|
+
"alpha": float, # graph-layer fusion
|
|
142
|
+
"original_query": str,
|
|
143
|
+
"search_query": str, # the rewritten form to search with
|
|
144
|
+
"rewrite_rules": [str],
|
|
145
|
+
"recency_half_life_days": float | None, # 14.0 only for recency
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
``recency_half_life_days`` is non-``None`` only for the ``recency``
|
|
149
|
+
class — the honest contract that age decay applies exactly where the
|
|
150
|
+
fusion layers wire it, and nowhere else.
|
|
151
|
+
"""
|
|
152
|
+
rewrite = rewrite_query(query)
|
|
153
|
+
profile = fusion_profile(rewrite["original"], overrides=overrides)
|
|
154
|
+
query_class = profile["query_class"]
|
|
155
|
+
search_query = rewrite["rewritten"] if rewrite["rewritten"] else rewrite["original"]
|
|
156
|
+
return {
|
|
157
|
+
"query_class": query_class,
|
|
158
|
+
"weights": dict(profile["weights"]),
|
|
159
|
+
"alpha": float(profile["alpha"]),
|
|
160
|
+
"original_query": rewrite["original"],
|
|
161
|
+
"search_query": search_query,
|
|
162
|
+
"rewrite_rules": list(rewrite["rules"]),
|
|
163
|
+
"recency_half_life_days": (
|
|
164
|
+
RECENCY_HALF_LIFE_DAYS if query_class == "recency" else None
|
|
165
|
+
),
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
__all__ = [
|
|
170
|
+
"QUERY_REWRITE_ENV",
|
|
171
|
+
"RECENCY_HALF_LIFE_DAYS",
|
|
172
|
+
"resolve_policy",
|
|
173
|
+
"rewrite_query",
|
|
174
|
+
]
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
"""Non-search read surface of the knowledge graph (v9.9.5 decomposition).
|
|
2
|
+
|
|
3
|
+
Byte-identical move-only split out of :mod:`lattice_brain.graph.retrieval`,
|
|
4
|
+
which now keeps the search surface (``search`` / ``hybrid_search`` /
|
|
5
|
+
``context_for_query``). This mixin owns the document listing, workspace
|
|
6
|
+
scoping reads, node/neighbor/relationship lookups, graph traversal, and
|
|
7
|
+
store statistics. Mixins share ``self`` on
|
|
8
|
+
:class:`lattice_brain.graph.store.KnowledgeGraphStore`, so cross-mixin
|
|
9
|
+
calls (e.g. ``search`` → ``filter_scoped_nodes``) behave exactly as before.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
# ruff: noqa: F403,F405
|
|
15
|
+
|
|
16
|
+
from ._kg_common import * # noqa: F403,F401
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class KnowledgeGraphReadsMixin:
|
|
20
|
+
def list_documents(self, limit: int = 200) -> Dict[str, Any]:
|
|
21
|
+
"""List ingested ``Document`` nodes with their ingest + index state.
|
|
22
|
+
|
|
23
|
+
Powers the Files view: every accepted upload and every indexed local
|
|
24
|
+
document becomes a ``Document`` node. A document is reported ``indexed``
|
|
25
|
+
once its retrieval chunks exist (searchable in Chat / Hybrid Search).
|
|
26
|
+
"""
|
|
27
|
+
limit = max(1, min(int(limit or 200), 1000))
|
|
28
|
+
nt, _ = self._read_tables()
|
|
29
|
+
documents: List[Dict[str, Any]] = []
|
|
30
|
+
with self._connect() as conn:
|
|
31
|
+
rows = conn.execute(
|
|
32
|
+
f"SELECT id, title, summary, metadata_json, created_at, updated_at "
|
|
33
|
+
f"FROM {nt} WHERE type='Document' ORDER BY updated_at DESC, id ASC LIMIT ?",
|
|
34
|
+
(limit,),
|
|
35
|
+
).fetchall()
|
|
36
|
+
for row in rows:
|
|
37
|
+
meta = _safe_loads(row["metadata_json"]) or {}
|
|
38
|
+
extracted = meta.get("extracted") or {}
|
|
39
|
+
node_id = row["id"]
|
|
40
|
+
chunk_count = conn.execute(
|
|
41
|
+
"SELECT COUNT(*) AS c FROM chunks WHERE source_node=?",
|
|
42
|
+
(node_id,),
|
|
43
|
+
).fetchone()["c"]
|
|
44
|
+
if not chunk_count:
|
|
45
|
+
# Legacy projections represented chunks as graph nodes and
|
|
46
|
+
# linked them only through metadata_json. Keep read
|
|
47
|
+
# compatibility without making the fragile LIKE path the
|
|
48
|
+
# primary query.
|
|
49
|
+
chunk_count = conn.execute(
|
|
50
|
+
f"SELECT COUNT(*) AS c FROM {nt} WHERE type='Chunk' AND metadata_json LIKE ?",
|
|
51
|
+
(f"%{node_id}%",),
|
|
52
|
+
).fetchone()["c"]
|
|
53
|
+
documents.append(
|
|
54
|
+
{
|
|
55
|
+
"id": node_id,
|
|
56
|
+
"filename": meta.get("filename") or row["title"],
|
|
57
|
+
"ext": meta.get("ext"),
|
|
58
|
+
"mime_type": meta.get("mime_type"),
|
|
59
|
+
"bytes": meta.get("bytes"),
|
|
60
|
+
"sha256": meta.get("sha256"),
|
|
61
|
+
"uploader": meta.get("uploader"),
|
|
62
|
+
"chars": extracted.get("chars"),
|
|
63
|
+
"chunks": int(chunk_count or 0),
|
|
64
|
+
"indexed": int(chunk_count or 0) > 0,
|
|
65
|
+
"ingest_state": "indexed"
|
|
66
|
+
if int(chunk_count or 0) > 0
|
|
67
|
+
else "ingested",
|
|
68
|
+
"created_at": row["created_at"],
|
|
69
|
+
"updated_at": row["updated_at"],
|
|
70
|
+
}
|
|
71
|
+
)
|
|
72
|
+
return {
|
|
73
|
+
"documents": documents,
|
|
74
|
+
"total": len(documents),
|
|
75
|
+
"generated_at": datetime.now().isoformat(timespec="seconds"),
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
def workspaces_of(self, node_ids) -> Dict[str, Optional[str]]:
|
|
79
|
+
"""Map known node ids to their workspace scope.
|
|
80
|
+
|
|
81
|
+
``None`` is returned only for a row that is explicitly present in the
|
|
82
|
+
authoritative v2 projection with a NULL workspace. Missing ids remain
|
|
83
|
+
missing, and projection/query failures propagate so callers can fail
|
|
84
|
+
closed instead of mistaking every candidate for legacy-global data.
|
|
85
|
+
"""
|
|
86
|
+
ids = [str(i) for i in node_ids if i]
|
|
87
|
+
if not ids:
|
|
88
|
+
return {}
|
|
89
|
+
placeholders = ",".join("?" for _ in ids)
|
|
90
|
+
with self._connect() as conn:
|
|
91
|
+
return {
|
|
92
|
+
row["id"]: row["workspace_id"]
|
|
93
|
+
for row in conn.execute(
|
|
94
|
+
f"SELECT id, workspace_id FROM nodes_v2 WHERE id IN ({placeholders})",
|
|
95
|
+
ids,
|
|
96
|
+
).fetchall()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
def filter_scoped_nodes(
|
|
100
|
+
self,
|
|
101
|
+
items,
|
|
102
|
+
allowed_workspaces,
|
|
103
|
+
*,
|
|
104
|
+
id_key: str = "id",
|
|
105
|
+
include_legacy_global: bool = False,
|
|
106
|
+
):
|
|
107
|
+
"""Drop items scoped to a workspace the caller is not a member of.
|
|
108
|
+
|
|
109
|
+
``allowed_workspaces=None`` means no scoping (single-user / no-auth
|
|
110
|
+
mode). In scoped/multi-user mode, unknown ids are private and
|
|
111
|
+
legacy-global rows require the explicit ``include_legacy_global=True``
|
|
112
|
+
compatibility opt-in.
|
|
113
|
+
"""
|
|
114
|
+
candidates = list(items)
|
|
115
|
+
if allowed_workspaces is None:
|
|
116
|
+
return candidates
|
|
117
|
+
allowed = {str(workspace_id) for workspace_id in allowed_workspaces if workspace_id}
|
|
118
|
+
scopes = self.workspaces_of([item.get(id_key) for item in candidates])
|
|
119
|
+
visible = []
|
|
120
|
+
for item in candidates:
|
|
121
|
+
node_id = str(item.get(id_key) or "")
|
|
122
|
+
if not node_id or node_id not in scopes:
|
|
123
|
+
# Unknown/unprojected rows are never treated as public.
|
|
124
|
+
continue
|
|
125
|
+
workspace_id = scopes[node_id]
|
|
126
|
+
if workspace_id is None:
|
|
127
|
+
if include_legacy_global:
|
|
128
|
+
visible.append(item)
|
|
129
|
+
elif str(workspace_id) in allowed:
|
|
130
|
+
visible.append(item)
|
|
131
|
+
return visible
|
|
132
|
+
|
|
133
|
+
def neighbors(
|
|
134
|
+
self,
|
|
135
|
+
node_id: str,
|
|
136
|
+
*,
|
|
137
|
+
allowed_workspaces=None,
|
|
138
|
+
include_legacy_global: bool = False,
|
|
139
|
+
) -> Dict[str, Any]:
|
|
140
|
+
"""Return direct neighbors (1-hop) of a node."""
|
|
141
|
+
if allowed_workspaces is not None and not self.filter_scoped_nodes(
|
|
142
|
+
[{"id": node_id}],
|
|
143
|
+
allowed_workspaces,
|
|
144
|
+
include_legacy_global=include_legacy_global,
|
|
145
|
+
):
|
|
146
|
+
raise ValueError(f"graph node not found: {node_id}")
|
|
147
|
+
nt, et = self._read_tables()
|
|
148
|
+
with self._connect() as conn:
|
|
149
|
+
edge_rows = conn.execute(
|
|
150
|
+
f"SELECT from_node, to_node, type, weight FROM {et} WHERE from_node=? OR to_node=? ORDER BY id ASC",
|
|
151
|
+
(node_id, node_id),
|
|
152
|
+
).fetchall()
|
|
153
|
+
neighbor_ids: set = set()
|
|
154
|
+
edges = []
|
|
155
|
+
for row in edge_rows:
|
|
156
|
+
neighbor_ids.add(row["from_node"])
|
|
157
|
+
neighbor_ids.add(row["to_node"])
|
|
158
|
+
edges.append(
|
|
159
|
+
{
|
|
160
|
+
"from": row["from_node"],
|
|
161
|
+
"to": row["to_node"],
|
|
162
|
+
"type": row["type"],
|
|
163
|
+
"weight": row["weight"],
|
|
164
|
+
}
|
|
165
|
+
)
|
|
166
|
+
neighbor_ids.discard(node_id)
|
|
167
|
+
nodes = []
|
|
168
|
+
if neighbor_ids:
|
|
169
|
+
placeholders = ",".join("?" * len(neighbor_ids))
|
|
170
|
+
nodes = [
|
|
171
|
+
{
|
|
172
|
+
"id": row["id"],
|
|
173
|
+
"type": row["type"],
|
|
174
|
+
"title": row["title"],
|
|
175
|
+
"summary": row["summary"],
|
|
176
|
+
"metadata": _safe_loads(row["metadata_json"]),
|
|
177
|
+
}
|
|
178
|
+
for row in conn.execute(
|
|
179
|
+
f"SELECT id, type, title, summary, metadata_json FROM {nt} WHERE id IN ({placeholders}) ORDER BY id ASC",
|
|
180
|
+
list(neighbor_ids),
|
|
181
|
+
)
|
|
182
|
+
]
|
|
183
|
+
if allowed_workspaces is not None:
|
|
184
|
+
nodes = self.filter_scoped_nodes(
|
|
185
|
+
nodes,
|
|
186
|
+
allowed_workspaces,
|
|
187
|
+
include_legacy_global=include_legacy_global,
|
|
188
|
+
)
|
|
189
|
+
kept = {node.get("id") for node in nodes}
|
|
190
|
+
edges = [
|
|
191
|
+
edge for edge in edges
|
|
192
|
+
if (edge.get("from") == node_id or edge.get("from") in kept)
|
|
193
|
+
and (edge.get("to") == node_id or edge.get("to") in kept)
|
|
194
|
+
]
|
|
195
|
+
return {"node_id": node_id, "neighbors": nodes, "edges": edges}
|
|
196
|
+
|
|
197
|
+
def get_node(
|
|
198
|
+
self,
|
|
199
|
+
node_id: str,
|
|
200
|
+
*,
|
|
201
|
+
allowed_workspaces=None,
|
|
202
|
+
include_legacy_global: bool = False,
|
|
203
|
+
) -> Dict[str, Any]:
|
|
204
|
+
node_id = str(node_id or "").strip()
|
|
205
|
+
if not node_id:
|
|
206
|
+
raise ValueError("node_id required")
|
|
207
|
+
nt, et = self._read_tables()
|
|
208
|
+
with self._connect() as conn:
|
|
209
|
+
row = conn.execute(
|
|
210
|
+
f"""
|
|
211
|
+
SELECT id, type, title, summary, metadata_json, updated_at
|
|
212
|
+
FROM {nt}
|
|
213
|
+
WHERE id=?
|
|
214
|
+
""",
|
|
215
|
+
(node_id,),
|
|
216
|
+
).fetchone()
|
|
217
|
+
if not row:
|
|
218
|
+
raise ValueError(f"graph node not found: {node_id}")
|
|
219
|
+
degree = conn.execute(
|
|
220
|
+
f"SELECT COUNT(*) AS c FROM {et} WHERE from_node=? OR to_node=?",
|
|
221
|
+
(node_id, node_id),
|
|
222
|
+
).fetchone()["c"]
|
|
223
|
+
node = {
|
|
224
|
+
"id": row["id"],
|
|
225
|
+
"type": row["type"],
|
|
226
|
+
"title": row["title"],
|
|
227
|
+
"summary": row["summary"],
|
|
228
|
+
"metadata": _safe_loads(row["metadata_json"]),
|
|
229
|
+
"updated_at": row["updated_at"],
|
|
230
|
+
"degree": degree,
|
|
231
|
+
}
|
|
232
|
+
if allowed_workspaces is not None and not self.filter_scoped_nodes(
|
|
233
|
+
[node],
|
|
234
|
+
allowed_workspaces,
|
|
235
|
+
include_legacy_global=include_legacy_global,
|
|
236
|
+
):
|
|
237
|
+
raise ValueError(f"graph node not found: {node_id}")
|
|
238
|
+
return node
|
|
239
|
+
|
|
240
|
+
def relationship_search(
|
|
241
|
+
self,
|
|
242
|
+
*,
|
|
243
|
+
query: str = "",
|
|
244
|
+
node_id: str = "",
|
|
245
|
+
relationship_type: str = "",
|
|
246
|
+
limit: int = 30,
|
|
247
|
+
allowed_workspaces=None,
|
|
248
|
+
include_legacy_global: bool = False,
|
|
249
|
+
) -> Dict[str, Any]:
|
|
250
|
+
query = str(query or "").strip()
|
|
251
|
+
node_id = str(node_id or "").strip()
|
|
252
|
+
relationship_type = str(relationship_type or "").strip()
|
|
253
|
+
limit = max(1, min(int(limit or 30), 200))
|
|
254
|
+
nt, et = self._read_tables()
|
|
255
|
+
where = []
|
|
256
|
+
params: List[Any] = []
|
|
257
|
+
if node_id:
|
|
258
|
+
where.append("(e.from_node=? OR e.to_node=?)")
|
|
259
|
+
params.extend([node_id, node_id])
|
|
260
|
+
if relationship_type:
|
|
261
|
+
where.append("e.type LIKE ?")
|
|
262
|
+
params.append(f"%{relationship_type}%")
|
|
263
|
+
if query:
|
|
264
|
+
where.append(
|
|
265
|
+
"(e.type LIKE ? OR e.metadata_json LIKE ? OR src.title LIKE ? OR dst.title LIKE ? OR src.summary LIKE ? OR dst.summary LIKE ?)"
|
|
266
|
+
)
|
|
267
|
+
params.extend([f"%{query}%"] * 6)
|
|
268
|
+
where_sql = "WHERE " + " AND ".join(where) if where else ""
|
|
269
|
+
with self._connect() as conn:
|
|
270
|
+
rows = conn.execute(
|
|
271
|
+
f"""
|
|
272
|
+
SELECT
|
|
273
|
+
e.id, e.from_node, e.to_node, e.type, e.weight, e.metadata_json, e.created_at,
|
|
274
|
+
src.type AS source_type, src.title AS source_title, src.summary AS source_summary,
|
|
275
|
+
src.metadata_json AS source_metadata,
|
|
276
|
+
dst.type AS target_type, dst.title AS target_title, dst.summary AS target_summary,
|
|
277
|
+
dst.metadata_json AS target_metadata
|
|
278
|
+
FROM {et} e
|
|
279
|
+
JOIN {nt} src ON src.id=e.from_node
|
|
280
|
+
JOIN {nt} dst ON dst.id=e.to_node
|
|
281
|
+
{where_sql}
|
|
282
|
+
ORDER BY e.weight DESC, e.created_at DESC, e.id ASC
|
|
283
|
+
LIMIT ?
|
|
284
|
+
""",
|
|
285
|
+
(*params, limit),
|
|
286
|
+
).fetchall()
|
|
287
|
+
relationships = [
|
|
288
|
+
{
|
|
289
|
+
"id": row["id"],
|
|
290
|
+
"type": row["type"],
|
|
291
|
+
"weight": row["weight"],
|
|
292
|
+
"metadata": _safe_loads(row["metadata_json"]),
|
|
293
|
+
"created_at": row["created_at"],
|
|
294
|
+
"source": {
|
|
295
|
+
"id": row["from_node"],
|
|
296
|
+
"type": row["source_type"],
|
|
297
|
+
"title": row["source_title"],
|
|
298
|
+
"summary": row["source_summary"],
|
|
299
|
+
"metadata": _safe_loads(row["source_metadata"]),
|
|
300
|
+
},
|
|
301
|
+
"target": {
|
|
302
|
+
"id": row["to_node"],
|
|
303
|
+
"type": row["target_type"],
|
|
304
|
+
"title": row["target_title"],
|
|
305
|
+
"summary": row["target_summary"],
|
|
306
|
+
"metadata": _safe_loads(row["target_metadata"]),
|
|
307
|
+
},
|
|
308
|
+
}
|
|
309
|
+
for row in rows
|
|
310
|
+
]
|
|
311
|
+
if allowed_workspaces is not None:
|
|
312
|
+
kept = []
|
|
313
|
+
for rel in relationships:
|
|
314
|
+
endpoints = [
|
|
315
|
+
{"id": (rel.get("source") or {}).get("id")},
|
|
316
|
+
{"id": (rel.get("target") or {}).get("id")},
|
|
317
|
+
]
|
|
318
|
+
if len(
|
|
319
|
+
self.filter_scoped_nodes(
|
|
320
|
+
endpoints,
|
|
321
|
+
allowed_workspaces,
|
|
322
|
+
include_legacy_global=include_legacy_global,
|
|
323
|
+
)
|
|
324
|
+
) == 2:
|
|
325
|
+
kept.append(rel)
|
|
326
|
+
relationships = kept
|
|
327
|
+
return {
|
|
328
|
+
"query": query,
|
|
329
|
+
"node_id": node_id,
|
|
330
|
+
"relationship_type": relationship_type,
|
|
331
|
+
"relationships": relationships,
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
def traverse(
|
|
335
|
+
self,
|
|
336
|
+
node_id: str,
|
|
337
|
+
*,
|
|
338
|
+
depth: int = 1,
|
|
339
|
+
limit: int = 100,
|
|
340
|
+
allowed_workspaces=None,
|
|
341
|
+
include_legacy_global: bool = False,
|
|
342
|
+
) -> Dict[str, Any]:
|
|
343
|
+
node_id = str(node_id or "").strip()
|
|
344
|
+
if not node_id:
|
|
345
|
+
raise ValueError("node_id required")
|
|
346
|
+
if allowed_workspaces is not None and not self.filter_scoped_nodes(
|
|
347
|
+
[{"id": node_id}],
|
|
348
|
+
allowed_workspaces,
|
|
349
|
+
include_legacy_global=include_legacy_global,
|
|
350
|
+
):
|
|
351
|
+
raise ValueError(f"graph node not found: {node_id}")
|
|
352
|
+
depth = max(0, min(int(depth or 1), 4))
|
|
353
|
+
limit = max(1, min(int(limit or 100), 500))
|
|
354
|
+
nt, et = self._read_tables()
|
|
355
|
+
visited = {node_id}
|
|
356
|
+
frontier = {node_id}
|
|
357
|
+
edges_by_id: Dict[str, Dict[str, Any]] = {}
|
|
358
|
+
with self._connect() as conn:
|
|
359
|
+
for _ in range(depth):
|
|
360
|
+
if not frontier or len(visited) >= limit:
|
|
361
|
+
break
|
|
362
|
+
placeholders = ",".join("?" * len(frontier))
|
|
363
|
+
rows = conn.execute(
|
|
364
|
+
f"""
|
|
365
|
+
SELECT id, from_node, to_node, type, weight, metadata_json
|
|
366
|
+
FROM {et}
|
|
367
|
+
WHERE from_node IN ({placeholders}) OR to_node IN ({placeholders})
|
|
368
|
+
ORDER BY weight DESC, id ASC
|
|
369
|
+
LIMIT ?
|
|
370
|
+
""",
|
|
371
|
+
(*frontier, *frontier, limit * 3),
|
|
372
|
+
).fetchall()
|
|
373
|
+
next_frontier = set()
|
|
374
|
+
for row in rows:
|
|
375
|
+
edges_by_id[row["id"]] = {
|
|
376
|
+
"id": row["id"],
|
|
377
|
+
"from": row["from_node"],
|
|
378
|
+
"to": row["to_node"],
|
|
379
|
+
"type": row["type"],
|
|
380
|
+
"weight": row["weight"],
|
|
381
|
+
"metadata": _safe_loads(row["metadata_json"]),
|
|
382
|
+
}
|
|
383
|
+
for candidate in (row["from_node"], row["to_node"]):
|
|
384
|
+
if candidate not in visited and len(visited) < limit:
|
|
385
|
+
visited.add(candidate)
|
|
386
|
+
next_frontier.add(candidate)
|
|
387
|
+
frontier = next_frontier
|
|
388
|
+
placeholders = ",".join("?" * len(visited))
|
|
389
|
+
node_rows = conn.execute(
|
|
390
|
+
f"""
|
|
391
|
+
SELECT id, type, title, summary, metadata_json, updated_at
|
|
392
|
+
FROM {nt}
|
|
393
|
+
WHERE id IN ({placeholders})
|
|
394
|
+
ORDER BY updated_at DESC, id ASC
|
|
395
|
+
""",
|
|
396
|
+
list(visited),
|
|
397
|
+
).fetchall()
|
|
398
|
+
nodes = [
|
|
399
|
+
{
|
|
400
|
+
"id": row["id"],
|
|
401
|
+
"type": row["type"],
|
|
402
|
+
"title": row["title"],
|
|
403
|
+
"summary": row["summary"],
|
|
404
|
+
"metadata": _safe_loads(row["metadata_json"]),
|
|
405
|
+
"updated_at": row["updated_at"],
|
|
406
|
+
}
|
|
407
|
+
for row in node_rows
|
|
408
|
+
]
|
|
409
|
+
edges = list(edges_by_id.values())
|
|
410
|
+
if allowed_workspaces is not None:
|
|
411
|
+
nodes = self.filter_scoped_nodes(
|
|
412
|
+
nodes,
|
|
413
|
+
allowed_workspaces,
|
|
414
|
+
include_legacy_global=include_legacy_global,
|
|
415
|
+
)
|
|
416
|
+
kept = {node.get("id") for node in nodes}
|
|
417
|
+
edges = [edge for edge in edges if edge.get("from") in kept and edge.get("to") in kept]
|
|
418
|
+
return {"root": node_id, "depth": depth, "nodes": nodes, "edges": edges}
|
|
419
|
+
|
|
420
|
+
def stats(self) -> Dict[str, Any]:
|
|
421
|
+
nt, et = self._read_tables()
|
|
422
|
+
with self._connect() as conn:
|
|
423
|
+
node_counts = {
|
|
424
|
+
row["type"]: row["count"]
|
|
425
|
+
for row in conn.execute(
|
|
426
|
+
f"SELECT type, COUNT(*) AS count FROM {nt} GROUP BY type"
|
|
427
|
+
)
|
|
428
|
+
}
|
|
429
|
+
edge_counts = {
|
|
430
|
+
row["type"]: row["count"]
|
|
431
|
+
for row in conn.execute(
|
|
432
|
+
f"SELECT type, COUNT(*) AS count FROM {et} GROUP BY type"
|
|
433
|
+
)
|
|
434
|
+
}
|
|
435
|
+
local_sources = conn.execute(
|
|
436
|
+
"SELECT COUNT(*) AS c FROM knowledge_sources"
|
|
437
|
+
).fetchone()["c"]
|
|
438
|
+
local_file_status = {
|
|
439
|
+
row["status"]: row["count"]
|
|
440
|
+
for row in conn.execute(
|
|
441
|
+
"SELECT status, COUNT(*) AS count FROM local_file_index GROUP BY status"
|
|
442
|
+
)
|
|
443
|
+
}
|
|
444
|
+
v2 = None
|
|
445
|
+
if KGStoreV2 is not None:
|
|
446
|
+
try:
|
|
447
|
+
v2 = KGStoreV2(self.db_path).stats()
|
|
448
|
+
except Exception as e:
|
|
449
|
+
v2 = {"available": False, "error": str(e)}
|
|
450
|
+
return {
|
|
451
|
+
"db_path": str(self.db_path),
|
|
452
|
+
"schema_version": GRAPH_SCHEMA_VERSION,
|
|
453
|
+
"v2_schema_available": KGStoreV2 is not None,
|
|
454
|
+
"nodes": node_counts,
|
|
455
|
+
"edges": edge_counts,
|
|
456
|
+
"local_sources": local_sources,
|
|
457
|
+
"local_file_status": local_file_status,
|
|
458
|
+
"v2": v2,
|
|
459
|
+
}
|