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,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
|
+
}
|
|
@@ -657,6 +657,7 @@ class KnowledgeGraphVectorMixin:
|
|
|
657
657
|
n.type AS node_type, n.title AS node_title, n.summary AS node_summary,
|
|
658
658
|
n.metadata_json AS node_metadata, n.updated_at AS node_updated_at,
|
|
659
659
|
c.text AS chunk_text, c.source_node AS parent_node_id,
|
|
660
|
+
c.metadata_json AS chunk_metadata,
|
|
660
661
|
pn.type AS parent_type, pn.title AS parent_title,
|
|
661
662
|
pn.summary AS parent_summary, pn.metadata_json AS parent_metadata,
|
|
662
663
|
pn.updated_at AS parent_updated_at
|
|
@@ -690,6 +691,13 @@ class KnowledgeGraphVectorMixin:
|
|
|
690
691
|
)
|
|
691
692
|
parent_metadata = _safe_loads(row["parent_metadata"])
|
|
692
693
|
node_metadata = _safe_loads(row["node_metadata"])
|
|
694
|
+
# Citation precision (review 2026-07-27 P1 #4): a chunk hit used to
|
|
695
|
+
# cite only its parent document, so a 200-page PDF answered with
|
|
696
|
+
# "from report.pdf". The chunk's own provenance (section heading,
|
|
697
|
+
# page, offset) now rides along, and `locator` is the one-line
|
|
698
|
+
# human form — absent when the chunk carries no such metadata.
|
|
699
|
+
chunk_metadata = _safe_loads(row["chunk_metadata"]) if is_chunk else {}
|
|
700
|
+
locator = citation_locator(chunk_metadata)
|
|
693
701
|
scored.append(
|
|
694
702
|
{
|
|
695
703
|
"id": row["item_id"],
|
|
@@ -708,6 +716,8 @@ class KnowledgeGraphVectorMixin:
|
|
|
708
716
|
"vector": _safe_loads(row["vector_metadata"]),
|
|
709
717
|
"parent_node_id": row["parent_node_id"],
|
|
710
718
|
"parent_type": row["parent_type"],
|
|
719
|
+
**({"chunk": chunk_metadata} if chunk_metadata else {}),
|
|
720
|
+
**({"locator": locator} if locator else {}),
|
|
711
721
|
},
|
|
712
722
|
"updated_at": row["parent_updated_at"]
|
|
713
723
|
if is_chunk and row["parent_updated_at"]
|
|
@@ -11,6 +11,7 @@ from .projection import KnowledgeGraphProjectionMixin
|
|
|
11
11
|
from .provenance import KnowledgeGraphProvenanceMixin
|
|
12
12
|
from .retrieval import KnowledgeGraphRetrievalMixin
|
|
13
13
|
from .retrieval_docgen import KnowledgeGraphDocGenMixin
|
|
14
|
+
from .retrieval_reads import KnowledgeGraphReadsMixin
|
|
14
15
|
from .retrieval_vector import KnowledgeGraphVectorMixin
|
|
15
16
|
from .write_master import KnowledgeGraphWriteMixin
|
|
16
17
|
|
|
@@ -24,6 +25,7 @@ class KnowledgeGraphStore(
|
|
|
24
25
|
KnowledgeGraphProvenanceMixin,
|
|
25
26
|
KnowledgeGraphDocumentsMixin,
|
|
26
27
|
KnowledgeGraphRetrievalMixin,
|
|
28
|
+
KnowledgeGraphReadsMixin,
|
|
27
29
|
KnowledgeGraphVectorMixin,
|
|
28
30
|
KnowledgeGraphDocGenMixin,
|
|
29
31
|
):
|
|
@@ -42,10 +42,9 @@ from __future__ import annotations
|
|
|
42
42
|
import fnmatch
|
|
43
43
|
import hashlib
|
|
44
44
|
import os
|
|
45
|
-
import threading
|
|
46
45
|
from dataclasses import dataclass, field
|
|
47
46
|
from pathlib import Path
|
|
48
|
-
from typing import Any, Dict, Iterable, List, Optional,
|
|
47
|
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
|
49
48
|
|
|
50
49
|
from .runtime.hooks import dispatch_tool
|
|
51
50
|
from .utils import utc_now_iso
|
|
@@ -353,110 +352,14 @@ def _matches_ignore(
|
|
|
353
352
|
return False
|
|
354
353
|
|
|
355
354
|
|
|
356
|
-
#
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
``done_indices`` tracks per-item completion so an interrupted or partially
|
|
365
|
-
failed job can be *resumed* from the remaining items instead of restarting.
|
|
366
|
-
``errors`` is capped at ``max_errors`` records; ``failed`` keeps counting.
|
|
367
|
-
"""
|
|
368
|
-
job_id: str
|
|
369
|
-
items: List[IngestionItem]
|
|
370
|
-
status: str = "queued" # queued | running | completed | failed | partial
|
|
371
|
-
created_at: str = field(default_factory=utc_now_iso)
|
|
372
|
-
updated_at: str = field(default_factory=utc_now_iso)
|
|
373
|
-
processed: int = 0
|
|
374
|
-
failed: int = 0
|
|
375
|
-
total: int = 0
|
|
376
|
-
errors: List[Dict[str, Any]] = field(default_factory=list)
|
|
377
|
-
incremental: bool = True
|
|
378
|
-
user_email: Optional[str] = None
|
|
379
|
-
max_errors: int = JOB_ERRORS_CAP
|
|
380
|
-
done_indices: Set[int] = field(default_factory=set)
|
|
381
|
-
|
|
382
|
-
def touch(self) -> None:
|
|
383
|
-
self.updated_at = utc_now_iso()
|
|
384
|
-
|
|
385
|
-
def record_error(self, index: int, item: IngestionItem, detail: Any) -> None:
|
|
386
|
-
self.failed += 1
|
|
387
|
-
if len(self.errors) < self.max_errors:
|
|
388
|
-
self.errors.append({
|
|
389
|
-
"index": index,
|
|
390
|
-
"source": item.source_uri or item.path or item.title or item.source_type,
|
|
391
|
-
"detail": str(detail)[:500],
|
|
392
|
-
})
|
|
393
|
-
|
|
394
|
-
def remaining_indices(self) -> List[int]:
|
|
395
|
-
return [i for i in range(len(self.items)) if i not in self.done_indices]
|
|
396
|
-
|
|
397
|
-
def as_dict(self) -> Dict[str, Any]:
|
|
398
|
-
"""Frozen job schema consumed by ``/api/ingestion/jobs*``."""
|
|
399
|
-
return {
|
|
400
|
-
"job_id": self.job_id,
|
|
401
|
-
"status": self.status,
|
|
402
|
-
"total": self.total,
|
|
403
|
-
"processed": self.processed,
|
|
404
|
-
"failed": self.failed,
|
|
405
|
-
"errors": list(self.errors),
|
|
406
|
-
"created_at": self.created_at,
|
|
407
|
-
"updated_at": self.updated_at,
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
class BackgroundIngestionQueue:
|
|
412
|
-
"""Simple in-memory queue for background incremental ingestion.
|
|
413
|
-
|
|
414
|
-
For large corpus: this is the seam where a real scheduler / worker pool
|
|
415
|
-
(celery, rq, or internal thread) can be plugged later without changing callers.
|
|
416
|
-
Supports incremental (skip duplicates) vs force reindex.
|
|
417
|
-
"""
|
|
418
|
-
def __init__(self) -> None:
|
|
419
|
-
self._jobs: Dict[str, BackgroundIngestionJob] = {}
|
|
420
|
-
self._counter = 0
|
|
421
|
-
self._lock = threading.Lock()
|
|
422
|
-
|
|
423
|
-
def schedule(
|
|
424
|
-
self,
|
|
425
|
-
items: List[IngestionItem],
|
|
426
|
-
*,
|
|
427
|
-
incremental: bool = True,
|
|
428
|
-
user_email: Optional[str] = None,
|
|
429
|
-
) -> BackgroundIngestionJob:
|
|
430
|
-
with self._lock:
|
|
431
|
-
self._counter += 1
|
|
432
|
-
job_id = f"bg_ingest_{self._counter:04d}"
|
|
433
|
-
job = BackgroundIngestionJob(
|
|
434
|
-
job_id=job_id,
|
|
435
|
-
items=items,
|
|
436
|
-
total=len(items),
|
|
437
|
-
incremental=incremental,
|
|
438
|
-
user_email=user_email,
|
|
439
|
-
)
|
|
440
|
-
# annotate items for downstream
|
|
441
|
-
for it in job.items:
|
|
442
|
-
# attach flag without breaking dataclass defaults (use metadata)
|
|
443
|
-
it.metadata = {**it.metadata, "incremental": incremental, "bg_job": job_id}
|
|
444
|
-
with self._lock:
|
|
445
|
-
self._jobs[job_id] = job
|
|
446
|
-
return job
|
|
447
|
-
|
|
448
|
-
def get(self, job_id: str) -> Optional[BackgroundIngestionJob]:
|
|
449
|
-
return self._jobs.get(job_id)
|
|
450
|
-
|
|
451
|
-
def list_pending(self) -> List[BackgroundIngestionJob]:
|
|
452
|
-
return [j for j in self._jobs.values() if j.status == "queued"]
|
|
453
|
-
|
|
454
|
-
def list_recent(self, limit: int = 20) -> List[BackgroundIngestionJob]:
|
|
455
|
-
"""Most recent jobs first (insertion order is schedule order)."""
|
|
456
|
-
limit = max(1, int(limit))
|
|
457
|
-
with self._lock:
|
|
458
|
-
jobs = list(self._jobs.values())
|
|
459
|
-
return list(reversed(jobs))[:limit]
|
|
355
|
+
# Background job scheduling + progress lives in its own module (v9.9.6):
|
|
356
|
+
# the pipeline owns "ingest one item", the queue owns "schedule many and
|
|
357
|
+
# report progress". Re-exported so every existing import keeps working.
|
|
358
|
+
from .ingestion_jobs import ( # noqa: E402,F401 — re-export for existing importers
|
|
359
|
+
JOB_ERRORS_CAP,
|
|
360
|
+
BackgroundIngestionJob,
|
|
361
|
+
BackgroundIngestionQueue,
|
|
362
|
+
)
|
|
460
363
|
|
|
461
364
|
|
|
462
365
|
@dataclass
|