ltcai 9.6.0 → 9.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +98 -306
- package/auto_setup.py +11 -1
- package/docs/CHANGELOG.md +91 -0
- package/docs/COMMUNITY_AND_PLUGINS.md +1 -1
- package/docs/DEVELOPMENT.md +1 -1
- package/docs/ONBOARDING.md +1 -1
- package/docs/PERFORMANCE.md +106 -0
- package/docs/TRUST_MODEL.md +1 -1
- package/docs/WHY_LATTICE.md +1 -1
- package/docs/kg-schema.md +1 -1
- package/kg_schema.py +11 -1
- package/knowledge_graph.py +12 -2
- package/knowledge_graph_api.py +11 -1
- package/lattice_brain/__init__.py +1 -1
- package/lattice_brain/graph/proactive.py +583 -0
- package/lattice_brain/graph/retrieval.py +301 -8
- package/lattice_brain/graph/retrieval_vector.py +145 -0
- package/lattice_brain/ingestion.py +757 -16
- package/lattice_brain/quality.py +44 -9
- package/lattice_brain/runtime/multi_agent.py +38 -2
- package/latticeai/__init__.py +1 -1
- package/latticeai/api/brain_intelligence.py +39 -2
- package/latticeai/api/change_proposals.py +32 -3
- package/latticeai/api/chat.py +17 -0
- package/latticeai/api/chat_helpers.py +48 -0
- package/latticeai/api/chat_stream.py +9 -1
- package/latticeai/api/local_files.py +120 -2
- package/latticeai/api/review_queue.py +66 -2
- package/latticeai/app_factory.py +3 -0
- package/latticeai/core/agent.py +193 -135
- package/latticeai/core/agent_eval.py +278 -4
- package/latticeai/core/legacy_compatibility.py +15 -1
- package/latticeai/core/marketplace.py +1 -1
- package/latticeai/core/workspace_os.py +1 -1
- package/latticeai/runtime/router_registration.py +2 -0
- package/latticeai/services/architecture_readiness.py +1 -1
- package/latticeai/services/automation_intelligence.py +151 -14
- package/latticeai/services/brain_intelligence.py +169 -1
- package/latticeai/services/change_proposals.py +56 -4
- package/latticeai/services/product_readiness.py +1 -1
- package/latticeai/services/review_queue.py +43 -2
- package/llm_router.py +10 -1
- package/local_knowledge_api.py +10 -1
- package/ltcai_cli.py +11 -1
- package/mcp_registry.py +10 -1
- package/p_reinforce.py +10 -1
- package/package.json +1 -1
- package/scripts/brain_quality_eval.py +1 -1
- package/scripts/check_current_release_docs.mjs +1 -1
- package/scripts/profile_kg.py +360 -0
- package/setup_wizard.py +10 -1
- 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 +11 -11
- package/static/app/assets/{Act-BkOEmwBi.js → Act-Dd3z8AzF.js} +2 -1
- package/static/app/assets/Brain-BMkgdWnI.js +321 -0
- package/static/app/assets/Capture-D2Aw9gkv.js +1 -0
- package/static/app/assets/Library-Yreq-KW5.js +1 -0
- package/static/app/assets/System-CXNmmtEo.js +1 -0
- package/static/app/assets/{index-85wQvEie.css → index-7gY9t9Sd.css} +1 -1
- package/static/app/assets/index-CndfILiF.js +18 -0
- package/static/app/assets/primitives-DxsIXb6G.js +1 -0
- package/static/app/assets/textarea-DH7ne8VI.js +1 -0
- package/static/app/index.html +2 -2
- package/static/sw.js +1 -1
- package/static/app/assets/Brain-C9ITUsQ_.js +0 -321
- package/static/app/assets/Capture-C-ppTeud.js +0 -1
- package/static/app/assets/Library-CGQbgWTu.js +0 -1
- package/static/app/assets/System-djmj0n2_.js +0 -1
- package/static/app/assets/index-AF0-4XVv.js +0 -18
- package/static/app/assets/primitives-jbb2qv4Q.js +0 -1
- package/static/app/assets/textarea-CFoo0OxJ.js +0 -1
|
@@ -0,0 +1,583 @@
|
|
|
1
|
+
"""Graph-layer Proactive Brain intelligence (v9.6.x).
|
|
2
|
+
|
|
3
|
+
Moves the "Proactive Brain Intelligence" operations (duplicate discovery,
|
|
4
|
+
contradiction detection, quality reporting, consolidation planning) down into
|
|
5
|
+
the graph layer, operating directly on a :class:`KnowledgeGraphStore` through
|
|
6
|
+
its *public read APIs* only (``graph(limit, allowed_workspaces=...)``).
|
|
7
|
+
|
|
8
|
+
Design contracts
|
|
9
|
+
----------------
|
|
10
|
+
* **Read-only by default.** Every method is a pure read over the store sample.
|
|
11
|
+
``consolidate_duplicates`` produces a merge *plan*; it mutates the store only
|
|
12
|
+
when ``dry_run=False`` **and** the store exposes a safe ``merge_nodes``
|
|
13
|
+
primitive (the current store does not — the plan is returned for review /
|
|
14
|
+
proposal-first governance instead; no raw SQL is ever issued from here).
|
|
15
|
+
* **Workspace scoped.** ``workspace_id`` is forwarded as
|
|
16
|
+
``allowed_workspaces={workspace_id}`` so multi-user scoping rules of the
|
|
17
|
+
store apply unchanged. ``workspace_id=None`` means unscoped (single-user).
|
|
18
|
+
* **Shared dedupe semantics.** Duplicate keys and token signatures reuse
|
|
19
|
+
:func:`lattice_brain.quality.dedupe_key` / ``content_signature`` — the exact
|
|
20
|
+
logic ``MemoryQualityManager.dedupe`` applies to memories — so memory-level
|
|
21
|
+
and graph-level dedupe agree by construction.
|
|
22
|
+
* **Edge-dict pitfall.** The store emits edges with ``from``/``to`` keys.
|
|
23
|
+
They are normalized once to ``source``/``target`` here. Scores/weights of
|
|
24
|
+
``0`` are meaningful — no ``or`` defaults on numeric fields.
|
|
25
|
+
|
|
26
|
+
``gate_ingest_candidate`` is a pure function seam for the ingestion pipeline
|
|
27
|
+
(owned elsewhere): it scores new content against existing graph content and
|
|
28
|
+
recommends ``ingest`` / ``skip_duplicate`` / ``review`` without side effects.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import logging
|
|
34
|
+
from datetime import datetime, timedelta, timezone
|
|
35
|
+
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
|
|
36
|
+
|
|
37
|
+
from lattice_brain.quality import (
|
|
38
|
+
GraphEdgeQualityManager,
|
|
39
|
+
MemoryQualityManager,
|
|
40
|
+
content_signature,
|
|
41
|
+
dedupe_key,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
logger = logging.getLogger(__name__)
|
|
45
|
+
|
|
46
|
+
_DEFAULT_SAMPLE_LIMIT = 800
|
|
47
|
+
_DEFAULT_CONTRADICTION_NODES = 300
|
|
48
|
+
_DEFAULT_NEAR_THRESHOLD = 0.75
|
|
49
|
+
_DEFAULT_MAX_PAIRS = 200
|
|
50
|
+
_DEFAULT_STALE_DAYS = 90 # mirrors MemoryQualityManager.apply_retention
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _parse_ts(value: Any) -> Optional[datetime]:
|
|
54
|
+
text = str(value or "").strip()
|
|
55
|
+
if not text:
|
|
56
|
+
return None
|
|
57
|
+
try:
|
|
58
|
+
parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))
|
|
59
|
+
except ValueError:
|
|
60
|
+
return None
|
|
61
|
+
if parsed.tzinfo is None:
|
|
62
|
+
parsed = parsed.replace(tzinfo=timezone.utc)
|
|
63
|
+
return parsed
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _jaccard(left: Set[str], right: Set[str]) -> float:
|
|
67
|
+
if not left or not right:
|
|
68
|
+
return 0.0
|
|
69
|
+
union = len(left | right)
|
|
70
|
+
if union == 0:
|
|
71
|
+
return 0.0
|
|
72
|
+
return len(left & right) / union
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _node_text(node: Dict[str, Any]) -> str:
|
|
76
|
+
title = str(node.get("title") or "").strip()
|
|
77
|
+
summary = str(node.get("summary") or "").strip()
|
|
78
|
+
return f"{title} {summary}".strip()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _slim(node: Dict[str, Any]) -> Dict[str, Any]:
|
|
82
|
+
return {
|
|
83
|
+
"id": node.get("id"),
|
|
84
|
+
"type": node.get("type"),
|
|
85
|
+
"title": str(node.get("title") or "")[:120],
|
|
86
|
+
"updated_at": node.get("updated_at"),
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class ProactiveBrain:
|
|
91
|
+
"""Proactive quality operations over a KnowledgeGraphStore sample.
|
|
92
|
+
|
|
93
|
+
``store`` only needs the public read API
|
|
94
|
+
``graph(limit, *, allowed_workspaces=None)`` (as implemented by
|
|
95
|
+
:class:`~lattice_brain.graph.store.KnowledgeGraphStore`); optional write
|
|
96
|
+
support is discovered via a ``merge_nodes`` attribute, never assumed.
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
def __init__(self, store: Any, *, sample_limit: int = _DEFAULT_SAMPLE_LIMIT):
|
|
100
|
+
if store is None:
|
|
101
|
+
raise ValueError("ProactiveBrain requires a graph store instance")
|
|
102
|
+
self._store = store
|
|
103
|
+
self._sample_limit = max(1, int(sample_limit))
|
|
104
|
+
self._memory_quality = MemoryQualityManager()
|
|
105
|
+
self._edge_quality = GraphEdgeQualityManager()
|
|
106
|
+
|
|
107
|
+
# ── sampling ─────────────────────────────────────────────────────────
|
|
108
|
+
|
|
109
|
+
def _sample(
|
|
110
|
+
self, *, workspace_id: Optional[str] = None, limit: Optional[int] = None
|
|
111
|
+
) -> Dict[str, List[Dict[str, Any]]]:
|
|
112
|
+
kwargs: Dict[str, Any] = {}
|
|
113
|
+
if workspace_id is not None:
|
|
114
|
+
kwargs["allowed_workspaces"] = {workspace_id}
|
|
115
|
+
data = self._store.graph(int(limit or self._sample_limit), **kwargs)
|
|
116
|
+
nodes = [dict(n) for n in (data.get("nodes") or [])]
|
|
117
|
+
edges: List[Dict[str, Any]] = []
|
|
118
|
+
for edge in data.get("edges") or []:
|
|
119
|
+
normalized = dict(edge)
|
|
120
|
+
# Store emits "from"/"to" (older projections: from_node/to_node).
|
|
121
|
+
if normalized.get("source") is None:
|
|
122
|
+
normalized["source"] = (
|
|
123
|
+
edge.get("from") if edge.get("from") is not None else edge.get("from_node")
|
|
124
|
+
)
|
|
125
|
+
if normalized.get("target") is None:
|
|
126
|
+
normalized["target"] = (
|
|
127
|
+
edge.get("to") if edge.get("to") is not None else edge.get("to_node")
|
|
128
|
+
)
|
|
129
|
+
edges.append(normalized)
|
|
130
|
+
return {"nodes": nodes, "edges": edges}
|
|
131
|
+
|
|
132
|
+
# ── duplicates ───────────────────────────────────────────────────────
|
|
133
|
+
|
|
134
|
+
def find_duplicates(
|
|
135
|
+
self,
|
|
136
|
+
*,
|
|
137
|
+
workspace_id: Optional[str] = None,
|
|
138
|
+
limit: Optional[int] = None,
|
|
139
|
+
near_threshold: float = _DEFAULT_NEAR_THRESHOLD,
|
|
140
|
+
max_pairs: int = _DEFAULT_MAX_PAIRS,
|
|
141
|
+
) -> Dict[str, Any]:
|
|
142
|
+
"""Candidate duplicate nodes: exact signature groups + near pairs."""
|
|
143
|
+
sample = self._sample(workspace_id=workspace_id, limit=limit)
|
|
144
|
+
return self._find_duplicates_in(
|
|
145
|
+
sample["nodes"], near_threshold=near_threshold, max_pairs=max_pairs
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
def _find_duplicates_in(
|
|
149
|
+
self,
|
|
150
|
+
nodes: List[Dict[str, Any]],
|
|
151
|
+
*,
|
|
152
|
+
near_threshold: float = _DEFAULT_NEAR_THRESHOLD,
|
|
153
|
+
max_pairs: int = _DEFAULT_MAX_PAIRS,
|
|
154
|
+
) -> Dict[str, Any]:
|
|
155
|
+
by_key: Dict[str, List[Dict[str, Any]]] = {}
|
|
156
|
+
signatures: List[Tuple[Dict[str, Any], Set[str]]] = []
|
|
157
|
+
for node in nodes:
|
|
158
|
+
text = _node_text(node)
|
|
159
|
+
if len(text) < 3:
|
|
160
|
+
continue
|
|
161
|
+
by_key.setdefault(dedupe_key(text), []).append(node)
|
|
162
|
+
signatures.append((node, content_signature(text)))
|
|
163
|
+
|
|
164
|
+
exact_groups = []
|
|
165
|
+
exact_ids: Set[str] = set()
|
|
166
|
+
grouped_together: Set[Tuple[str, str]] = set()
|
|
167
|
+
for key, members in by_key.items():
|
|
168
|
+
if len(members) < 2:
|
|
169
|
+
continue
|
|
170
|
+
ids = [str(m.get("id")) for m in members]
|
|
171
|
+
exact_groups.append(
|
|
172
|
+
{
|
|
173
|
+
"signature": key,
|
|
174
|
+
"count": len(members),
|
|
175
|
+
"node_ids": ids,
|
|
176
|
+
"nodes": [_slim(m) for m in members],
|
|
177
|
+
}
|
|
178
|
+
)
|
|
179
|
+
exact_ids.update(ids[1:])
|
|
180
|
+
for i, left in enumerate(ids):
|
|
181
|
+
for right in ids[i + 1:]:
|
|
182
|
+
grouped_together.add((min(left, right), max(left, right)))
|
|
183
|
+
|
|
184
|
+
# Near-duplicate pairs via token-signature blocking (co-occurrence >= 3
|
|
185
|
+
# shared tokens) to avoid a full O(n^2) scan on large samples.
|
|
186
|
+
token_index: Dict[str, List[int]] = {}
|
|
187
|
+
for idx, (_node, sig) in enumerate(signatures):
|
|
188
|
+
for token in sig:
|
|
189
|
+
token_index.setdefault(token, []).append(idx)
|
|
190
|
+
cooccur: Dict[Tuple[int, int], int] = {}
|
|
191
|
+
for indices in token_index.values():
|
|
192
|
+
if len(indices) < 2 or len(indices) > 50: # skip too-common tokens
|
|
193
|
+
continue
|
|
194
|
+
for i, left in enumerate(indices):
|
|
195
|
+
for right in indices[i + 1:]:
|
|
196
|
+
cooccur[(left, right)] = cooccur.get((left, right), 0) + 1
|
|
197
|
+
|
|
198
|
+
near_pairs = []
|
|
199
|
+
for (li, ri), shared in sorted(cooccur.items(), key=lambda kv: -kv[1]):
|
|
200
|
+
if shared < 3:
|
|
201
|
+
continue
|
|
202
|
+
left_node, left_sig = signatures[li]
|
|
203
|
+
right_node, right_sig = signatures[ri]
|
|
204
|
+
pair_key = (
|
|
205
|
+
min(str(left_node.get("id")), str(right_node.get("id"))),
|
|
206
|
+
max(str(left_node.get("id")), str(right_node.get("id"))),
|
|
207
|
+
)
|
|
208
|
+
if pair_key in grouped_together:
|
|
209
|
+
continue # already reported as exact duplicates
|
|
210
|
+
similarity = _jaccard(left_sig, right_sig)
|
|
211
|
+
if similarity < near_threshold:
|
|
212
|
+
continue
|
|
213
|
+
near_pairs.append(
|
|
214
|
+
{
|
|
215
|
+
"left": _slim(left_node),
|
|
216
|
+
"right": _slim(right_node),
|
|
217
|
+
"similarity": round(similarity, 4),
|
|
218
|
+
}
|
|
219
|
+
)
|
|
220
|
+
if len(near_pairs) >= max_pairs:
|
|
221
|
+
break
|
|
222
|
+
near_pairs.sort(key=lambda p: p["similarity"], reverse=True)
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
"nodes_scanned": len(nodes),
|
|
226
|
+
"exact_groups": exact_groups,
|
|
227
|
+
"exact_duplicate_nodes": len(exact_ids),
|
|
228
|
+
"near_pairs": near_pairs,
|
|
229
|
+
"near_threshold": near_threshold,
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
# ── contradictions ───────────────────────────────────────────────────
|
|
233
|
+
|
|
234
|
+
def detect_contradictions(
|
|
235
|
+
self,
|
|
236
|
+
*,
|
|
237
|
+
workspace_id: Optional[str] = None,
|
|
238
|
+
limit: Optional[int] = None,
|
|
239
|
+
max_nodes: int = _DEFAULT_CONTRADICTION_NODES,
|
|
240
|
+
) -> Dict[str, Any]:
|
|
241
|
+
"""Contradiction signals over graph node contents + CONTRADICTS edges."""
|
|
242
|
+
sample = self._sample(workspace_id=workspace_id, limit=limit)
|
|
243
|
+
return self._detect_contradictions_in(
|
|
244
|
+
sample["nodes"], sample["edges"], max_nodes=max_nodes
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
def _detect_contradictions_in(
|
|
248
|
+
self,
|
|
249
|
+
nodes: List[Dict[str, Any]],
|
|
250
|
+
edges: List[Dict[str, Any]],
|
|
251
|
+
*,
|
|
252
|
+
max_nodes: int = _DEFAULT_CONTRADICTION_NODES,
|
|
253
|
+
) -> Dict[str, Any]:
|
|
254
|
+
rows = []
|
|
255
|
+
for i, node in enumerate(nodes[: max(1, int(max_nodes))]):
|
|
256
|
+
text = _node_text(node)
|
|
257
|
+
if not text:
|
|
258
|
+
continue
|
|
259
|
+
rows.append(
|
|
260
|
+
{
|
|
261
|
+
"id": str(node.get("id") or f"node-{i}"),
|
|
262
|
+
"content": text,
|
|
263
|
+
"score": 0.6,
|
|
264
|
+
"source": "graph",
|
|
265
|
+
"timestamp": node.get("updated_at") or 0,
|
|
266
|
+
}
|
|
267
|
+
)
|
|
268
|
+
by_id = {row["id"]: row for row in rows}
|
|
269
|
+
|
|
270
|
+
node_pairs: List[Dict[str, Any]] = []
|
|
271
|
+
candidates = self._memory_quality.extract_candidates(rows)
|
|
272
|
+
for candidate in self._memory_quality.detect_conflicts(candidates):
|
|
273
|
+
for marker in candidate.conflicts:
|
|
274
|
+
if not marker.startswith("conflict:contradicts:"):
|
|
275
|
+
continue
|
|
276
|
+
other_id = marker.rsplit(":", 1)[-1]
|
|
277
|
+
if any(
|
|
278
|
+
{p["left_id"], p["right_id"]} == {candidate.id, other_id}
|
|
279
|
+
for p in node_pairs
|
|
280
|
+
):
|
|
281
|
+
continue
|
|
282
|
+
other = by_id.get(other_id) or {}
|
|
283
|
+
node_pairs.append(
|
|
284
|
+
{
|
|
285
|
+
"left_id": candidate.id,
|
|
286
|
+
"left_content": candidate.content[:200],
|
|
287
|
+
"right_id": other_id,
|
|
288
|
+
"right_content": str(other.get("content") or "")[:200],
|
|
289
|
+
"signal": "preference_negation",
|
|
290
|
+
}
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
temporal = [
|
|
294
|
+
{
|
|
295
|
+
"id": item.get("id"),
|
|
296
|
+
"content": str(item.get("content") or "")[:200],
|
|
297
|
+
"signal": item.get("proactive_flag"),
|
|
298
|
+
}
|
|
299
|
+
for item in self._memory_quality.detect_temporal_contradictions(rows)
|
|
300
|
+
]
|
|
301
|
+
|
|
302
|
+
contradiction_edges = [
|
|
303
|
+
{
|
|
304
|
+
"id": edge.get("id"),
|
|
305
|
+
"source": edge.get("source"),
|
|
306
|
+
"target": edge.get("target"),
|
|
307
|
+
"type": edge.get("type"),
|
|
308
|
+
"signal": "contradicts_edge",
|
|
309
|
+
}
|
|
310
|
+
for edge in edges
|
|
311
|
+
if "CONTRADICT" in str(edge.get("type") or "").upper()
|
|
312
|
+
]
|
|
313
|
+
|
|
314
|
+
return {
|
|
315
|
+
"nodes_scanned": len(rows),
|
|
316
|
+
"node_pairs": node_pairs,
|
|
317
|
+
"temporal": temporal,
|
|
318
|
+
"contradiction_edges": contradiction_edges,
|
|
319
|
+
"count": len(node_pairs) + len(temporal) + len(contradiction_edges),
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
# ── quality report ───────────────────────────────────────────────────
|
|
323
|
+
|
|
324
|
+
def quality_report(
|
|
325
|
+
self,
|
|
326
|
+
*,
|
|
327
|
+
workspace_id: Optional[str] = None,
|
|
328
|
+
limit: Optional[int] = None,
|
|
329
|
+
max_age_days: int = _DEFAULT_STALE_DAYS,
|
|
330
|
+
near_threshold: float = _DEFAULT_NEAR_THRESHOLD,
|
|
331
|
+
) -> Dict[str, Any]:
|
|
332
|
+
"""Combined JSON-safe report: duplicates, contradictions, stale nodes,
|
|
333
|
+
edge quality. One graph sample feeds every section."""
|
|
334
|
+
sample = self._sample(workspace_id=workspace_id, limit=limit)
|
|
335
|
+
nodes, edges = sample["nodes"], sample["edges"]
|
|
336
|
+
|
|
337
|
+
duplicates = self._find_duplicates_in(nodes, near_threshold=near_threshold)
|
|
338
|
+
contradictions = self._detect_contradictions_in(nodes, edges)
|
|
339
|
+
|
|
340
|
+
# Stale nodes — apply_retention semantics (age > max_age_days).
|
|
341
|
+
cutoff = datetime.now(timezone.utc) - timedelta(days=max(1, int(max_age_days)))
|
|
342
|
+
stale = []
|
|
343
|
+
dated = 0
|
|
344
|
+
for node in nodes:
|
|
345
|
+
ts = _parse_ts(node.get("updated_at"))
|
|
346
|
+
if ts is None:
|
|
347
|
+
continue
|
|
348
|
+
dated += 1
|
|
349
|
+
if ts < cutoff:
|
|
350
|
+
stale.append(node)
|
|
351
|
+
stale_report = {
|
|
352
|
+
"count": len(stale),
|
|
353
|
+
"dated_nodes": dated,
|
|
354
|
+
"threshold_days": int(max_age_days),
|
|
355
|
+
"samples": [_slim(n) for n in stale[:10]],
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
# Edge quality — confidence/evidence read explicitly (0.0 is a valid
|
|
359
|
+
# confidence; never `or`-defaulted away).
|
|
360
|
+
quality_edges = []
|
|
361
|
+
for edge in edges:
|
|
362
|
+
meta = edge.get("metadata") or {}
|
|
363
|
+
entry: Dict[str, Any] = {
|
|
364
|
+
"id": edge.get("id"),
|
|
365
|
+
"source": edge.get("source"),
|
|
366
|
+
"target": edge.get("target"),
|
|
367
|
+
"type": edge.get("type"),
|
|
368
|
+
}
|
|
369
|
+
confidence = meta.get("confidence")
|
|
370
|
+
if confidence is None:
|
|
371
|
+
confidence = edge.get("confidence")
|
|
372
|
+
if isinstance(confidence, (int, float)) and not isinstance(confidence, bool):
|
|
373
|
+
entry["confidence"] = float(confidence)
|
|
374
|
+
evidence = meta.get("evidence")
|
|
375
|
+
if evidence is None:
|
|
376
|
+
evidence = edge.get("evidence")
|
|
377
|
+
entry["evidence"] = list(evidence) if isinstance(evidence, (list, tuple)) else []
|
|
378
|
+
quality_edges.append(entry)
|
|
379
|
+
edge_metrics = self._edge_quality.compute_quality_metrics(quality_edges)
|
|
380
|
+
duplicate_edge_ids = [
|
|
381
|
+
eid for eid in self._edge_quality.detect_duplicate_edges(quality_edges) if eid
|
|
382
|
+
]
|
|
383
|
+
|
|
384
|
+
return {
|
|
385
|
+
"nodes_scanned": len(nodes),
|
|
386
|
+
"edges_scanned": len(edges),
|
|
387
|
+
"duplicates": duplicates,
|
|
388
|
+
"contradictions": contradictions,
|
|
389
|
+
"stale_nodes": stale_report,
|
|
390
|
+
"edge_quality": {
|
|
391
|
+
"metrics": edge_metrics,
|
|
392
|
+
"duplicate_edge_ids": duplicate_edge_ids[:50],
|
|
393
|
+
"duplicate_edge_count": len(duplicate_edge_ids),
|
|
394
|
+
},
|
|
395
|
+
"summary": {
|
|
396
|
+
"exact_duplicate_nodes": duplicates["exact_duplicate_nodes"],
|
|
397
|
+
"near_duplicate_pairs": len(duplicates["near_pairs"]),
|
|
398
|
+
"contradiction_signals": contradictions["count"],
|
|
399
|
+
"stale_nodes": stale_report["count"],
|
|
400
|
+
},
|
|
401
|
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
# ── consolidation ────────────────────────────────────────────────────
|
|
405
|
+
|
|
406
|
+
def consolidate_duplicates(
|
|
407
|
+
self,
|
|
408
|
+
*,
|
|
409
|
+
workspace_id: Optional[str] = None,
|
|
410
|
+
limit: Optional[int] = None,
|
|
411
|
+
dry_run: bool = True,
|
|
412
|
+
near_threshold: float = _DEFAULT_NEAR_THRESHOLD,
|
|
413
|
+
) -> Dict[str, Any]:
|
|
414
|
+
"""Merge plan for exact-duplicate node groups.
|
|
415
|
+
|
|
416
|
+
Canonical node per group = most recently updated (ties: smallest id,
|
|
417
|
+
deterministic). Near-duplicate pairs are *reported for review only* —
|
|
418
|
+
they are never auto-merged.
|
|
419
|
+
|
|
420
|
+
Writes happen only when ``dry_run=False`` **and** the store exposes a
|
|
421
|
+
safe ``merge_nodes(keep_id, remove_ids)`` primitive. The current
|
|
422
|
+
KnowledgeGraphStore does not, so apply requests degrade to
|
|
423
|
+
``mode="plan_only"`` with an actionable plan instead of issuing raw
|
|
424
|
+
SQL against store internals.
|
|
425
|
+
"""
|
|
426
|
+
sample = self._sample(workspace_id=workspace_id, limit=limit)
|
|
427
|
+
nodes, edges = sample["nodes"], sample["edges"]
|
|
428
|
+
duplicates = self._find_duplicates_in(nodes, near_threshold=near_threshold)
|
|
429
|
+
|
|
430
|
+
def _keep_rank(node: Dict[str, Any]):
|
|
431
|
+
ts = _parse_ts(node.get("updated_at")) or datetime.fromtimestamp(
|
|
432
|
+
0, tz=timezone.utc
|
|
433
|
+
)
|
|
434
|
+
# Latest update first; ties broken by smallest id — deterministic.
|
|
435
|
+
return (-ts.timestamp(), str(node.get("id") or ""))
|
|
436
|
+
|
|
437
|
+
groups = []
|
|
438
|
+
for group in duplicates["exact_groups"]:
|
|
439
|
+
members = group["nodes"]
|
|
440
|
+
keep = sorted(members, key=_keep_rank)[0]
|
|
441
|
+
keep_id = str(keep.get("id"))
|
|
442
|
+
remove_ids = [str(m.get("id")) for m in members if str(m.get("id")) != keep_id]
|
|
443
|
+
touched_edges = sum(
|
|
444
|
+
1
|
|
445
|
+
for e in edges
|
|
446
|
+
if str(e.get("source")) in remove_ids or str(e.get("target")) in remove_ids
|
|
447
|
+
)
|
|
448
|
+
groups.append(
|
|
449
|
+
{
|
|
450
|
+
"signature": group["signature"],
|
|
451
|
+
"keep": keep_id,
|
|
452
|
+
"keep_title": keep.get("title"),
|
|
453
|
+
"remove": remove_ids,
|
|
454
|
+
"edges_to_redirect": touched_edges,
|
|
455
|
+
"reason": "exact_duplicate",
|
|
456
|
+
}
|
|
457
|
+
)
|
|
458
|
+
|
|
459
|
+
merge_fn = getattr(self._store, "merge_nodes", None)
|
|
460
|
+
apply_supported = callable(merge_fn)
|
|
461
|
+
applied: List[Dict[str, Any]] = []
|
|
462
|
+
if dry_run:
|
|
463
|
+
mode = "dry_run"
|
|
464
|
+
elif not apply_supported:
|
|
465
|
+
mode = "plan_only"
|
|
466
|
+
else:
|
|
467
|
+
mode = "applied"
|
|
468
|
+
for group in groups:
|
|
469
|
+
try:
|
|
470
|
+
result = merge_fn(group["keep"], group["remove"])
|
|
471
|
+
applied.append({"keep": group["keep"], "result": result})
|
|
472
|
+
except Exception as exc: # keep going; report per-group failure
|
|
473
|
+
logger.exception("proactive merge failed for %s", group["keep"])
|
|
474
|
+
applied.append({"keep": group["keep"], "error": str(exc)})
|
|
475
|
+
|
|
476
|
+
return {
|
|
477
|
+
"mode": mode,
|
|
478
|
+
"apply_supported": apply_supported,
|
|
479
|
+
"nodes_scanned": len(nodes),
|
|
480
|
+
"groups": groups,
|
|
481
|
+
"group_count": len(groups),
|
|
482
|
+
"applied": applied,
|
|
483
|
+
"review_only_near_pairs": duplicates["near_pairs"][:20],
|
|
484
|
+
"note": (
|
|
485
|
+
None
|
|
486
|
+
if apply_supported or dry_run
|
|
487
|
+
else "Store exposes no safe merge primitive (merge_nodes); "
|
|
488
|
+
"returning the merge plan for review instead of mutating the graph."
|
|
489
|
+
),
|
|
490
|
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
# ── ingestion quality gate (pure function seam) ──────────────────────────
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def gate_ingest_candidate(
|
|
498
|
+
text: str,
|
|
499
|
+
existing_search_fn: Callable[[str], Any],
|
|
500
|
+
*,
|
|
501
|
+
near_threshold: float = 0.6,
|
|
502
|
+
) -> Dict[str, Any]:
|
|
503
|
+
"""Score whether new content should be ingested into the graph.
|
|
504
|
+
|
|
505
|
+
Pure function — no store access, no side effects. Intended adoption point
|
|
506
|
+
for the ingestion pipeline (``services/ingestion.py`` /
|
|
507
|
+
``lattice_brain.graph.ingest``), which passes a closure over its own
|
|
508
|
+
scoped search, e.g.::
|
|
509
|
+
|
|
510
|
+
gate = gate_ingest_candidate(
|
|
511
|
+
text,
|
|
512
|
+
lambda q: store.search(q, 20, allowed_workspaces={ws}),
|
|
513
|
+
)
|
|
514
|
+
if gate["action"] == "skip_duplicate": ...
|
|
515
|
+
|
|
516
|
+
``existing_search_fn(text)`` may return either the store's
|
|
517
|
+
``{"matches": [...]}`` shape or a plain list of node dicts
|
|
518
|
+
(``id``/``title``/``summary`` or ``content``).
|
|
519
|
+
|
|
520
|
+
Returns ``{"action": "ingest"|"skip_duplicate"|"review", "reason": str,
|
|
521
|
+
"match_id": Optional[str], "similarity": float}``. A search failure
|
|
522
|
+
returns ``review`` (fail-open to a human, never silent data loss).
|
|
523
|
+
"""
|
|
524
|
+
text = str(text or "").strip()
|
|
525
|
+
if len(text) < 3:
|
|
526
|
+
return {
|
|
527
|
+
"action": "review",
|
|
528
|
+
"reason": "empty_or_too_short",
|
|
529
|
+
"match_id": None,
|
|
530
|
+
"similarity": 0.0,
|
|
531
|
+
}
|
|
532
|
+
try:
|
|
533
|
+
raw = existing_search_fn(text)
|
|
534
|
+
except Exception as exc:
|
|
535
|
+
return {
|
|
536
|
+
"action": "review",
|
|
537
|
+
"reason": f"search_failed: {exc}",
|
|
538
|
+
"match_id": None,
|
|
539
|
+
"similarity": 0.0,
|
|
540
|
+
}
|
|
541
|
+
matches = raw.get("matches") if isinstance(raw, dict) else raw
|
|
542
|
+
key = dedupe_key(text)
|
|
543
|
+
signature = content_signature(text)
|
|
544
|
+
best_similarity = 0.0
|
|
545
|
+
best_id: Optional[str] = None
|
|
546
|
+
for match in list(matches or []):
|
|
547
|
+
if not isinstance(match, dict):
|
|
548
|
+
continue
|
|
549
|
+
parts = [
|
|
550
|
+
str(match.get("title") or ""),
|
|
551
|
+
str(match.get("summary") or ""),
|
|
552
|
+
str(match.get("content") or ""),
|
|
553
|
+
]
|
|
554
|
+
match_text = " ".join(p for p in parts if p).strip()
|
|
555
|
+
if not match_text:
|
|
556
|
+
continue
|
|
557
|
+
if dedupe_key(match_text) == key:
|
|
558
|
+
return {
|
|
559
|
+
"action": "skip_duplicate",
|
|
560
|
+
"reason": "exact_signature_match",
|
|
561
|
+
"match_id": match.get("id"),
|
|
562
|
+
"similarity": 1.0,
|
|
563
|
+
}
|
|
564
|
+
similarity = _jaccard(signature, content_signature(match_text))
|
|
565
|
+
if similarity > best_similarity:
|
|
566
|
+
best_similarity = similarity
|
|
567
|
+
best_id = match.get("id")
|
|
568
|
+
if best_similarity >= near_threshold:
|
|
569
|
+
return {
|
|
570
|
+
"action": "review",
|
|
571
|
+
"reason": "near_duplicate",
|
|
572
|
+
"match_id": best_id,
|
|
573
|
+
"similarity": round(best_similarity, 4),
|
|
574
|
+
}
|
|
575
|
+
return {
|
|
576
|
+
"action": "ingest",
|
|
577
|
+
"reason": "novel_content",
|
|
578
|
+
"match_id": best_id,
|
|
579
|
+
"similarity": round(best_similarity, 4),
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
__all__ = ["ProactiveBrain", "gate_ingest_candidate"]
|