ltcai 11.2.0 → 11.4.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 +46 -53
- package/docs/CHANGELOG.md +61 -0
- package/docs/COMMUNITY_AND_PLUGINS.md +1 -1
- package/docs/DEVELOPMENT.md +1 -1
- package/docs/MULTI_AGENT_RUNTIME.md +1 -1
- package/docs/ONBOARDING.md +1 -1
- package/docs/OPERATIONS.md +6 -2
- package/docs/PERMISSION_MODE.md +1 -1
- package/docs/TRUST_MODEL.md +1 -1
- package/docs/WHY_LATTICE.md +1 -1
- package/docs/kg-schema.md +2 -2
- package/docs/v11.3.0_PLAN.md +202 -0
- package/docs/v11.4.0_RUST_FOUNDATION_PLAN.md +176 -0
- package/lattice_brain/__init__.py +1 -1
- package/lattice_brain/graph/_kg_common/__init__.py +287 -0
- package/lattice_brain/graph/_kg_common/extraction.py +516 -0
- package/lattice_brain/graph/_kg_common/relations.py +161 -0
- package/lattice_brain/graph/_kg_common/text.py +479 -0
- package/lattice_brain/graph/discovery_index/__init__.py +35 -0
- package/lattice_brain/graph/discovery_index/cleanup.py +182 -0
- package/lattice_brain/graph/discovery_index/extract.py +137 -0
- package/lattice_brain/graph/discovery_index/scan.py +411 -0
- package/lattice_brain/graph/discovery_index/upsert.py +495 -0
- package/lattice_brain/graph/projection/__init__.py +42 -0
- package/lattice_brain/graph/projection/curation.py +500 -0
- package/lattice_brain/graph/{projection.py → projection/v2_schema.py} +15 -477
- package/lattice_brain/graph/retrieval/__init__.py +54 -0
- package/lattice_brain/graph/retrieval/context.py +197 -0
- package/lattice_brain/graph/retrieval/graph_view.py +319 -0
- package/lattice_brain/graph/retrieval/hybrid.py +488 -0
- package/lattice_brain/graph/retrieval/maintenance.py +121 -0
- package/lattice_brain/graph/retrieval/signals.py +95 -0
- package/lattice_brain/graph/retrieval_vector/__init__.py +42 -0
- package/lattice_brain/graph/retrieval_vector/fingerprint.py +97 -0
- package/lattice_brain/graph/retrieval_vector/indexing.py +347 -0
- package/lattice_brain/graph/retrieval_vector/search.py +560 -0
- package/lattice_brain/graph/retrieval_vector/status.py +374 -0
- package/lattice_brain/ingestion/__init__.py +130 -0
- package/lattice_brain/ingestion/_contract.py +90 -0
- package/lattice_brain/ingestion/constants.py +127 -0
- package/lattice_brain/ingestion/folder_scan.py +57 -0
- package/lattice_brain/ingestion/folders.py +258 -0
- package/lattice_brain/ingestion/hashing.py +26 -0
- package/lattice_brain/ingestion/jobs_api.py +107 -0
- package/lattice_brain/ingestion/models.py +80 -0
- package/lattice_brain/ingestion/pipeline.py +486 -0
- package/lattice_brain/ingestion/quality.py +209 -0
- package/lattice_brain/ingestion/routing.py +295 -0
- package/lattice_brain/multimodal/__init__.py +164 -0
- package/lattice_brain/multimodal/audio.py +77 -0
- package/lattice_brain/multimodal/common.py +118 -0
- package/lattice_brain/multimodal/images.py +498 -0
- package/lattice_brain/multimodal/ports.py +169 -0
- package/lattice_brain/multimodal/video.py +410 -0
- package/lattice_brain/portability/__init__.py +90 -0
- package/lattice_brain/portability/_contract.py +42 -0
- package/lattice_brain/portability/backups.py +338 -0
- package/lattice_brain/portability/bundles.py +136 -0
- package/lattice_brain/portability/constants.py +93 -0
- package/lattice_brain/portability/fsops.py +138 -0
- package/lattice_brain/portability/service.py +41 -0
- package/lattice_brain/{portability.py → portability/sharing.py} +44 -677
- package/lattice_brain/runtime/__init__.py +1 -1
- package/lattice_brain/runtime/multi_agent.py +1 -1
- package/latticeai/__init__.py +1 -1
- package/latticeai/api/chronicle.py +63 -0
- package/latticeai/core/agent/__init__.py +93 -0
- package/latticeai/core/agent/_contract.py +79 -0
- package/latticeai/core/agent/context.py +57 -0
- package/latticeai/core/agent/deps.py +125 -0
- package/latticeai/core/agent/execution.py +622 -0
- package/latticeai/core/agent/planning.py +145 -0
- package/latticeai/core/agent/recovery.py +157 -0
- package/latticeai/core/agent/runtime.py +210 -0
- package/latticeai/core/agent/verification.py +231 -0
- package/latticeai/core/embedding_providers/__init__.py +151 -0
- package/latticeai/core/embedding_providers/base.py +199 -0
- package/latticeai/core/embedding_providers/captions.py +162 -0
- package/latticeai/core/embedding_providers/profiles.py +126 -0
- package/latticeai/core/embedding_providers/text.py +350 -0
- package/latticeai/core/embedding_providers/vision.py +352 -0
- package/latticeai/core/file_generation/__init__.py +115 -0
- package/latticeai/core/file_generation/bundles.py +76 -0
- package/latticeai/core/file_generation/extraction.py +154 -0
- package/latticeai/core/file_generation/inference.py +235 -0
- package/latticeai/core/file_generation/orchestration.py +152 -0
- package/latticeai/core/file_generation/prompting.py +117 -0
- package/latticeai/core/file_generation/repair.py +114 -0
- package/latticeai/core/file_generation/sanitize.py +61 -0
- package/latticeai/core/file_generation/validation.py +201 -0
- package/latticeai/core/legacy_compatibility.py +1 -1
- package/latticeai/core/marketplace.py +1 -1
- package/latticeai/core/messages.py +9 -0
- package/latticeai/core/workspace_os_constants.py +1 -1
- package/latticeai/integrations/telegram_bot/__init__.py +123 -0
- package/latticeai/integrations/telegram_bot/__main__.py +17 -0
- package/latticeai/integrations/telegram_bot/config.py +86 -0
- package/latticeai/integrations/telegram_bot/dispatch.py +311 -0
- package/latticeai/integrations/telegram_bot/flows.py +478 -0
- package/latticeai/integrations/telegram_bot/helpers.py +322 -0
- package/latticeai/integrations/telegram_bot/screens.py +394 -0
- package/latticeai/models/router/__init__.py +88 -0
- package/latticeai/models/router/_contract.py +66 -0
- package/latticeai/models/router/branding.py +56 -0
- package/latticeai/models/router/catalog.py +69 -0
- package/latticeai/models/router/documents.py +199 -0
- package/latticeai/models/router/errors.py +37 -0
- package/latticeai/models/router/generation.py +258 -0
- package/latticeai/models/router/loading.py +291 -0
- package/latticeai/models/router/local_models.py +85 -0
- package/latticeai/models/router/registry.py +147 -0
- package/latticeai/runtime/build_phases/__init__.py +82 -0
- package/latticeai/runtime/build_phases/features.py +407 -0
- package/latticeai/runtime/build_phases/foundation.py +555 -0
- package/latticeai/runtime/build_phases/web.py +492 -0
- package/latticeai/runtime/runtime_context.py +1 -0
- package/latticeai/services/architecture_readiness.py +48 -19
- package/latticeai/services/brain_intelligence/__init__.py +58 -0
- package/latticeai/services/brain_intelligence/_contract.py +71 -0
- package/latticeai/services/brain_intelligence/consistency.py +193 -0
- package/latticeai/services/brain_intelligence/constants.py +47 -0
- package/latticeai/services/brain_intelligence/digest.py +258 -0
- package/latticeai/services/brain_intelligence/health.py +331 -0
- package/latticeai/services/brain_intelligence/proposals.py +264 -0
- package/latticeai/services/brain_intelligence/sampling.py +84 -0
- package/latticeai/services/brain_intelligence/service.py +48 -0
- package/latticeai/services/chronicle.py +557 -0
- package/latticeai/services/memory_service/__init__.py +52 -0
- package/latticeai/services/memory_service/_contract.py +100 -0
- package/latticeai/services/memory_service/brief.py +431 -0
- package/latticeai/services/memory_service/constants.py +57 -0
- package/latticeai/services/memory_service/maintenance.py +138 -0
- package/latticeai/services/memory_service/manager.py +186 -0
- package/latticeai/services/memory_service/proof.py +136 -0
- package/latticeai/services/memory_service/recall.py +225 -0
- package/latticeai/services/memory_service/service.py +48 -0
- package/latticeai/services/memory_service/stores.py +110 -0
- package/latticeai/services/model_runtime/__init__.py +322 -0
- package/latticeai/services/model_runtime/cloud.py +87 -0
- package/latticeai/services/model_runtime/download.py +282 -0
- package/latticeai/services/model_runtime/engines.py +341 -0
- package/latticeai/services/model_runtime/loading.py +178 -0
- package/latticeai/services/model_runtime/service.py +129 -0
- package/latticeai/services/model_runtime/state.py +131 -0
- package/latticeai/services/model_runtime/status.py +255 -0
- package/latticeai/services/product_readiness.py +15 -7
- package/latticeai/setup/wizard/__init__.py +126 -0
- package/latticeai/setup/wizard/catalog.py +172 -0
- package/latticeai/setup/wizard/detect.py +323 -0
- package/latticeai/setup/wizard/install.py +348 -0
- package/latticeai/setup/wizard/paths.py +168 -0
- package/latticeai/setup/wizard/plans.py +74 -0
- package/latticeai/setup/wizard/recommend.py +320 -0
- package/package.json +6 -2
- package/scripts/bump_version.py +14 -0
- package/scripts/capture_release_evidence.mjs +33 -21
- package/scripts/check_current_release_docs.mjs +1 -1
- package/scripts/check_i18n_namespace_coverage.mjs +41 -4
- package/scripts/check_max_file_lines.mjs +102 -0
- package/scripts/check_release_evidence_bound.mjs +30 -15
- package/scripts/check_screenshot_pixel_delta.py +34 -4
- package/scripts/check_server_i18n.mjs +1 -0
- package/scripts/generate_rust_parity_fixtures.py +562 -0
- package/scripts/lib/mock_server_fingerprint.mjs +94 -0
- package/scripts/release_screen_claims.json +31 -2
- package/src-tauri/Cargo.lock +361 -3
- package/src-tauri/Cargo.toml +6 -1
- package/src-tauri/src/backend.rs +349 -0
- package/src-tauri/src/folder.rs +33 -0
- package/src-tauri/src/main.rs +97 -399
- package/src-tauri/tauri.conf.json +1 -1
- package/static/app/asset-manifest.json +41 -37
- package/static/app/assets/Act-yYpYnn0v.js +1 -0
- package/static/app/assets/AdminConsole-DL3Cr5pL.js +1 -0
- package/static/app/assets/{Brain-tuhI4sOC.js → Brain-C1HBN0Wf.js} +2 -2
- package/static/app/assets/BrainHome-DoXRhUUC.js +2 -0
- package/static/app/assets/BrainSignals-6yR6ir5t.js +1 -0
- package/static/app/assets/Capture-CFIRsFNE.js +1 -0
- package/static/app/assets/Chronicle-BZbEgiwN.js +1 -0
- package/static/app/assets/CommandPalette-D2pMxC2I.js +1 -0
- package/static/app/assets/Library-DwO3yZST.js +1 -0
- package/static/app/assets/{LivingBrain-DBwhto14.js → LivingBrain-Jn1GK0-S.js} +1 -1
- package/static/app/assets/ProductFlow-B-w1R4Oo.js +1 -0
- package/static/app/assets/ReviewCard-6B27X8Vg.js +3 -0
- package/static/app/assets/System-DW8F-2xL.js +1 -0
- package/static/app/assets/arrow-left-DXvKg9U6.js +1 -0
- package/static/app/assets/{bot-Cia42c2h.js → bot-IM_E_Y12.js} +1 -1
- package/static/app/assets/brain-Ci1CkWjM.js +1 -0
- package/static/app/assets/{button-2j2Ijzgq.js → button-COwyqfHM.js} +1 -1
- package/static/app/assets/circle-check-DfInj-qD.js +1 -0
- package/static/app/assets/{circle-pause-BEFeWpVW.js → circle-pause-DEM4A1Y5.js} +1 -1
- package/static/app/assets/{circle-play-ujXMcHxl.js → circle-play-C9djDuLd.js} +1 -1
- package/static/app/assets/{cpu-k4awryFq.js → cpu-DFdo1gw-.js} +1 -1
- package/static/app/assets/{download-DFbLJ_ig.js → download-SnJL6oqk.js} +1 -1
- package/static/app/assets/{folder-open-7y_b6xkM.js → folder-open-CqZeDkjE.js} +1 -1
- package/static/app/assets/{hard-drive-Bidh02Kr.js → hard-drive-j1jJXYYf.js} +1 -1
- package/static/app/assets/{index-DwDl9-8Y.css → index-BLPb5lmE.css} +1 -1
- package/static/app/assets/index-_u5iUHDr.js +10 -0
- package/static/app/assets/input-B0lPdRQZ.js +1 -0
- package/static/app/assets/link-2-CoFbooHS.js +1 -0
- package/static/app/assets/{permissionCopy-Bpb83Hx9.js → permissionCopy-BsyLxtao.js} +1 -1
- package/static/app/assets/primitives-DEbN-d6p.js +1 -0
- package/static/app/assets/search-BybIWPNd.js +1 -0
- package/static/app/assets/{share-2-BH1M-WNi.js → share-2-CVtZ_ewX.js} +1 -1
- package/static/app/assets/{shield-alert-BlKdBXcG.js → shield-alert-CBi2GNWM.js} +1 -1
- package/static/app/assets/{textarea-CCWbUfFB.js → textarea-DNMpB5ih.js} +1 -1
- package/static/app/assets/{useFocusTrap-YdHQ7pJ1.js → useFocusTrap-C83t3GXF.js} +1 -1
- package/static/app/assets/useMutation-DtbJDoyz.js +1 -0
- package/static/app/assets/{useQuery-CXQiwbVT.js → useQuery-Dcp1OChy.js} +1 -1
- package/static/app/assets/utils-BlZr7Pd4.js +4 -0
- package/static/app/assets/workspace-jJY4RuAV.js +1 -0
- package/static/app/index.html +4 -4
- package/static/sw.js +1 -1
- package/lattice_brain/graph/_kg_common.py +0 -1331
- package/lattice_brain/graph/discovery_index.py +0 -1141
- package/lattice_brain/graph/retrieval.py +0 -1120
- package/lattice_brain/graph/retrieval_vector.py +0 -1293
- package/lattice_brain/ingestion.py +0 -1525
- package/lattice_brain/multimodal.py +0 -1258
- package/latticeai/core/agent.py +0 -1465
- package/latticeai/core/embedding_providers.py +0 -1196
- package/latticeai/core/file_generation.py +0 -1047
- package/latticeai/integrations/telegram_bot.py +0 -1390
- package/latticeai/models/router.py +0 -1007
- package/latticeai/runtime/build_phases.py +0 -1450
- package/latticeai/services/brain_intelligence.py +0 -1083
- package/latticeai/services/memory_service.py +0 -1177
- package/latticeai/services/model_runtime.py +0 -1281
- package/latticeai/setup/wizard.py +0 -1310
- package/static/app/assets/Act-AWf0SAKp.js +0 -1
- package/static/app/assets/AdminConsole-D0u8Tiyj.js +0 -1
- package/static/app/assets/BrainHome-Ts7G_Ila.js +0 -2
- package/static/app/assets/BrainSignals-jMYgQ2Ar.js +0 -1
- package/static/app/assets/Capture-CqOSzyPr.js +0 -1
- package/static/app/assets/CommandPalette-DC0Bzh-I.js +0 -1
- package/static/app/assets/Library-CX-bbhmK.js +0 -1
- package/static/app/assets/ProductFlow-BHA2cfKI.js +0 -1
- package/static/app/assets/ReviewCard-BUhCKRNM.js +0 -3
- package/static/app/assets/System-Bu2t5hn1.js +0 -1
- package/static/app/assets/arrow-left-Dzwa5zRb.js +0 -1
- package/static/app/assets/brain-DJMoqrwx.js +0 -1
- package/static/app/assets/index-BpYkzcVm.js +0 -10
- package/static/app/assets/input-DSlJJxRs.js +0 -1
- package/static/app/assets/primitives-BCx6TvfG.js +0 -1
- package/static/app/assets/search-Cgy8cCFJ.js +0 -1
- package/static/app/assets/utils-zqPZJxdx.js +0 -4
- package/static/app/assets/workspace-DXTihhfU.js +0 -1
|
@@ -1,1083 +0,0 @@
|
|
|
1
|
-
"""Proactive Brain Intelligence service (v9.3.0).
|
|
2
|
-
|
|
3
|
-
The Brain graduates from a passive store to an active steward of its own
|
|
4
|
-
knowledge. This service wires the previously dormant quality layer
|
|
5
|
-
(:mod:`lattice_brain.quality` — dedupe, merge, conflict and temporal
|
|
6
|
-
contradiction detection, retention) into router-facing capabilities:
|
|
7
|
-
|
|
8
|
-
* **health_report** — scored diagnosis of the Brain across freshness,
|
|
9
|
-
connectivity, embedding coverage, and contradiction pressure, with
|
|
10
|
-
recommended next actions. Every number is read from the live stores;
|
|
11
|
-
a missing store degrades the dimension to ``unavailable``, never a guess.
|
|
12
|
-
* **insights** — a proactive digest: recent knowledge growth, most active
|
|
13
|
-
types, stale knowledge, orphan (disconnected) nodes, and suggested
|
|
14
|
-
questions grounded in real node titles.
|
|
15
|
-
* **contradictions** — surfaced conflicts across workspace memories
|
|
16
|
-
(negation/preference conflicts, temporal contradictions) plus explicit
|
|
17
|
-
CONTRADICTS edges already recorded in the graph.
|
|
18
|
-
* **consolidate** — duplicate-memory and duplicate-edge detection. Dry-run
|
|
19
|
-
by default (consent-first, like every Brain automation); ``apply=True``
|
|
20
|
-
prunes only exact duplicate workspace memories through the audited
|
|
21
|
-
MemoryService path and never touches graph content.
|
|
22
|
-
|
|
23
|
-
Pure service: no FastAPI, no globals. Collaborators are injected.
|
|
24
|
-
"""
|
|
25
|
-
|
|
26
|
-
from __future__ import annotations
|
|
27
|
-
|
|
28
|
-
import logging
|
|
29
|
-
from datetime import datetime, timedelta, timezone
|
|
30
|
-
from typing import Any, Dict, List, Optional
|
|
31
|
-
|
|
32
|
-
from lattice_brain.quality import GraphEdgeQualityManager, MemoryQualityManager
|
|
33
|
-
from latticeai.core.timeutil import now_iso as _now
|
|
34
|
-
|
|
35
|
-
LOGGER = logging.getLogger(__name__)
|
|
36
|
-
|
|
37
|
-
_STALE_DAYS = 45
|
|
38
|
-
_RECENT_DAYS = 7
|
|
39
|
-
_GRAPH_SAMPLE_LIMIT = 800
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
def _parse_ts(value: Any) -> Optional[datetime]:
|
|
43
|
-
text = str(value or "").strip()
|
|
44
|
-
if not text:
|
|
45
|
-
return None
|
|
46
|
-
try:
|
|
47
|
-
parsed = datetime.fromisoformat(text.replace("Z", "+00:00"))
|
|
48
|
-
except ValueError:
|
|
49
|
-
return None
|
|
50
|
-
if parsed.tzinfo is None:
|
|
51
|
-
parsed = parsed.replace(tzinfo=timezone.utc)
|
|
52
|
-
return parsed
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
def _no_graph_reason(graph_available: bool) -> str:
|
|
56
|
-
"""Why a graph-derived health dimension has nothing to say.
|
|
57
|
-
|
|
58
|
-
Two different situations that both end in ``status: "unavailable"``: the
|
|
59
|
-
graph could not be read at all, and the graph read fine but holds nothing
|
|
60
|
-
yet. Telling them apart is the difference between "something is broken"
|
|
61
|
-
and "you have not saved anything yet".
|
|
62
|
-
"""
|
|
63
|
-
return (
|
|
64
|
-
"no knowledge saved yet"
|
|
65
|
-
if graph_available
|
|
66
|
-
else "the knowledge graph could not be read"
|
|
67
|
-
)
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
class BrainIntelligenceService:
|
|
71
|
-
def __init__(
|
|
72
|
-
self,
|
|
73
|
-
*,
|
|
74
|
-
knowledge_graph: Any = None,
|
|
75
|
-
memory_service: Any = None,
|
|
76
|
-
enable_graph: bool = True,
|
|
77
|
-
review_queue: Any = None,
|
|
78
|
-
) -> None:
|
|
79
|
-
self._kg = knowledge_graph
|
|
80
|
-
self._memory = memory_service
|
|
81
|
-
self._enable_graph = bool(enable_graph and knowledge_graph is not None)
|
|
82
|
-
self._memory_quality = MemoryQualityManager()
|
|
83
|
-
self._edge_quality = GraphEdgeQualityManager()
|
|
84
|
-
self._proactive_brain: Any = None
|
|
85
|
-
self._review_queue_service = review_queue
|
|
86
|
-
self._synthesizer: Any = None
|
|
87
|
-
|
|
88
|
-
# ── proposal path (v11.1.0) ───────────────────────────────────────────
|
|
89
|
-
#
|
|
90
|
-
# Synthesis never writes: it proposes, and the Review Center decides. That
|
|
91
|
-
# makes the review queue a hard dependency of every method below — when it
|
|
92
|
-
# is absent they report ``available: False`` rather than falling back to a
|
|
93
|
-
# direct write.
|
|
94
|
-
|
|
95
|
-
def attach_review_queue(self, review_queue: Any) -> None:
|
|
96
|
-
"""Bind the review queue proposals are written to (composition root)."""
|
|
97
|
-
self._review_queue_service = review_queue
|
|
98
|
-
self._synthesizer = None
|
|
99
|
-
|
|
100
|
-
def _review_queue(self) -> Any:
|
|
101
|
-
"""The queue to propose into, or ``None`` when there is none.
|
|
102
|
-
|
|
103
|
-
Prefers an explicitly injected service. Otherwise it builds one over
|
|
104
|
-
the workspace store the memory service already holds — the same
|
|
105
|
-
``WorkspaceOSStore`` every other ``ReviewQueueService`` in the process
|
|
106
|
-
is constructed over, so proposals land in the one inbox the user reads
|
|
107
|
-
even before the composition root injects the service directly.
|
|
108
|
-
"""
|
|
109
|
-
if self._review_queue_service is not None:
|
|
110
|
-
return self._review_queue_service
|
|
111
|
-
store = getattr(self._memory, "_store", None)
|
|
112
|
-
if store is None or not hasattr(store, "create_review_item"):
|
|
113
|
-
return None
|
|
114
|
-
from latticeai.services.review_queue import ReviewQueueService
|
|
115
|
-
|
|
116
|
-
self._review_queue_service = ReviewQueueService(store=store)
|
|
117
|
-
return self._review_queue_service
|
|
118
|
-
|
|
119
|
-
def _synthesis(self) -> Any:
|
|
120
|
-
"""Lazy :class:`BrainSynthesizer` over the graph + review queue."""
|
|
121
|
-
if self._synthesizer is not None:
|
|
122
|
-
return self._synthesizer
|
|
123
|
-
queue = self._review_queue()
|
|
124
|
-
if not self._enable_graph or queue is None:
|
|
125
|
-
return None
|
|
126
|
-
from lattice_brain.synthesis import BrainSynthesizer
|
|
127
|
-
|
|
128
|
-
self._synthesizer = BrainSynthesizer(self._kg, queue)
|
|
129
|
-
return self._synthesizer
|
|
130
|
-
|
|
131
|
-
@staticmethod
|
|
132
|
-
def _no_queue(detail: str) -> Dict[str, Any]:
|
|
133
|
-
return {"available": False, "detail": detail, "generated_at": _now()}
|
|
134
|
-
|
|
135
|
-
def synthesize(
|
|
136
|
-
self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None
|
|
137
|
-
) -> Dict[str, Any]:
|
|
138
|
-
"""Run one synthesis pass; every finding becomes a review proposal."""
|
|
139
|
-
synthesizer = self._synthesis()
|
|
140
|
-
if synthesizer is None:
|
|
141
|
-
return self._no_queue(
|
|
142
|
-
"synthesis needs both the knowledge graph and the review queue"
|
|
143
|
-
)
|
|
144
|
-
try:
|
|
145
|
-
result = dict(
|
|
146
|
-
synthesizer.run(workspace_id=workspace_id, user_email=user_email)
|
|
147
|
-
)
|
|
148
|
-
except Exception as exc: # noqa: BLE001 — a failed pass is reported, not raised
|
|
149
|
-
LOGGER.exception("brain synthesis failed")
|
|
150
|
-
return {"available": False, "error": str(exc), "generated_at": _now()}
|
|
151
|
-
result["available"] = True
|
|
152
|
-
return result
|
|
153
|
-
|
|
154
|
-
def note_ingest(
|
|
155
|
-
self,
|
|
156
|
-
result: Any,
|
|
157
|
-
*,
|
|
158
|
-
user_email: Optional[str] = None,
|
|
159
|
-
workspace_id: Optional[str] = None,
|
|
160
|
-
) -> Optional[Dict[str, Any]]:
|
|
161
|
-
"""Ingest-driven trigger seam.
|
|
162
|
-
|
|
163
|
-
Hand every ingest result here; synthesis runs only once the configured
|
|
164
|
-
number of genuinely new nodes has accumulated. Returns the run result
|
|
165
|
-
when one fired, ``None`` otherwise — so an ingest path can call this
|
|
166
|
-
unconditionally and cheaply.
|
|
167
|
-
"""
|
|
168
|
-
synthesizer = self._synthesis()
|
|
169
|
-
if synthesizer is None:
|
|
170
|
-
return None
|
|
171
|
-
try:
|
|
172
|
-
return synthesizer.run_if_due(
|
|
173
|
-
result, workspace_id=workspace_id, user_email=user_email
|
|
174
|
-
)
|
|
175
|
-
except Exception: # noqa: BLE001 — synthesis must never break an ingest
|
|
176
|
-
LOGGER.exception("ingest-triggered synthesis failed")
|
|
177
|
-
return None
|
|
178
|
-
|
|
179
|
-
def propose_contradictions(
|
|
180
|
-
self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None
|
|
181
|
-
) -> Dict[str, Any]:
|
|
182
|
-
"""Raise a review proposal for every contradicting pair of memories."""
|
|
183
|
-
queue = self._review_queue()
|
|
184
|
-
if not self._enable_graph or queue is None:
|
|
185
|
-
return self._no_queue(
|
|
186
|
-
"contradiction proposals need both the knowledge graph and the review queue"
|
|
187
|
-
)
|
|
188
|
-
from lattice_brain.synthesis import propose_contradictions
|
|
189
|
-
|
|
190
|
-
try:
|
|
191
|
-
return propose_contradictions(
|
|
192
|
-
self._kg, queue, workspace_id=workspace_id, user_email=user_email
|
|
193
|
-
)
|
|
194
|
-
except Exception as exc: # noqa: BLE001
|
|
195
|
-
LOGGER.exception("contradiction proposal pass failed")
|
|
196
|
-
return {"available": False, "error": str(exc), "generated_at": _now()}
|
|
197
|
-
|
|
198
|
-
def resolve_contradiction(
|
|
199
|
-
self,
|
|
200
|
-
item_id: str,
|
|
201
|
-
*,
|
|
202
|
-
resolution: str,
|
|
203
|
-
workspace_id: Optional[str] = None,
|
|
204
|
-
) -> Dict[str, Any]:
|
|
205
|
-
"""Approve a contradiction proposal and apply its temporal stamps.
|
|
206
|
-
|
|
207
|
-
Raises ``ContradictionResolutionError`` (a ``ValueError``) for an
|
|
208
|
-
unknown resolution or a review item that is not a contradiction — the
|
|
209
|
-
router turns those into 400s.
|
|
210
|
-
"""
|
|
211
|
-
queue = self._review_queue()
|
|
212
|
-
if not self._enable_graph or queue is None:
|
|
213
|
-
return self._no_queue(
|
|
214
|
-
"resolving a contradiction needs both the knowledge graph and the review queue"
|
|
215
|
-
)
|
|
216
|
-
from lattice_brain.synthesis import resolve_contradiction
|
|
217
|
-
|
|
218
|
-
result = dict(
|
|
219
|
-
resolve_contradiction(
|
|
220
|
-
self._kg,
|
|
221
|
-
queue,
|
|
222
|
-
item_id,
|
|
223
|
-
resolution=resolution,
|
|
224
|
-
workspace_id=workspace_id,
|
|
225
|
-
)
|
|
226
|
-
)
|
|
227
|
-
result["available"] = True
|
|
228
|
-
return result
|
|
229
|
-
|
|
230
|
-
def importance_report(
|
|
231
|
-
self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None
|
|
232
|
-
) -> Dict[str, Any]:
|
|
233
|
-
"""Which memories are load-bearing, and which have decayed into noise."""
|
|
234
|
-
proactive = self._proactive()
|
|
235
|
-
if proactive is None:
|
|
236
|
-
return {"available": False, "candidates": [], "generated_at": _now()}
|
|
237
|
-
try:
|
|
238
|
-
report = dict(proactive.importance_report(workspace_id=workspace_id))
|
|
239
|
-
except Exception as exc: # noqa: BLE001
|
|
240
|
-
LOGGER.exception("importance report failed")
|
|
241
|
-
return {
|
|
242
|
-
"available": False,
|
|
243
|
-
"error": str(exc),
|
|
244
|
-
"candidates": [],
|
|
245
|
-
"generated_at": _now(),
|
|
246
|
-
}
|
|
247
|
-
report["available"] = True
|
|
248
|
-
return report
|
|
249
|
-
|
|
250
|
-
def proactive_brief(
|
|
251
|
-
self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None
|
|
252
|
-
) -> Dict[str, Any]:
|
|
253
|
-
"""The Brain Brief's proactive section: what the Brain noticed on its own.
|
|
254
|
-
|
|
255
|
-
Read-only. It counts the proposals already waiting in the Review Center
|
|
256
|
-
rather than raising new ones, so opening the home screen never mutates
|
|
257
|
-
anything — and reports honestly when there is no queue to read.
|
|
258
|
-
"""
|
|
259
|
-
section: Dict[str, Any] = {
|
|
260
|
-
"available": False,
|
|
261
|
-
"pending": {"total": 0, "by_kind": {}},
|
|
262
|
-
"tidying": False,
|
|
263
|
-
"headline": "",
|
|
264
|
-
"lines": [],
|
|
265
|
-
"generated_at": _now(),
|
|
266
|
-
}
|
|
267
|
-
queue = self._review_queue()
|
|
268
|
-
if queue is None:
|
|
269
|
-
section["detail"] = "the review queue is not available on this deployment"
|
|
270
|
-
return section
|
|
271
|
-
pending = self._pending_synthesis_items(queue, workspace_id=workspace_id)
|
|
272
|
-
by_kind: Dict[str, int] = {}
|
|
273
|
-
for item in pending:
|
|
274
|
-
kind = str(item.get("kind") or "suggestion")
|
|
275
|
-
by_kind[kind] = by_kind.get(kind, 0) + 1
|
|
276
|
-
synthesizer = self._synthesis()
|
|
277
|
-
brief: Dict[str, Any] = {}
|
|
278
|
-
if synthesizer is not None:
|
|
279
|
-
try:
|
|
280
|
-
brief = dict(
|
|
281
|
-
synthesizer.brief_section(
|
|
282
|
-
counts=by_kind, workspace_id=workspace_id
|
|
283
|
-
)
|
|
284
|
-
)
|
|
285
|
-
except Exception: # noqa: BLE001 — the section degrades, never raises
|
|
286
|
-
LOGGER.exception("synthesis brief section failed")
|
|
287
|
-
section.update(
|
|
288
|
-
{
|
|
289
|
-
"available": True,
|
|
290
|
-
"pending": {"total": len(pending), "by_kind": by_kind},
|
|
291
|
-
"items": [
|
|
292
|
-
{
|
|
293
|
-
"id": item.get("id"),
|
|
294
|
-
"kind": item.get("kind"),
|
|
295
|
-
"title": item.get("title"),
|
|
296
|
-
"summary": item.get("summary"),
|
|
297
|
-
}
|
|
298
|
-
for item in pending[:5]
|
|
299
|
-
],
|
|
300
|
-
"tidying": by_kind.get("consolidation", 0) > 0,
|
|
301
|
-
"headline": str(brief.get("headline") or ""),
|
|
302
|
-
"lines": list(brief.get("lines") or []),
|
|
303
|
-
"recent_nodes": brief.get("recent_nodes"),
|
|
304
|
-
}
|
|
305
|
-
)
|
|
306
|
-
return section
|
|
307
|
-
|
|
308
|
-
@staticmethod
|
|
309
|
-
def _pending_synthesis_items(
|
|
310
|
-
queue: Any, *, workspace_id: Optional[str]
|
|
311
|
-
) -> List[Dict[str, Any]]:
|
|
312
|
-
from lattice_brain.synthesis import SYNTHESIS_REVIEW_SOURCE
|
|
313
|
-
|
|
314
|
-
try:
|
|
315
|
-
listing = queue.list(
|
|
316
|
-
workspace_id=workspace_id, source=SYNTHESIS_REVIEW_SOURCE
|
|
317
|
-
)
|
|
318
|
-
except Exception: # noqa: BLE001 — an unreadable inbox reads as empty
|
|
319
|
-
LOGGER.exception("review queue listing failed")
|
|
320
|
-
return []
|
|
321
|
-
return [
|
|
322
|
-
item
|
|
323
|
-
for item in listing.get("items") or []
|
|
324
|
-
if str(item.get("effective_status") or item.get("status")) == "pending"
|
|
325
|
-
]
|
|
326
|
-
|
|
327
|
-
def _proactive(self) -> Any:
|
|
328
|
-
"""Lazy graph-layer ProactiveBrain over the injected store (or None)."""
|
|
329
|
-
if not self._enable_graph:
|
|
330
|
-
return None
|
|
331
|
-
if self._proactive_brain is None:
|
|
332
|
-
try:
|
|
333
|
-
from lattice_brain.graph.proactive import ProactiveBrain
|
|
334
|
-
|
|
335
|
-
self._proactive_brain = ProactiveBrain(
|
|
336
|
-
self._kg, sample_limit=_GRAPH_SAMPLE_LIMIT
|
|
337
|
-
)
|
|
338
|
-
except Exception:
|
|
339
|
-
LOGGER.exception("proactive brain initialization failed")
|
|
340
|
-
return None
|
|
341
|
-
return self._proactive_brain
|
|
342
|
-
|
|
343
|
-
# ── shared graph sampling ─────────────────────────────────────────────
|
|
344
|
-
|
|
345
|
-
def _graph_sample(self, *, workspace_id: Optional[str]) -> Dict[str, Any]:
|
|
346
|
-
"""Recent graph slice with scoping applied. Empty when graph is off."""
|
|
347
|
-
if not self._enable_graph:
|
|
348
|
-
return {"nodes": [], "edges": [], "available": False}
|
|
349
|
-
try:
|
|
350
|
-
kwargs: Dict[str, Any] = {}
|
|
351
|
-
if workspace_id is not None:
|
|
352
|
-
kwargs["allowed_workspaces"] = {workspace_id}
|
|
353
|
-
data = self._kg.graph(_GRAPH_SAMPLE_LIMIT, **kwargs)
|
|
354
|
-
edges = []
|
|
355
|
-
for edge in data.get("edges") or []:
|
|
356
|
-
# Store emits "from"/"to"; the quality layer expects
|
|
357
|
-
# "source"/"target". Normalize once here.
|
|
358
|
-
normalized = dict(edge)
|
|
359
|
-
normalized.setdefault("source", edge.get("from"))
|
|
360
|
-
normalized.setdefault("target", edge.get("to"))
|
|
361
|
-
edges.append(normalized)
|
|
362
|
-
return {
|
|
363
|
-
"nodes": list(data.get("nodes") or []),
|
|
364
|
-
"edges": edges,
|
|
365
|
-
"available": True,
|
|
366
|
-
}
|
|
367
|
-
except Exception as exc:
|
|
368
|
-
LOGGER.exception("brain intelligence graph sample failed")
|
|
369
|
-
return {"nodes": [], "edges": [], "available": False, "error": str(exc)}
|
|
370
|
-
|
|
371
|
-
def _workspace_memories(
|
|
372
|
-
self, *, user_email: Optional[str], workspace_id: Optional[str]
|
|
373
|
-
) -> List[Dict[str, Any]]:
|
|
374
|
-
if self._memory is None:
|
|
375
|
-
return []
|
|
376
|
-
try:
|
|
377
|
-
inspected = self._memory.inspect(
|
|
378
|
-
"workspace",
|
|
379
|
-
user_email=user_email,
|
|
380
|
-
workspace_id=workspace_id or "personal",
|
|
381
|
-
limit=500,
|
|
382
|
-
)
|
|
383
|
-
return list(inspected.get("items") or [])
|
|
384
|
-
except Exception:
|
|
385
|
-
LOGGER.exception("brain intelligence memory read failed")
|
|
386
|
-
return []
|
|
387
|
-
|
|
388
|
-
# ── health report ─────────────────────────────────────────────────────
|
|
389
|
-
|
|
390
|
-
def health_report(
|
|
391
|
-
self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None
|
|
392
|
-
) -> Dict[str, Any]:
|
|
393
|
-
sample = self._graph_sample(workspace_id=workspace_id)
|
|
394
|
-
nodes, edges = sample["nodes"], sample["edges"]
|
|
395
|
-
now = datetime.now(timezone.utc)
|
|
396
|
-
dimensions: Dict[str, Dict[str, Any]] = {}
|
|
397
|
-
|
|
398
|
-
# Freshness — how much of the sampled knowledge saw recent updates.
|
|
399
|
-
if sample["available"] and nodes:
|
|
400
|
-
stale_cutoff = now - timedelta(days=_STALE_DAYS)
|
|
401
|
-
dated = [(_parse_ts(n.get("updated_at")), n) for n in nodes]
|
|
402
|
-
known = [pair for pair in dated if pair[0] is not None]
|
|
403
|
-
stale = [n for ts, n in known if ts is not None and ts < stale_cutoff]
|
|
404
|
-
fresh_ratio = 1.0 - (len(stale) / len(known)) if known else 0.0
|
|
405
|
-
dimensions["freshness"] = {
|
|
406
|
-
"status": "ok",
|
|
407
|
-
"score": round(fresh_ratio * 100),
|
|
408
|
-
"sampled": len(nodes),
|
|
409
|
-
"stale_nodes": len(stale),
|
|
410
|
-
"stale_threshold_days": _STALE_DAYS,
|
|
411
|
-
}
|
|
412
|
-
else:
|
|
413
|
-
dimensions["freshness"] = {
|
|
414
|
-
"status": "unavailable",
|
|
415
|
-
"score": None,
|
|
416
|
-
"reason": _no_graph_reason(sample["available"]),
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
# Connectivity — orphan nodes are knowledge the Brain cannot reason
|
|
420
|
-
# across; a well-tended graph keeps them rare.
|
|
421
|
-
if sample["available"] and nodes:
|
|
422
|
-
connected = set()
|
|
423
|
-
for edge in edges:
|
|
424
|
-
connected.add(str(edge.get("source") or edge.get("from_node") or ""))
|
|
425
|
-
connected.add(str(edge.get("target") or edge.get("to_node") or ""))
|
|
426
|
-
orphans = [n for n in nodes if str(n.get("id")) not in connected]
|
|
427
|
-
ratio = 1.0 - (len(orphans) / len(nodes))
|
|
428
|
-
dimensions["connectivity"] = {
|
|
429
|
-
"status": "ok",
|
|
430
|
-
"score": round(ratio * 100),
|
|
431
|
-
"sampled": len(nodes),
|
|
432
|
-
"orphan_nodes": len(orphans),
|
|
433
|
-
"edges": len(edges),
|
|
434
|
-
}
|
|
435
|
-
else:
|
|
436
|
-
dimensions["connectivity"] = {
|
|
437
|
-
"status": "unavailable",
|
|
438
|
-
"score": None,
|
|
439
|
-
"reason": _no_graph_reason(sample["available"]),
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
# Embedding coverage — semantic recall only works for indexed items.
|
|
443
|
-
index_status: Dict[str, Any] = {}
|
|
444
|
-
if self._enable_graph and hasattr(self._kg, "index_status"):
|
|
445
|
-
try:
|
|
446
|
-
index_status = self._kg.index_status()
|
|
447
|
-
except Exception as exc:
|
|
448
|
-
LOGGER.exception("brain intelligence index status failed")
|
|
449
|
-
index_status = {"error": str(exc)}
|
|
450
|
-
scale = index_status.get("scale") or {}
|
|
451
|
-
indexable = scale.get("source_items", index_status.get("source_items"))
|
|
452
|
-
if "coverage_ratio" not in scale:
|
|
453
|
-
dimensions["embedding_coverage"] = {
|
|
454
|
-
"status": "unavailable",
|
|
455
|
-
"score": None,
|
|
456
|
-
"reason": "this knowledge store does not report vector index coverage",
|
|
457
|
-
}
|
|
458
|
-
elif indexable == 0:
|
|
459
|
-
# An empty index covers 100% of nothing. Scoring that as a perfect
|
|
460
|
-
# 100 is how a brand-new Brain used to grade itself "excellent"
|
|
461
|
-
# off its only measurable dimension (audit v11.2.0, Finding 3).
|
|
462
|
-
dimensions["embedding_coverage"] = {
|
|
463
|
-
"status": "unavailable",
|
|
464
|
-
"score": None,
|
|
465
|
-
"reason": "no indexable items yet",
|
|
466
|
-
}
|
|
467
|
-
else:
|
|
468
|
-
dimensions["embedding_coverage"] = {
|
|
469
|
-
"status": "ok",
|
|
470
|
-
"score": round(float(scale["coverage_ratio"]) * 100),
|
|
471
|
-
"ready_items": scale.get("ready_items"),
|
|
472
|
-
"pending_items": scale.get("pending_items"),
|
|
473
|
-
"needs_reindex": index_status.get("status") == "needs_reindex",
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
# Edge quality + contradiction pressure — reuses the quality layer.
|
|
477
|
-
if sample["available"] and edges:
|
|
478
|
-
metrics = self._edge_quality.compute_quality_metrics(edges)
|
|
479
|
-
contradiction_edges = [
|
|
480
|
-
e for e in edges if "CONTRADICT" in str(e.get("type") or "").upper()
|
|
481
|
-
]
|
|
482
|
-
pressure = min(1.0, metrics.get("dup_rate", 0.0) + len(contradiction_edges) / max(len(edges), 1))
|
|
483
|
-
dimensions["consistency"] = {
|
|
484
|
-
"status": "ok",
|
|
485
|
-
"score": round((1.0 - pressure) * 100),
|
|
486
|
-
"edge_metrics": metrics,
|
|
487
|
-
"contradiction_edges": len(contradiction_edges),
|
|
488
|
-
}
|
|
489
|
-
else:
|
|
490
|
-
dimensions["consistency"] = {
|
|
491
|
-
"status": "unavailable",
|
|
492
|
-
"score": None,
|
|
493
|
-
"reason": (
|
|
494
|
-
_no_graph_reason(sample["available"])
|
|
495
|
-
if not (sample["available"] and nodes)
|
|
496
|
-
else "no relationships recorded yet"
|
|
497
|
-
),
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
scores = [d["score"] for d in dimensions.values() if d.get("score") is not None]
|
|
501
|
-
overall = round(sum(scores) / len(scores)) if scores else None
|
|
502
|
-
grade = (
|
|
503
|
-
None if overall is None
|
|
504
|
-
else "excellent" if overall >= 85
|
|
505
|
-
else "good" if overall >= 70
|
|
506
|
-
else "attention" if overall >= 50
|
|
507
|
-
else "critical"
|
|
508
|
-
)
|
|
509
|
-
# What the verdict rests on. A composite averages only what could be
|
|
510
|
-
# measured, so the count of measured dimensions is part of the answer
|
|
511
|
-
# rather than a footnote — and when nothing could be measured the
|
|
512
|
-
# report says so instead of leaving a bare null (the 9.9.7 rule: a
|
|
513
|
-
# "—" always states why).
|
|
514
|
-
unmeasured = sorted(
|
|
515
|
-
name for name, dim in dimensions.items() if dim.get("score") is None
|
|
516
|
-
)
|
|
517
|
-
coverage: Dict[str, Any] = {
|
|
518
|
-
"measured": len(scores),
|
|
519
|
-
"total": len(dimensions),
|
|
520
|
-
"unavailable": unmeasured,
|
|
521
|
-
"partial": bool(unmeasured),
|
|
522
|
-
}
|
|
523
|
-
reason: Optional[str] = None
|
|
524
|
-
if overall is None:
|
|
525
|
-
reason = (
|
|
526
|
-
"no health dimension could be measured yet — "
|
|
527
|
-
+ "; ".join(
|
|
528
|
-
f"{name}: {dimensions[name].get('reason') or 'unavailable'}"
|
|
529
|
-
for name in unmeasured
|
|
530
|
-
)
|
|
531
|
-
)
|
|
532
|
-
|
|
533
|
-
actions: List[Dict[str, str]] = []
|
|
534
|
-
emb = dimensions["embedding_coverage"]
|
|
535
|
-
if emb.get("needs_reindex"):
|
|
536
|
-
actions.append({
|
|
537
|
-
"id": "rebuild_vector_index",
|
|
538
|
-
"reason": f"{emb.get('pending_items', 0)} items are missing or stale in the vector index.",
|
|
539
|
-
})
|
|
540
|
-
conn_dim = dimensions["connectivity"]
|
|
541
|
-
conn_score = conn_dim.get("score")
|
|
542
|
-
if conn_score is not None and conn_score < 70:
|
|
543
|
-
actions.append({
|
|
544
|
-
"id": "review_orphans",
|
|
545
|
-
"reason": f"{conn_dim.get('orphan_nodes', 0)} nodes have no relationships.",
|
|
546
|
-
})
|
|
547
|
-
fresh_dim = dimensions["freshness"]
|
|
548
|
-
fresh_score = fresh_dim.get("score")
|
|
549
|
-
if fresh_score is not None and fresh_score < 60:
|
|
550
|
-
actions.append({
|
|
551
|
-
"id": "refresh_stale_knowledge",
|
|
552
|
-
"reason": f"{fresh_dim.get('stale_nodes', 0)} nodes untouched for over {_STALE_DAYS} days.",
|
|
553
|
-
})
|
|
554
|
-
cons_dim = dimensions["consistency"]
|
|
555
|
-
if cons_dim.get("contradiction_edges"):
|
|
556
|
-
actions.append({
|
|
557
|
-
"id": "resolve_contradictions",
|
|
558
|
-
"reason": f"{cons_dim['contradiction_edges']} contradiction edges recorded in the graph.",
|
|
559
|
-
})
|
|
560
|
-
|
|
561
|
-
report: Dict[str, Any] = {
|
|
562
|
-
"overall_score": overall,
|
|
563
|
-
"grade": grade,
|
|
564
|
-
"dimensions": dimensions,
|
|
565
|
-
"coverage": coverage,
|
|
566
|
-
"recommended_actions": actions,
|
|
567
|
-
"graph_available": sample["available"],
|
|
568
|
-
"generated_at": _now(),
|
|
569
|
-
}
|
|
570
|
-
if reason is not None:
|
|
571
|
-
report["reason"] = reason
|
|
572
|
-
return report
|
|
573
|
-
|
|
574
|
-
# ── vector freshness (v9.8.0) ────────────────────────────────────────
|
|
575
|
-
|
|
576
|
-
def vector_freshness(
|
|
577
|
-
self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None
|
|
578
|
-
) -> Dict[str, Any]:
|
|
579
|
-
"""Fixed-contract vector index freshness for ``/api/brain/vector-freshness``.
|
|
580
|
-
|
|
581
|
-
Always returns ``{"status": "ready"|"pending"|"unavailable",
|
|
582
|
-
"pending_items": int, "total_items": int, "detail": str}`` and never
|
|
583
|
-
raises. The vector index is store-global (not workspace-partitioned);
|
|
584
|
-
scope arguments are accepted for router symmetry but do not narrow
|
|
585
|
-
the report.
|
|
586
|
-
|
|
587
|
-
Since v11.2.0 a store that can split its backlog also gets a
|
|
588
|
-
``breakdown`` key (see :meth:`_freshness_breakdown`). It is additive:
|
|
589
|
-
the four keys above keep their meaning and their types, so the
|
|
590
|
-
freshness chip that reads ``pending_items`` is untouched, and a store
|
|
591
|
-
without the split simply has no ``breakdown``.
|
|
592
|
-
"""
|
|
593
|
-
payload = self._vector_freshness_contract()
|
|
594
|
-
breakdown = self._freshness_breakdown()
|
|
595
|
-
if breakdown is not None:
|
|
596
|
-
payload["breakdown"] = breakdown
|
|
597
|
-
return payload
|
|
598
|
-
|
|
599
|
-
def _freshness_breakdown(self) -> Optional[Dict[str, Any]]:
|
|
600
|
-
"""``vector_freshness_breakdown()`` from the store, or ``None``.
|
|
601
|
-
|
|
602
|
-
"12 pending" hides two different situations — twelve items never
|
|
603
|
-
embedded (a new import) and twelve whose text changed under an
|
|
604
|
-
existing embedding (edits, where current answers are quietly wrong).
|
|
605
|
-
The store has always known the difference; until now nothing asked it.
|
|
606
|
-
|
|
607
|
-
``None`` covers every reason the split is not available (graph off,
|
|
608
|
-
an older store, an unreadable index), because a caller can only act on
|
|
609
|
-
numbers that were really measured — never on zeros standing in for
|
|
610
|
-
them.
|
|
611
|
-
"""
|
|
612
|
-
if not self._enable_graph or self._kg is None:
|
|
613
|
-
return None
|
|
614
|
-
breakdown_fn = getattr(self._kg, "vector_freshness_breakdown", None)
|
|
615
|
-
if not callable(breakdown_fn):
|
|
616
|
-
return None
|
|
617
|
-
try:
|
|
618
|
-
raw = breakdown_fn()
|
|
619
|
-
except Exception:
|
|
620
|
-
LOGGER.exception("vector freshness breakdown read failed")
|
|
621
|
-
return None
|
|
622
|
-
# An empty or unrecognisable answer is "not measured", which is what
|
|
623
|
-
# ``None`` already means here — publishing an empty block would claim
|
|
624
|
-
# a split nobody computed.
|
|
625
|
-
if not isinstance(raw, dict) or not raw:
|
|
626
|
-
return None
|
|
627
|
-
return dict(raw)
|
|
628
|
-
|
|
629
|
-
def _vector_freshness_contract(self) -> Dict[str, Any]:
|
|
630
|
-
"""The four-key freshness payload, unchanged since v9.8.0."""
|
|
631
|
-
|
|
632
|
-
def _unavailable(detail: str) -> Dict[str, Any]:
|
|
633
|
-
return {
|
|
634
|
-
"status": "unavailable",
|
|
635
|
-
"pending_items": 0,
|
|
636
|
-
"total_items": 0,
|
|
637
|
-
"detail": detail,
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
if not self._enable_graph or self._kg is None:
|
|
641
|
-
return _unavailable("knowledge graph is disabled; no vector index is configured")
|
|
642
|
-
|
|
643
|
-
freshness_fn = getattr(self._kg, "vector_freshness", None)
|
|
644
|
-
if callable(freshness_fn):
|
|
645
|
-
try:
|
|
646
|
-
raw = freshness_fn() or {}
|
|
647
|
-
except Exception as exc:
|
|
648
|
-
LOGGER.exception("vector freshness read failed")
|
|
649
|
-
return _unavailable(f"vector freshness read failed: {exc}")
|
|
650
|
-
status = str(raw.get("status") or "unavailable")
|
|
651
|
-
if status == "needs_reindex":
|
|
652
|
-
status = "pending"
|
|
653
|
-
if status not in {"ready", "pending", "unavailable"}:
|
|
654
|
-
status = "unavailable"
|
|
655
|
-
return {
|
|
656
|
-
"status": status,
|
|
657
|
-
"pending_items": int(raw.get("pending_items") or 0),
|
|
658
|
-
"total_items": int(raw.get("total_items") or 0),
|
|
659
|
-
"detail": str(raw.get("detail") or ""),
|
|
660
|
-
}
|
|
661
|
-
|
|
662
|
-
# Older/lighter stores: summarize index_status directly.
|
|
663
|
-
status_fn = getattr(self._kg, "index_status", None)
|
|
664
|
-
if callable(status_fn):
|
|
665
|
-
try:
|
|
666
|
-
raw = status_fn() or {}
|
|
667
|
-
except Exception as exc:
|
|
668
|
-
LOGGER.exception("vector index status read failed")
|
|
669
|
-
return _unavailable(f"vector index status unavailable: {exc}")
|
|
670
|
-
pending = int(raw.get("pending_items") or 0)
|
|
671
|
-
total = int(raw.get("source_items") or 0)
|
|
672
|
-
if pending > 0:
|
|
673
|
-
return {
|
|
674
|
-
"status": "pending",
|
|
675
|
-
"pending_items": pending,
|
|
676
|
-
"total_items": total,
|
|
677
|
-
"detail": (
|
|
678
|
-
f"{pending} of {total} items are missing or stale in the vector index"
|
|
679
|
-
),
|
|
680
|
-
}
|
|
681
|
-
return {
|
|
682
|
-
"status": "ready",
|
|
683
|
-
"pending_items": 0,
|
|
684
|
-
"total_items": total,
|
|
685
|
-
"detail": "vector index is up to date",
|
|
686
|
-
}
|
|
687
|
-
|
|
688
|
-
return _unavailable("this knowledge store does not expose a vector index")
|
|
689
|
-
|
|
690
|
-
# ── insights digest ──────────────────────────────────────────────────
|
|
691
|
-
|
|
692
|
-
def insights(
|
|
693
|
-
self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None
|
|
694
|
-
) -> Dict[str, Any]:
|
|
695
|
-
sample = self._graph_sample(workspace_id=workspace_id)
|
|
696
|
-
nodes, edges = sample["nodes"], sample["edges"]
|
|
697
|
-
now = datetime.now(timezone.utc)
|
|
698
|
-
recent_cutoff = now - timedelta(days=_RECENT_DAYS)
|
|
699
|
-
stale_cutoff = now - timedelta(days=_STALE_DAYS)
|
|
700
|
-
|
|
701
|
-
recent_nodes: List[Dict[str, Any]] = []
|
|
702
|
-
stale_nodes: List[Dict[str, Any]] = []
|
|
703
|
-
type_counts: Dict[str, int] = {}
|
|
704
|
-
for node in nodes:
|
|
705
|
-
node_type = str(node.get("type") or "node")
|
|
706
|
-
ts = _parse_ts(node.get("updated_at"))
|
|
707
|
-
if ts is not None and ts >= recent_cutoff:
|
|
708
|
-
recent_nodes.append(node)
|
|
709
|
-
type_counts[node_type] = type_counts.get(node_type, 0) + 1
|
|
710
|
-
elif ts is not None and ts < stale_cutoff:
|
|
711
|
-
stale_nodes.append(node)
|
|
712
|
-
|
|
713
|
-
connected = set()
|
|
714
|
-
for edge in edges:
|
|
715
|
-
connected.add(str(edge.get("source") or edge.get("from_node") or ""))
|
|
716
|
-
connected.add(str(edge.get("target") or edge.get("to_node") or ""))
|
|
717
|
-
orphans = [n for n in nodes if str(n.get("id")) not in connected]
|
|
718
|
-
|
|
719
|
-
def _slim(node: Dict[str, Any]) -> Dict[str, Any]:
|
|
720
|
-
return {
|
|
721
|
-
"id": node.get("id"),
|
|
722
|
-
"type": node.get("type"),
|
|
723
|
-
"title": str(node.get("title") or "")[:120],
|
|
724
|
-
"updated_at": node.get("updated_at"),
|
|
725
|
-
}
|
|
726
|
-
|
|
727
|
-
trending = sorted(type_counts.items(), key=lambda kv: kv[1], reverse=True)[:5]
|
|
728
|
-
suggested_questions = [
|
|
729
|
-
f"{str(node.get('title') or '').strip()[:60]}에 대해 지금까지 알고 있는 것을 정리해줘"
|
|
730
|
-
for node in recent_nodes[:3]
|
|
731
|
-
if str(node.get("title") or "").strip()
|
|
732
|
-
]
|
|
733
|
-
|
|
734
|
-
return {
|
|
735
|
-
"window_days": _RECENT_DAYS,
|
|
736
|
-
"activity": {
|
|
737
|
-
"recent_nodes": len(recent_nodes),
|
|
738
|
-
"recent_samples": [_slim(n) for n in recent_nodes[:8]],
|
|
739
|
-
"trending_types": [{"type": t, "count": c} for t, c in trending],
|
|
740
|
-
},
|
|
741
|
-
"attention": {
|
|
742
|
-
"stale_nodes": len(stale_nodes),
|
|
743
|
-
"stale_samples": [_slim(n) for n in stale_nodes[:8]],
|
|
744
|
-
"orphan_nodes": len(orphans),
|
|
745
|
-
"orphan_samples": [_slim(n) for n in orphans[:8]],
|
|
746
|
-
},
|
|
747
|
-
"suggested_questions": suggested_questions,
|
|
748
|
-
"graph_available": sample["available"],
|
|
749
|
-
"generated_at": _now(),
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
def garden_overview(
|
|
753
|
-
self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None,
|
|
754
|
-
limit: int = 8,
|
|
755
|
-
) -> Dict[str, Any]:
|
|
756
|
-
"""The knowledge garden in four beds (v9.9.7).
|
|
757
|
-
|
|
758
|
-
Living Brain answers "how healthy is my knowledge?" in aggregate.
|
|
759
|
-
A gardener asks four concrete questions instead, and this answers all
|
|
760
|
-
four from one workspace-scoped graph sample plus the memory tier:
|
|
761
|
-
|
|
762
|
-
* **recent** — what came in lately (the garden's new growth);
|
|
763
|
-
* **contradictions** — what disagrees with itself (needs weeding);
|
|
764
|
-
* **stale** — what has not been touched in a long time;
|
|
765
|
-
* **frequent** — what the rest of the graph leans on most (by degree).
|
|
766
|
-
|
|
767
|
-
Read-only and honest: when the graph is unavailable every bed is empty
|
|
768
|
-
and ``available`` is false — the view never invents plants.
|
|
769
|
-
"""
|
|
770
|
-
# Explicit 0 clamps to 1 — `limit or 8` would silently re-expand it.
|
|
771
|
-
try:
|
|
772
|
-
limit = max(1, min(int(limit), 50))
|
|
773
|
-
except (TypeError, ValueError):
|
|
774
|
-
limit = 8
|
|
775
|
-
sample = self._graph_sample(workspace_id=workspace_id)
|
|
776
|
-
nodes, edges = sample["nodes"], sample["edges"]
|
|
777
|
-
now = datetime.now(timezone.utc)
|
|
778
|
-
recent_cutoff = now - timedelta(days=_RECENT_DAYS)
|
|
779
|
-
stale_cutoff = now - timedelta(days=_STALE_DAYS)
|
|
780
|
-
|
|
781
|
-
def _slim(node: Dict[str, Any], **extra: Any) -> Dict[str, Any]:
|
|
782
|
-
return {
|
|
783
|
-
"id": node.get("id"),
|
|
784
|
-
"type": node.get("type"),
|
|
785
|
-
"title": str(node.get("title") or "")[:120],
|
|
786
|
-
"updated_at": node.get("updated_at"),
|
|
787
|
-
**extra,
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
recent: List[Dict[str, Any]] = []
|
|
791
|
-
stale: List[Dict[str, Any]] = []
|
|
792
|
-
for node in nodes:
|
|
793
|
-
# Chunks are retrieval plumbing, not knowledge a gardener tends.
|
|
794
|
-
if str(node.get("type") or "") == "Chunk":
|
|
795
|
-
continue
|
|
796
|
-
ts = _parse_ts(node.get("updated_at"))
|
|
797
|
-
if ts is None:
|
|
798
|
-
continue
|
|
799
|
-
if ts >= recent_cutoff:
|
|
800
|
-
recent.append(node)
|
|
801
|
-
elif ts < stale_cutoff:
|
|
802
|
-
stale.append(node)
|
|
803
|
-
recent.sort(key=lambda n: str(n.get("updated_at") or ""), reverse=True)
|
|
804
|
-
stale.sort(key=lambda n: str(n.get("updated_at") or ""))
|
|
805
|
-
|
|
806
|
-
# "Frequent" is degree, not a guess: how many relations actually point
|
|
807
|
-
# at a node. Chunks are retrieval plumbing, never garden plants.
|
|
808
|
-
degree: Dict[str, int] = {}
|
|
809
|
-
for edge in edges:
|
|
810
|
-
for key in ("source", "target"):
|
|
811
|
-
node_id = str(edge.get(key) or "")
|
|
812
|
-
if node_id:
|
|
813
|
-
degree[node_id] = degree.get(node_id, 0) + 1
|
|
814
|
-
by_id = {str(node.get("id")): node for node in nodes}
|
|
815
|
-
frequent = [
|
|
816
|
-
_slim(by_id[node_id], degree=count)
|
|
817
|
-
for node_id, count in sorted(degree.items(), key=lambda kv: kv[1], reverse=True)
|
|
818
|
-
if node_id in by_id and str(by_id[node_id].get("type") or "") != "Chunk"
|
|
819
|
-
][:limit]
|
|
820
|
-
|
|
821
|
-
contradiction_items: List[Dict[str, Any]] = []
|
|
822
|
-
contradiction_count = 0
|
|
823
|
-
try:
|
|
824
|
-
found = self.contradictions(user_email=user_email, workspace_id=workspace_id)
|
|
825
|
-
items = found.get("items") if isinstance(found, dict) else None
|
|
826
|
-
if isinstance(items, list):
|
|
827
|
-
contradiction_count = len(items)
|
|
828
|
-
contradiction_items = items[:limit]
|
|
829
|
-
except Exception: # noqa: BLE001 — one empty bed, never a broken view
|
|
830
|
-
LOGGER.exception("garden overview contradictions failed")
|
|
831
|
-
|
|
832
|
-
return {
|
|
833
|
-
"available": sample["available"],
|
|
834
|
-
"window_days": _RECENT_DAYS,
|
|
835
|
-
"stale_threshold_days": _STALE_DAYS,
|
|
836
|
-
"beds": {
|
|
837
|
-
"recent": {
|
|
838
|
-
"count": len(recent),
|
|
839
|
-
"items": [_slim(node) for node in recent[:limit]],
|
|
840
|
-
},
|
|
841
|
-
"contradictions": {
|
|
842
|
-
"count": contradiction_count,
|
|
843
|
-
"items": contradiction_items,
|
|
844
|
-
},
|
|
845
|
-
"stale": {
|
|
846
|
-
"count": len(stale),
|
|
847
|
-
"items": [_slim(node) for node in stale[:limit]],
|
|
848
|
-
},
|
|
849
|
-
"frequent": {
|
|
850
|
-
"count": len(frequent),
|
|
851
|
-
"items": frequent,
|
|
852
|
-
},
|
|
853
|
-
},
|
|
854
|
-
"generated_at": _now(),
|
|
855
|
-
}
|
|
856
|
-
|
|
857
|
-
# ── graph-layer proactive quality (v9.6.x) ───────────────────────────
|
|
858
|
-
|
|
859
|
-
def graph_duplicates(
|
|
860
|
-
self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None
|
|
861
|
-
) -> Dict[str, Any]:
|
|
862
|
-
"""Duplicate graph nodes (exact groups + near pairs) — read only."""
|
|
863
|
-
proactive = self._proactive()
|
|
864
|
-
if proactive is None:
|
|
865
|
-
return {
|
|
866
|
-
"available": False,
|
|
867
|
-
"exact_groups": [],
|
|
868
|
-
"near_pairs": [],
|
|
869
|
-
"exact_duplicate_nodes": 0,
|
|
870
|
-
"nodes_scanned": 0,
|
|
871
|
-
"generated_at": _now(),
|
|
872
|
-
}
|
|
873
|
-
try:
|
|
874
|
-
result = dict(proactive.find_duplicates(workspace_id=workspace_id))
|
|
875
|
-
except Exception as exc:
|
|
876
|
-
LOGGER.exception("graph duplicates scan failed")
|
|
877
|
-
return {
|
|
878
|
-
"available": False,
|
|
879
|
-
"error": str(exc),
|
|
880
|
-
"exact_groups": [],
|
|
881
|
-
"near_pairs": [],
|
|
882
|
-
"exact_duplicate_nodes": 0,
|
|
883
|
-
"nodes_scanned": 0,
|
|
884
|
-
"generated_at": _now(),
|
|
885
|
-
}
|
|
886
|
-
result["available"] = True
|
|
887
|
-
result["generated_at"] = _now()
|
|
888
|
-
return result
|
|
889
|
-
|
|
890
|
-
def quality_report(
|
|
891
|
-
self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None
|
|
892
|
-
) -> Dict[str, Any]:
|
|
893
|
-
"""Combined graph quality report: duplicates, contradictions, stale
|
|
894
|
-
nodes, edge quality — one workspace-scoped graph sample."""
|
|
895
|
-
proactive = self._proactive()
|
|
896
|
-
if proactive is None:
|
|
897
|
-
return {"available": False, "generated_at": _now()}
|
|
898
|
-
try:
|
|
899
|
-
result = dict(proactive.quality_report(workspace_id=workspace_id))
|
|
900
|
-
except Exception as exc:
|
|
901
|
-
LOGGER.exception("graph quality report failed")
|
|
902
|
-
return {"available": False, "error": str(exc), "generated_at": _now()}
|
|
903
|
-
result["available"] = True
|
|
904
|
-
# v11.1.0: decay is part of quality, and "the Brain is tidying up" is a
|
|
905
|
-
# state the user is entitled to see rather than a background surprise.
|
|
906
|
-
importance = self.importance_report(
|
|
907
|
-
user_email=user_email, workspace_id=workspace_id
|
|
908
|
-
)
|
|
909
|
-
candidates = len(importance.get("candidates") or [])
|
|
910
|
-
result["importance"] = importance
|
|
911
|
-
result["tidying"] = bool(importance.get("available")) and candidates > 0
|
|
912
|
-
summary = dict(result.get("summary") or {})
|
|
913
|
-
summary["consolidation_candidates"] = candidates
|
|
914
|
-
result["summary"] = summary
|
|
915
|
-
result["generated_at"] = _now()
|
|
916
|
-
return result
|
|
917
|
-
|
|
918
|
-
# ── contradictions ───────────────────────────────────────────────────
|
|
919
|
-
|
|
920
|
-
def contradictions(
|
|
921
|
-
self, *, user_email: Optional[str] = None, workspace_id: Optional[str] = None
|
|
922
|
-
) -> Dict[str, Any]:
|
|
923
|
-
memories = self._workspace_memories(user_email=user_email, workspace_id=workspace_id)
|
|
924
|
-
memory_rows = [
|
|
925
|
-
{
|
|
926
|
-
"id": str(m.get("id") or f"mem-{i}"),
|
|
927
|
-
"content": str(m.get("content") or ""),
|
|
928
|
-
"score": 0.6,
|
|
929
|
-
"source": "workspace",
|
|
930
|
-
"timestamp": m.get("created_at") or m.get("timestamp") or 0,
|
|
931
|
-
}
|
|
932
|
-
for i, m in enumerate(memories)
|
|
933
|
-
if str(m.get("content") or "").strip()
|
|
934
|
-
]
|
|
935
|
-
|
|
936
|
-
conflicts: List[Dict[str, Any]] = []
|
|
937
|
-
candidates = self._memory_quality.extract_candidates(memory_rows)
|
|
938
|
-
for candidate in self._memory_quality.detect_conflicts(candidates):
|
|
939
|
-
pair_conflicts = [c for c in candidate.conflicts if c.startswith("conflict:contradicts:")]
|
|
940
|
-
for marker in pair_conflicts:
|
|
941
|
-
other_id = marker.rsplit(":", 1)[-1]
|
|
942
|
-
if any(
|
|
943
|
-
c["kind"] == "memory_pair"
|
|
944
|
-
and {c["left_id"], c["right_id"]} == {candidate.id, other_id}
|
|
945
|
-
for c in conflicts
|
|
946
|
-
):
|
|
947
|
-
continue
|
|
948
|
-
other: Dict[str, Any] | None = next(
|
|
949
|
-
(r for r in memory_rows if r["id"] == other_id), None
|
|
950
|
-
)
|
|
951
|
-
conflicts.append({
|
|
952
|
-
"kind": "memory_pair",
|
|
953
|
-
"left_id": candidate.id,
|
|
954
|
-
"left_content": candidate.content[:200],
|
|
955
|
-
"right_id": other_id,
|
|
956
|
-
"right_content": (other or {}).get("content", "")[:200],
|
|
957
|
-
"signal": "preference_negation",
|
|
958
|
-
})
|
|
959
|
-
|
|
960
|
-
temporal = self._memory_quality.detect_temporal_contradictions(memory_rows)
|
|
961
|
-
temporal_items = [
|
|
962
|
-
{
|
|
963
|
-
"kind": "temporal",
|
|
964
|
-
"id": item.get("id"),
|
|
965
|
-
"content": str(item.get("content") or "")[:200],
|
|
966
|
-
"signal": item.get("proactive_flag"),
|
|
967
|
-
}
|
|
968
|
-
for item in temporal
|
|
969
|
-
]
|
|
970
|
-
|
|
971
|
-
edge_items: List[Dict[str, Any]] = []
|
|
972
|
-
sample = self._graph_sample(workspace_id=workspace_id)
|
|
973
|
-
for edge in sample["edges"]:
|
|
974
|
-
if "CONTRADICT" in str(edge.get("type") or "").upper():
|
|
975
|
-
edge_items.append({
|
|
976
|
-
"kind": "graph_edge",
|
|
977
|
-
"id": edge.get("id"),
|
|
978
|
-
"source": edge.get("source") or edge.get("from_node"),
|
|
979
|
-
"target": edge.get("target") or edge.get("to_node"),
|
|
980
|
-
"signal": "contradicts_edge",
|
|
981
|
-
})
|
|
982
|
-
|
|
983
|
-
# v9.6.x additive: graph-layer node-content contradictions (proactive
|
|
984
|
-
# detector over node title/summary), on top of the memory + edge scans.
|
|
985
|
-
graph_pair_items: List[Dict[str, Any]] = []
|
|
986
|
-
proactive = self._proactive()
|
|
987
|
-
if proactive is not None:
|
|
988
|
-
try:
|
|
989
|
-
graph_result = proactive.detect_contradictions(workspace_id=workspace_id)
|
|
990
|
-
graph_pair_items = [
|
|
991
|
-
{"kind": "graph_node_pair", **pair}
|
|
992
|
-
for pair in graph_result.get("node_pairs") or []
|
|
993
|
-
]
|
|
994
|
-
except Exception:
|
|
995
|
-
LOGGER.exception("graph contradiction scan failed")
|
|
996
|
-
|
|
997
|
-
items = conflicts + temporal_items + edge_items + graph_pair_items
|
|
998
|
-
return {
|
|
999
|
-
"items": items,
|
|
1000
|
-
"count": len(items),
|
|
1001
|
-
"sources": {
|
|
1002
|
-
"memory_pairs": len(conflicts),
|
|
1003
|
-
"temporal": len(temporal_items),
|
|
1004
|
-
"graph_edges": len(edge_items),
|
|
1005
|
-
"graph_node_pairs": len(graph_pair_items),
|
|
1006
|
-
},
|
|
1007
|
-
"memories_scanned": len(memory_rows),
|
|
1008
|
-
"generated_at": _now(),
|
|
1009
|
-
}
|
|
1010
|
-
|
|
1011
|
-
# ── consolidation ────────────────────────────────────────────────────
|
|
1012
|
-
|
|
1013
|
-
def consolidate(
|
|
1014
|
-
self,
|
|
1015
|
-
*,
|
|
1016
|
-
apply: bool = False,
|
|
1017
|
-
user_email: Optional[str] = None,
|
|
1018
|
-
workspace_id: Optional[str] = None,
|
|
1019
|
-
) -> Dict[str, Any]:
|
|
1020
|
-
memories = self._workspace_memories(user_email=user_email, workspace_id=workspace_id)
|
|
1021
|
-
memory_rows = [
|
|
1022
|
-
{
|
|
1023
|
-
"id": str(m.get("id") or f"mem-{i}"),
|
|
1024
|
-
"content": str(m.get("content") or ""),
|
|
1025
|
-
"score": 0.6,
|
|
1026
|
-
"source": "workspace",
|
|
1027
|
-
}
|
|
1028
|
-
for i, m in enumerate(memories)
|
|
1029
|
-
if str(m.get("content") or "").strip()
|
|
1030
|
-
]
|
|
1031
|
-
candidates = self._memory_quality.extract_candidates(memory_rows)
|
|
1032
|
-
kept = self._memory_quality.dedupe(candidates)
|
|
1033
|
-
kept_ids = {c.id for c in kept}
|
|
1034
|
-
duplicate_memory_ids = [c.id for c in candidates if c.id not in kept_ids]
|
|
1035
|
-
|
|
1036
|
-
sample = self._graph_sample(workspace_id=workspace_id)
|
|
1037
|
-
duplicate_edge_ids = [
|
|
1038
|
-
edge_id
|
|
1039
|
-
for edge_id in self._edge_quality.detect_duplicate_edges(sample["edges"])
|
|
1040
|
-
if edge_id
|
|
1041
|
-
]
|
|
1042
|
-
|
|
1043
|
-
pruned = 0
|
|
1044
|
-
if apply and duplicate_memory_ids and self._memory is not None:
|
|
1045
|
-
try:
|
|
1046
|
-
result = self._memory.prune(
|
|
1047
|
-
ids=duplicate_memory_ids,
|
|
1048
|
-
user_email=user_email,
|
|
1049
|
-
workspace_id=workspace_id,
|
|
1050
|
-
)
|
|
1051
|
-
pruned = int(result.get("count") or 0)
|
|
1052
|
-
except Exception:
|
|
1053
|
-
LOGGER.exception("consolidation prune failed")
|
|
1054
|
-
|
|
1055
|
-
# v9.6.x additive: graph-layer node merge plan. Always dry-run from
|
|
1056
|
-
# this service — graph content changes stay proposal-first; the plan
|
|
1057
|
-
# is surfaced so a governed apply path can adopt it later.
|
|
1058
|
-
graph_consolidation: Optional[Dict[str, Any]] = None
|
|
1059
|
-
proactive = self._proactive()
|
|
1060
|
-
if proactive is not None:
|
|
1061
|
-
try:
|
|
1062
|
-
graph_consolidation = proactive.consolidate_duplicates(
|
|
1063
|
-
workspace_id=workspace_id, dry_run=True
|
|
1064
|
-
)
|
|
1065
|
-
except Exception:
|
|
1066
|
-
LOGGER.exception("graph consolidation plan failed")
|
|
1067
|
-
|
|
1068
|
-
return {
|
|
1069
|
-
"mode": "applied" if apply else "dry_run",
|
|
1070
|
-
"memories_scanned": len(memory_rows),
|
|
1071
|
-
"duplicate_memories": duplicate_memory_ids,
|
|
1072
|
-
"duplicate_memory_count": len(duplicate_memory_ids),
|
|
1073
|
-
"pruned": pruned,
|
|
1074
|
-
# Graph edges are reported for review only; consolidation never
|
|
1075
|
-
# mutates graph content directly.
|
|
1076
|
-
"duplicate_edges": duplicate_edge_ids[:50],
|
|
1077
|
-
"duplicate_edge_count": len(duplicate_edge_ids),
|
|
1078
|
-
"graph_consolidation": graph_consolidation,
|
|
1079
|
-
"generated_at": _now(),
|
|
1080
|
-
}
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
__all__ = ["BrainIntelligenceService"]
|