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.
Files changed (247) hide show
  1. package/README.md +46 -53
  2. package/docs/CHANGELOG.md +61 -0
  3. package/docs/COMMUNITY_AND_PLUGINS.md +1 -1
  4. package/docs/DEVELOPMENT.md +1 -1
  5. package/docs/MULTI_AGENT_RUNTIME.md +1 -1
  6. package/docs/ONBOARDING.md +1 -1
  7. package/docs/OPERATIONS.md +6 -2
  8. package/docs/PERMISSION_MODE.md +1 -1
  9. package/docs/TRUST_MODEL.md +1 -1
  10. package/docs/WHY_LATTICE.md +1 -1
  11. package/docs/kg-schema.md +2 -2
  12. package/docs/v11.3.0_PLAN.md +202 -0
  13. package/docs/v11.4.0_RUST_FOUNDATION_PLAN.md +176 -0
  14. package/lattice_brain/__init__.py +1 -1
  15. package/lattice_brain/graph/_kg_common/__init__.py +287 -0
  16. package/lattice_brain/graph/_kg_common/extraction.py +516 -0
  17. package/lattice_brain/graph/_kg_common/relations.py +161 -0
  18. package/lattice_brain/graph/_kg_common/text.py +479 -0
  19. package/lattice_brain/graph/discovery_index/__init__.py +35 -0
  20. package/lattice_brain/graph/discovery_index/cleanup.py +182 -0
  21. package/lattice_brain/graph/discovery_index/extract.py +137 -0
  22. package/lattice_brain/graph/discovery_index/scan.py +411 -0
  23. package/lattice_brain/graph/discovery_index/upsert.py +495 -0
  24. package/lattice_brain/graph/projection/__init__.py +42 -0
  25. package/lattice_brain/graph/projection/curation.py +500 -0
  26. package/lattice_brain/graph/{projection.py → projection/v2_schema.py} +15 -477
  27. package/lattice_brain/graph/retrieval/__init__.py +54 -0
  28. package/lattice_brain/graph/retrieval/context.py +197 -0
  29. package/lattice_brain/graph/retrieval/graph_view.py +319 -0
  30. package/lattice_brain/graph/retrieval/hybrid.py +488 -0
  31. package/lattice_brain/graph/retrieval/maintenance.py +121 -0
  32. package/lattice_brain/graph/retrieval/signals.py +95 -0
  33. package/lattice_brain/graph/retrieval_vector/__init__.py +42 -0
  34. package/lattice_brain/graph/retrieval_vector/fingerprint.py +97 -0
  35. package/lattice_brain/graph/retrieval_vector/indexing.py +347 -0
  36. package/lattice_brain/graph/retrieval_vector/search.py +560 -0
  37. package/lattice_brain/graph/retrieval_vector/status.py +374 -0
  38. package/lattice_brain/ingestion/__init__.py +130 -0
  39. package/lattice_brain/ingestion/_contract.py +90 -0
  40. package/lattice_brain/ingestion/constants.py +127 -0
  41. package/lattice_brain/ingestion/folder_scan.py +57 -0
  42. package/lattice_brain/ingestion/folders.py +258 -0
  43. package/lattice_brain/ingestion/hashing.py +26 -0
  44. package/lattice_brain/ingestion/jobs_api.py +107 -0
  45. package/lattice_brain/ingestion/models.py +80 -0
  46. package/lattice_brain/ingestion/pipeline.py +486 -0
  47. package/lattice_brain/ingestion/quality.py +209 -0
  48. package/lattice_brain/ingestion/routing.py +295 -0
  49. package/lattice_brain/multimodal/__init__.py +164 -0
  50. package/lattice_brain/multimodal/audio.py +77 -0
  51. package/lattice_brain/multimodal/common.py +118 -0
  52. package/lattice_brain/multimodal/images.py +498 -0
  53. package/lattice_brain/multimodal/ports.py +169 -0
  54. package/lattice_brain/multimodal/video.py +410 -0
  55. package/lattice_brain/portability/__init__.py +90 -0
  56. package/lattice_brain/portability/_contract.py +42 -0
  57. package/lattice_brain/portability/backups.py +338 -0
  58. package/lattice_brain/portability/bundles.py +136 -0
  59. package/lattice_brain/portability/constants.py +93 -0
  60. package/lattice_brain/portability/fsops.py +138 -0
  61. package/lattice_brain/portability/service.py +41 -0
  62. package/lattice_brain/{portability.py → portability/sharing.py} +44 -677
  63. package/lattice_brain/runtime/__init__.py +1 -1
  64. package/lattice_brain/runtime/multi_agent.py +1 -1
  65. package/latticeai/__init__.py +1 -1
  66. package/latticeai/api/chronicle.py +63 -0
  67. package/latticeai/core/agent/__init__.py +93 -0
  68. package/latticeai/core/agent/_contract.py +79 -0
  69. package/latticeai/core/agent/context.py +57 -0
  70. package/latticeai/core/agent/deps.py +125 -0
  71. package/latticeai/core/agent/execution.py +622 -0
  72. package/latticeai/core/agent/planning.py +145 -0
  73. package/latticeai/core/agent/recovery.py +157 -0
  74. package/latticeai/core/agent/runtime.py +210 -0
  75. package/latticeai/core/agent/verification.py +231 -0
  76. package/latticeai/core/embedding_providers/__init__.py +151 -0
  77. package/latticeai/core/embedding_providers/base.py +199 -0
  78. package/latticeai/core/embedding_providers/captions.py +162 -0
  79. package/latticeai/core/embedding_providers/profiles.py +126 -0
  80. package/latticeai/core/embedding_providers/text.py +350 -0
  81. package/latticeai/core/embedding_providers/vision.py +352 -0
  82. package/latticeai/core/file_generation/__init__.py +115 -0
  83. package/latticeai/core/file_generation/bundles.py +76 -0
  84. package/latticeai/core/file_generation/extraction.py +154 -0
  85. package/latticeai/core/file_generation/inference.py +235 -0
  86. package/latticeai/core/file_generation/orchestration.py +152 -0
  87. package/latticeai/core/file_generation/prompting.py +117 -0
  88. package/latticeai/core/file_generation/repair.py +114 -0
  89. package/latticeai/core/file_generation/sanitize.py +61 -0
  90. package/latticeai/core/file_generation/validation.py +201 -0
  91. package/latticeai/core/legacy_compatibility.py +1 -1
  92. package/latticeai/core/marketplace.py +1 -1
  93. package/latticeai/core/messages.py +9 -0
  94. package/latticeai/core/workspace_os_constants.py +1 -1
  95. package/latticeai/integrations/telegram_bot/__init__.py +123 -0
  96. package/latticeai/integrations/telegram_bot/__main__.py +17 -0
  97. package/latticeai/integrations/telegram_bot/config.py +86 -0
  98. package/latticeai/integrations/telegram_bot/dispatch.py +311 -0
  99. package/latticeai/integrations/telegram_bot/flows.py +478 -0
  100. package/latticeai/integrations/telegram_bot/helpers.py +322 -0
  101. package/latticeai/integrations/telegram_bot/screens.py +394 -0
  102. package/latticeai/models/router/__init__.py +88 -0
  103. package/latticeai/models/router/_contract.py +66 -0
  104. package/latticeai/models/router/branding.py +56 -0
  105. package/latticeai/models/router/catalog.py +69 -0
  106. package/latticeai/models/router/documents.py +199 -0
  107. package/latticeai/models/router/errors.py +37 -0
  108. package/latticeai/models/router/generation.py +258 -0
  109. package/latticeai/models/router/loading.py +291 -0
  110. package/latticeai/models/router/local_models.py +85 -0
  111. package/latticeai/models/router/registry.py +147 -0
  112. package/latticeai/runtime/build_phases/__init__.py +82 -0
  113. package/latticeai/runtime/build_phases/features.py +407 -0
  114. package/latticeai/runtime/build_phases/foundation.py +555 -0
  115. package/latticeai/runtime/build_phases/web.py +492 -0
  116. package/latticeai/runtime/runtime_context.py +1 -0
  117. package/latticeai/services/architecture_readiness.py +48 -19
  118. package/latticeai/services/brain_intelligence/__init__.py +58 -0
  119. package/latticeai/services/brain_intelligence/_contract.py +71 -0
  120. package/latticeai/services/brain_intelligence/consistency.py +193 -0
  121. package/latticeai/services/brain_intelligence/constants.py +47 -0
  122. package/latticeai/services/brain_intelligence/digest.py +258 -0
  123. package/latticeai/services/brain_intelligence/health.py +331 -0
  124. package/latticeai/services/brain_intelligence/proposals.py +264 -0
  125. package/latticeai/services/brain_intelligence/sampling.py +84 -0
  126. package/latticeai/services/brain_intelligence/service.py +48 -0
  127. package/latticeai/services/chronicle.py +557 -0
  128. package/latticeai/services/memory_service/__init__.py +52 -0
  129. package/latticeai/services/memory_service/_contract.py +100 -0
  130. package/latticeai/services/memory_service/brief.py +431 -0
  131. package/latticeai/services/memory_service/constants.py +57 -0
  132. package/latticeai/services/memory_service/maintenance.py +138 -0
  133. package/latticeai/services/memory_service/manager.py +186 -0
  134. package/latticeai/services/memory_service/proof.py +136 -0
  135. package/latticeai/services/memory_service/recall.py +225 -0
  136. package/latticeai/services/memory_service/service.py +48 -0
  137. package/latticeai/services/memory_service/stores.py +110 -0
  138. package/latticeai/services/model_runtime/__init__.py +322 -0
  139. package/latticeai/services/model_runtime/cloud.py +87 -0
  140. package/latticeai/services/model_runtime/download.py +282 -0
  141. package/latticeai/services/model_runtime/engines.py +341 -0
  142. package/latticeai/services/model_runtime/loading.py +178 -0
  143. package/latticeai/services/model_runtime/service.py +129 -0
  144. package/latticeai/services/model_runtime/state.py +131 -0
  145. package/latticeai/services/model_runtime/status.py +255 -0
  146. package/latticeai/services/product_readiness.py +15 -7
  147. package/latticeai/setup/wizard/__init__.py +126 -0
  148. package/latticeai/setup/wizard/catalog.py +172 -0
  149. package/latticeai/setup/wizard/detect.py +323 -0
  150. package/latticeai/setup/wizard/install.py +348 -0
  151. package/latticeai/setup/wizard/paths.py +168 -0
  152. package/latticeai/setup/wizard/plans.py +74 -0
  153. package/latticeai/setup/wizard/recommend.py +320 -0
  154. package/package.json +6 -2
  155. package/scripts/bump_version.py +14 -0
  156. package/scripts/capture_release_evidence.mjs +33 -21
  157. package/scripts/check_current_release_docs.mjs +1 -1
  158. package/scripts/check_i18n_namespace_coverage.mjs +41 -4
  159. package/scripts/check_max_file_lines.mjs +102 -0
  160. package/scripts/check_release_evidence_bound.mjs +30 -15
  161. package/scripts/check_screenshot_pixel_delta.py +34 -4
  162. package/scripts/check_server_i18n.mjs +1 -0
  163. package/scripts/generate_rust_parity_fixtures.py +562 -0
  164. package/scripts/lib/mock_server_fingerprint.mjs +94 -0
  165. package/scripts/release_screen_claims.json +31 -2
  166. package/src-tauri/Cargo.lock +361 -3
  167. package/src-tauri/Cargo.toml +6 -1
  168. package/src-tauri/src/backend.rs +349 -0
  169. package/src-tauri/src/folder.rs +33 -0
  170. package/src-tauri/src/main.rs +97 -399
  171. package/src-tauri/tauri.conf.json +1 -1
  172. package/static/app/asset-manifest.json +41 -37
  173. package/static/app/assets/Act-yYpYnn0v.js +1 -0
  174. package/static/app/assets/AdminConsole-DL3Cr5pL.js +1 -0
  175. package/static/app/assets/{Brain-tuhI4sOC.js → Brain-C1HBN0Wf.js} +2 -2
  176. package/static/app/assets/BrainHome-DoXRhUUC.js +2 -0
  177. package/static/app/assets/BrainSignals-6yR6ir5t.js +1 -0
  178. package/static/app/assets/Capture-CFIRsFNE.js +1 -0
  179. package/static/app/assets/Chronicle-BZbEgiwN.js +1 -0
  180. package/static/app/assets/CommandPalette-D2pMxC2I.js +1 -0
  181. package/static/app/assets/Library-DwO3yZST.js +1 -0
  182. package/static/app/assets/{LivingBrain-DBwhto14.js → LivingBrain-Jn1GK0-S.js} +1 -1
  183. package/static/app/assets/ProductFlow-B-w1R4Oo.js +1 -0
  184. package/static/app/assets/ReviewCard-6B27X8Vg.js +3 -0
  185. package/static/app/assets/System-DW8F-2xL.js +1 -0
  186. package/static/app/assets/arrow-left-DXvKg9U6.js +1 -0
  187. package/static/app/assets/{bot-Cia42c2h.js → bot-IM_E_Y12.js} +1 -1
  188. package/static/app/assets/brain-Ci1CkWjM.js +1 -0
  189. package/static/app/assets/{button-2j2Ijzgq.js → button-COwyqfHM.js} +1 -1
  190. package/static/app/assets/circle-check-DfInj-qD.js +1 -0
  191. package/static/app/assets/{circle-pause-BEFeWpVW.js → circle-pause-DEM4A1Y5.js} +1 -1
  192. package/static/app/assets/{circle-play-ujXMcHxl.js → circle-play-C9djDuLd.js} +1 -1
  193. package/static/app/assets/{cpu-k4awryFq.js → cpu-DFdo1gw-.js} +1 -1
  194. package/static/app/assets/{download-DFbLJ_ig.js → download-SnJL6oqk.js} +1 -1
  195. package/static/app/assets/{folder-open-7y_b6xkM.js → folder-open-CqZeDkjE.js} +1 -1
  196. package/static/app/assets/{hard-drive-Bidh02Kr.js → hard-drive-j1jJXYYf.js} +1 -1
  197. package/static/app/assets/{index-DwDl9-8Y.css → index-BLPb5lmE.css} +1 -1
  198. package/static/app/assets/index-_u5iUHDr.js +10 -0
  199. package/static/app/assets/input-B0lPdRQZ.js +1 -0
  200. package/static/app/assets/link-2-CoFbooHS.js +1 -0
  201. package/static/app/assets/{permissionCopy-Bpb83Hx9.js → permissionCopy-BsyLxtao.js} +1 -1
  202. package/static/app/assets/primitives-DEbN-d6p.js +1 -0
  203. package/static/app/assets/search-BybIWPNd.js +1 -0
  204. package/static/app/assets/{share-2-BH1M-WNi.js → share-2-CVtZ_ewX.js} +1 -1
  205. package/static/app/assets/{shield-alert-BlKdBXcG.js → shield-alert-CBi2GNWM.js} +1 -1
  206. package/static/app/assets/{textarea-CCWbUfFB.js → textarea-DNMpB5ih.js} +1 -1
  207. package/static/app/assets/{useFocusTrap-YdHQ7pJ1.js → useFocusTrap-C83t3GXF.js} +1 -1
  208. package/static/app/assets/useMutation-DtbJDoyz.js +1 -0
  209. package/static/app/assets/{useQuery-CXQiwbVT.js → useQuery-Dcp1OChy.js} +1 -1
  210. package/static/app/assets/utils-BlZr7Pd4.js +4 -0
  211. package/static/app/assets/workspace-jJY4RuAV.js +1 -0
  212. package/static/app/index.html +4 -4
  213. package/static/sw.js +1 -1
  214. package/lattice_brain/graph/_kg_common.py +0 -1331
  215. package/lattice_brain/graph/discovery_index.py +0 -1141
  216. package/lattice_brain/graph/retrieval.py +0 -1120
  217. package/lattice_brain/graph/retrieval_vector.py +0 -1293
  218. package/lattice_brain/ingestion.py +0 -1525
  219. package/lattice_brain/multimodal.py +0 -1258
  220. package/latticeai/core/agent.py +0 -1465
  221. package/latticeai/core/embedding_providers.py +0 -1196
  222. package/latticeai/core/file_generation.py +0 -1047
  223. package/latticeai/integrations/telegram_bot.py +0 -1390
  224. package/latticeai/models/router.py +0 -1007
  225. package/latticeai/runtime/build_phases.py +0 -1450
  226. package/latticeai/services/brain_intelligence.py +0 -1083
  227. package/latticeai/services/memory_service.py +0 -1177
  228. package/latticeai/services/model_runtime.py +0 -1281
  229. package/latticeai/setup/wizard.py +0 -1310
  230. package/static/app/assets/Act-AWf0SAKp.js +0 -1
  231. package/static/app/assets/AdminConsole-D0u8Tiyj.js +0 -1
  232. package/static/app/assets/BrainHome-Ts7G_Ila.js +0 -2
  233. package/static/app/assets/BrainSignals-jMYgQ2Ar.js +0 -1
  234. package/static/app/assets/Capture-CqOSzyPr.js +0 -1
  235. package/static/app/assets/CommandPalette-DC0Bzh-I.js +0 -1
  236. package/static/app/assets/Library-CX-bbhmK.js +0 -1
  237. package/static/app/assets/ProductFlow-BHA2cfKI.js +0 -1
  238. package/static/app/assets/ReviewCard-BUhCKRNM.js +0 -3
  239. package/static/app/assets/System-Bu2t5hn1.js +0 -1
  240. package/static/app/assets/arrow-left-Dzwa5zRb.js +0 -1
  241. package/static/app/assets/brain-DJMoqrwx.js +0 -1
  242. package/static/app/assets/index-BpYkzcVm.js +0 -10
  243. package/static/app/assets/input-DSlJJxRs.js +0 -1
  244. package/static/app/assets/primitives-BCx6TvfG.js +0 -1
  245. package/static/app/assets/search-Cgy8cCFJ.js +0 -1
  246. package/static/app/assets/utils-zqPZJxdx.js +0 -4
  247. package/static/app/assets/workspace-DXTihhfU.js +0 -1
@@ -0,0 +1,500 @@
1
+ """Curation over the projected graph: promotions, the review queue, noise.
2
+
3
+ Two jobs and the queue between them. ``curate`` runs the curator's gated topic
4
+ promotion and either writes it or — in review mode — parks it in ``graph_meta``
5
+ for a human decision; ``curate_noise`` removes heuristic concept nodes whose
6
+ document-frequency stats mark them as noise and normalizes free-string relation
7
+ verbs. Both are explicit and observable: everything skipped is reported with a
8
+ reason, and ``dry_run=True`` is the default for the destructive one.
9
+ """
10
+
11
+ # ruff: noqa: F403,F405,S608
12
+ from __future__ import annotations
13
+
14
+ from typing import TYPE_CHECKING
15
+
16
+ from .._kg_common import * # noqa: F401
17
+
18
+ # The cross-mixin surface (`_connect`, `_upsert_node`, …) is declared in
19
+ # `_kg_contract.KnowledgeGraphCore`. It is a typing-only base: at runtime this
20
+ # is `object`, so the MRO of `KnowledgeGraphStore` is unchanged.
21
+ if TYPE_CHECKING:
22
+ from .._kg_contract import KnowledgeGraphCore as _Core
23
+ else:
24
+ _Core = object
25
+
26
+
27
+ # ── promotion review mode (review 2026-07-25 Wave 4) ─────────────────────────
28
+ # When enabled, curate() parks would-be Topic promotions in graph_meta for a
29
+ # human decision instead of writing them immediately. Explicit review_mode=
30
+ # argument wins; otherwise this env opt-in decides; default stays auto-promote.
31
+ _PROMOTION_REVIEW_ENV = "LATTICEAI_GRAPH_PROMOTION_REVIEW"
32
+ _PENDING_PROMOTIONS_KEY = "pending_promotions"
33
+ _PENDING_PROMOTIONS_CAP = 100
34
+
35
+ # graph_meta stamp written by an applied (dry_run=False) noise-curate run; the
36
+ # Command Center hygiene advisory reads it to pace its suggestion (Wave 2.5).
37
+ _LAST_NOISE_CURATE_KEY = "last_noise_curate_at"
38
+
39
+
40
+ def _promotion_review_default() -> bool:
41
+ return os.getenv(_PROMOTION_REVIEW_ENV, "").strip().lower() in ("1", "true", "yes")
42
+
43
+
44
+ class KnowledgeGraphCurationMixin(_Core):
45
+ """Curation + promotions. Mixed into ``KnowledgeGraphProjectionMixin``."""
46
+
47
+ def curate(
48
+ self,
49
+ *,
50
+ max_documents: int = 200,
51
+ max_new_nodes: int = 8,
52
+ review_mode: Optional[bool] = None,
53
+ ) -> Dict[str, Any]:
54
+ """On-demand graph curation (T4.4 — graph_curator goes live).
55
+
56
+ Runs the curator's gated topic-promotion pipeline over recent content
57
+ nodes: candidates are clustered, secret-bearing labels are refused,
58
+ and only multi-source topics above the importance threshold become
59
+ Topic nodes (with MENTIONS edges back to their sources and a real
60
+ importance_score in nodes_v2). Explicit and observable — the result
61
+ reports everything promoted AND everything skipped, with reasons.
62
+
63
+ ``review_mode`` (review 2026-07-25 Wave 4): when True, nothing is
64
+ written — the would-be promotions are parked in ``graph_meta`` as
65
+ ``pending_promotions`` for a human decision via
66
+ :meth:`apply_pending_promotions` / :meth:`reject_pending_promotions`.
67
+ Explicit argument wins; ``None`` falls back to the
68
+ ``LATTICEAI_GRAPH_PROMOTION_REVIEW`` env opt-in; default stays the
69
+ historical auto-promote behavior.
70
+ """
71
+ from ..curator import auto_build_graph_overlay
72
+
73
+ content_types = (
74
+ "Document",
75
+ "File",
76
+ "CodeFile",
77
+ "Message",
78
+ "AIResponse",
79
+ "Chat",
80
+ "Page",
81
+ "Slide",
82
+ "Spreadsheet",
83
+ )
84
+ nt, _ = self._read_tables()
85
+ with self._connect() as conn:
86
+ placeholders = ",".join("?" for _ in content_types)
87
+ rows = conn.execute(
88
+ f"""
89
+ SELECT id, type, title, summary FROM {nt}
90
+ WHERE type IN ({placeholders})
91
+ ORDER BY updated_at DESC, id ASC LIMIT ?
92
+ """,
93
+ (*content_types, max(1, min(int(max_documents), 2000))),
94
+ ).fetchall()
95
+ existing_labels = {
96
+ str(row["title"] or "").strip().lower()
97
+ for row in conn.execute(
98
+ f"SELECT title FROM {nt} WHERE type IN ('Topic', 'Concept')"
99
+ ).fetchall()
100
+ }
101
+ documents = [
102
+ {
103
+ "id": row["id"],
104
+ "text": f"{row['title']} {row['summary'] or ''}",
105
+ "kind": "file"
106
+ if row["type"] in {"Document", "File", "CodeFile", "Spreadsheet"}
107
+ else "chat",
108
+ }
109
+ for row in rows
110
+ ]
111
+ overlay = auto_build_graph_overlay(
112
+ documents,
113
+ existing_node_labels=existing_labels,
114
+ max_new_nodes=max(1, min(int(max_new_nodes), 50)),
115
+ )
116
+ valid_ids = {row["id"] for row in rows}
117
+ review = review_mode if review_mode is not None else _promotion_review_default()
118
+ if review:
119
+ proposed_at = _now()
120
+ proposed = [
121
+ {
122
+ "id": f"topic:{_slug(promo['label'])}",
123
+ "label": promo["label"],
124
+ "importance": promo["importance"],
125
+ "aliases": promo["aliases"],
126
+ "sources": [s for s in promo["sources"][:10] if s in valid_ids],
127
+ "proposed_at": proposed_at,
128
+ }
129
+ for promo in overlay["promotions"]
130
+ ]
131
+ with self._connect() as conn:
132
+ merged = self._merge_pending_promotions(conn, proposed)
133
+ return {
134
+ "status": "pending_review",
135
+ "documents_scanned": len(documents),
136
+ "candidates_total": overlay["candidates_total"],
137
+ "pending": proposed,
138
+ "pending_total": len(merged),
139
+ "skipped": overlay["skipped"][:50],
140
+ "skipped_total": len(overlay["skipped"]),
141
+ }
142
+ promoted: List[Dict[str, Any]] = []
143
+ with self._connect() as conn:
144
+ for promo in overlay["promotions"]:
145
+ promoted.append(
146
+ self._write_promotion(conn, promo, valid_source_ids=valid_ids)
147
+ )
148
+ return {
149
+ "status": "ok",
150
+ "documents_scanned": len(documents),
151
+ "candidates_total": overlay["candidates_total"],
152
+ "promoted": promoted,
153
+ "skipped": overlay["skipped"][:50],
154
+ "skipped_total": len(overlay["skipped"]),
155
+ }
156
+
157
+ def _write_promotion(
158
+ self,
159
+ conn: sqlite3.Connection,
160
+ promo: Dict[str, Any],
161
+ *,
162
+ valid_source_ids: Optional[set] = None,
163
+ ) -> Dict[str, Any]:
164
+ """Write one curator promotion: Topic node + importance + MENTIONS edges.
165
+
166
+ Single write path shared by direct ``curate()`` and
167
+ :meth:`apply_pending_promotions`, so a human-approved promotion lands
168
+ exactly like an auto-promoted one. ``valid_source_ids`` restricts the
169
+ linkable sources to this curate run's scanned rows; when ``None``
170
+ (apply-after-review), each stored source is checked for existence so a
171
+ node deleted between propose and apply is skipped, not an error.
172
+ """
173
+ topic_id = str(promo.get("id") or f"topic:{_slug(str(promo['label']))}")
174
+ self._upsert_node(
175
+ conn,
176
+ topic_id,
177
+ "Topic",
178
+ str(promo["label"]),
179
+ metadata={
180
+ "curated": True,
181
+ "importance": promo["importance"],
182
+ "aliases": list(promo.get("aliases") or []),
183
+ "source": "graph_curator",
184
+ },
185
+ )
186
+ conn.execute(
187
+ "UPDATE nodes_v2 SET importance_score=? WHERE id=?",
188
+ (float(promo["importance"]), topic_id),
189
+ )
190
+ linked = 0
191
+ for source_id in list(promo.get("sources") or [])[:10]:
192
+ if valid_source_ids is not None:
193
+ if source_id not in valid_source_ids:
194
+ continue
195
+ elif not conn.execute(
196
+ "SELECT 1 FROM nodes WHERE id=?", (source_id,)
197
+ ).fetchone():
198
+ continue
199
+ self._upsert_edge(
200
+ conn,
201
+ source_id,
202
+ topic_id,
203
+ "MENTIONS",
204
+ weight=0.6,
205
+ metadata={"source": "graph_curator"},
206
+ )
207
+ linked += 1
208
+ return {
209
+ "node_id": topic_id,
210
+ "label": promo["label"],
211
+ "importance": promo["importance"],
212
+ "linked_sources": linked,
213
+ }
214
+
215
+ # ── pending promotion queue (review 2026-07-25 Wave 4) ───────────────────
216
+
217
+ def _read_pending_promotions(
218
+ self, conn: sqlite3.Connection
219
+ ) -> List[Dict[str, Any]]:
220
+ try:
221
+ row = conn.execute(
222
+ "SELECT value FROM graph_meta WHERE key=?",
223
+ (_PENDING_PROMOTIONS_KEY,),
224
+ ).fetchone()
225
+ except sqlite3.Error:
226
+ return []
227
+ if not row or not row["value"]:
228
+ return []
229
+ try:
230
+ parsed = json.loads(row["value"])
231
+ except (TypeError, ValueError):
232
+ return []
233
+ if not isinstance(parsed, list):
234
+ return []
235
+ return [
236
+ item for item in parsed if isinstance(item, dict) and item.get("id")
237
+ ]
238
+
239
+ def _store_pending_promotions(
240
+ self, conn: sqlite3.Connection, entries: List[Dict[str, Any]]
241
+ ) -> None:
242
+ conn.execute(
243
+ "INSERT OR REPLACE INTO graph_meta(key, value) VALUES (?, ?)",
244
+ (_PENDING_PROMOTIONS_KEY, json.dumps(entries, ensure_ascii=False)),
245
+ )
246
+
247
+ def _merge_pending_promotions(
248
+ self, conn: sqlite3.Connection, proposed: List[Dict[str, Any]]
249
+ ) -> List[Dict[str, Any]]:
250
+ """Merge new proposals into the stored queue (dedupe by id, cap 100)."""
251
+ merged: Dict[str, Dict[str, Any]] = {}
252
+ for item in self._read_pending_promotions(conn) + list(proposed):
253
+ merged[str(item["id"])] = item # newest proposal wins per id
254
+ entries = list(merged.values())[-_PENDING_PROMOTIONS_CAP:]
255
+ self._store_pending_promotions(conn, entries)
256
+ return entries
257
+
258
+ def pending_promotions(self) -> List[Dict[str, Any]]:
259
+ """List promotions waiting for a human decision (review mode)."""
260
+ with self._connect() as conn:
261
+ return self._read_pending_promotions(conn)
262
+
263
+ def apply_pending_promotions(
264
+ self, ids: Optional[List[str]] = None
265
+ ) -> Dict[str, Any]:
266
+ """Apply stored pending promotions (all of them when ``ids`` is None).
267
+
268
+ Uses the exact node-writing path as direct ``curate()`` via
269
+ :meth:`_write_promotion`; applied entries leave the queue.
270
+ """
271
+ wanted = None if ids is None else {str(item) for item in ids}
272
+ applied: List[Dict[str, Any]] = []
273
+ remaining: List[Dict[str, Any]] = []
274
+ with self._connect() as conn:
275
+ for promo in self._read_pending_promotions(conn):
276
+ if wanted is not None and str(promo.get("id")) not in wanted:
277
+ remaining.append(promo)
278
+ continue
279
+ applied.append(self._write_promotion(conn, promo))
280
+ self._store_pending_promotions(conn, remaining)
281
+ return {"status": "ok", "applied": applied, "remaining": len(remaining)}
282
+
283
+ def reject_pending_promotions(
284
+ self, ids: Optional[List[str]] = None
285
+ ) -> Dict[str, Any]:
286
+ """Drop pending promotions without writing (all when ``ids`` is None)."""
287
+ wanted = None if ids is None else {str(item) for item in ids}
288
+ rejected: List[str] = []
289
+ remaining: List[Dict[str, Any]] = []
290
+ with self._connect() as conn:
291
+ for promo in self._read_pending_promotions(conn):
292
+ if wanted is not None and str(promo.get("id")) not in wanted:
293
+ remaining.append(promo)
294
+ continue
295
+ rejected.append(str(promo.get("id")))
296
+ self._store_pending_promotions(conn, remaining)
297
+ return {"status": "ok", "rejected": rejected, "remaining": len(remaining)}
298
+
299
+ _NOISE_CONTENT_TYPES = (
300
+ "Document",
301
+ "File",
302
+ "CodeFile",
303
+ "Message",
304
+ "AIResponse",
305
+ "Chat",
306
+ "Page",
307
+ "Slide",
308
+ "Spreadsheet",
309
+ )
310
+ _NOISE_CONCEPT_TYPES = ("Concept", "Feature", "Topic", "Code", "Error")
311
+
312
+ def curate_noise(
313
+ self,
314
+ *,
315
+ dry_run: bool = True,
316
+ max_df_ratio: float = 0.8,
317
+ min_doc_frequency: int = 1,
318
+ min_corpus_docs: int = 5,
319
+ normalize_verbs: bool = True,
320
+ max_removals: int = 200,
321
+ ) -> Dict[str, Any]:
322
+ """Noise-reduction curation job (backlog #10, review §7.2 D).
323
+
324
+ (a) Removes heuristic concept nodes (``auto_extracted`` /
325
+ ``graph_curator``-promoted) whose document frequency marks them as
326
+ noise: ubiquitous (low IDF — linked from more than ``max_df_ratio`` of
327
+ content docs once the corpus has ``min_corpus_docs``) or below the
328
+ ``min_doc_frequency`` floor. Explicitly user-created nodes are never
329
+ touched, whatever their stats.
330
+
331
+ (b) Normalizes free-string relation verbs on the legacy edge table via
332
+ the ko/en dictionary in :mod:`lattice_brain.graph.curator`
333
+ ('만들다/만든/creates' → 'created', …), merging rows that collide
334
+ after the rename.
335
+
336
+ ``dry_run=True`` (the default) only *reports* what would change.
337
+ """
338
+ from ..curator import (
339
+ build_relation_verb_index,
340
+ plan_concept_noise_reduction,
341
+ plan_relation_normalization,
342
+ )
343
+
344
+ max_removals = max(0, int(max_removals))
345
+ # Operate on the legacy write tables directly: they are the mutation
346
+ # target, and raw free-string verbs only exist there (the v4 write
347
+ # door normalizes new edges; the kgv2_* read views collapse
348
+ # legacy_type and would hide exactly the rows this job cleans up).
349
+ nt, et = "nodes", "edges"
350
+ with self._connect() as conn:
351
+ content_ph = ",".join("?" for _ in self._NOISE_CONTENT_TYPES)
352
+ total_docs = conn.execute(
353
+ f"SELECT COUNT(*) AS c FROM {nt} WHERE type IN ({content_ph})",
354
+ self._NOISE_CONTENT_TYPES,
355
+ ).fetchone()["c"]
356
+
357
+ concept_ph = ",".join("?" for _ in self._NOISE_CONCEPT_TYPES)
358
+ concept_rows = conn.execute(
359
+ f"SELECT id, type, title, metadata_json FROM {nt} WHERE type IN ({concept_ph})",
360
+ self._NOISE_CONCEPT_TYPES,
361
+ ).fetchall()
362
+ concepts = []
363
+ for row in concept_rows:
364
+ meta = _safe_loads(row["metadata_json"]) or {}
365
+ heuristic = bool(meta.get("auto_extracted")) or (
366
+ meta.get("source") == "graph_curator" or meta.get("curated") is True
367
+ )
368
+ # Document frequency: distinct *content* nodes linked to this
369
+ # concept in either direction.
370
+ df = conn.execute(
371
+ f"""
372
+ SELECT COUNT(DISTINCT n.id) AS c
373
+ FROM {et} e
374
+ JOIN {nt} n
375
+ ON n.id = CASE WHEN e.to_node = ? THEN e.from_node ELSE e.to_node END
376
+ WHERE (e.to_node = ? OR e.from_node = ?)
377
+ AND n.type IN ({content_ph})
378
+ """,
379
+ (row["id"], row["id"], row["id"], *self._NOISE_CONTENT_TYPES),
380
+ ).fetchone()["c"]
381
+ concepts.append({
382
+ "id": row["id"],
383
+ "label": row["title"],
384
+ "type": row["type"],
385
+ "df": int(df or 0),
386
+ "heuristic": heuristic,
387
+ })
388
+
389
+ plan = plan_concept_noise_reduction(
390
+ concepts,
391
+ total_docs,
392
+ max_df_ratio=max_df_ratio,
393
+ min_doc_frequency=min_doc_frequency,
394
+ min_corpus_docs=min_corpus_docs,
395
+ )
396
+ removals = plan["remove"][:max_removals]
397
+
398
+ verb_index = build_relation_verb_index()
399
+ edge_type_rows = conn.execute(
400
+ f"SELECT DISTINCT type FROM {et}"
401
+ ).fetchall()
402
+ verb_plan = (
403
+ plan_relation_normalization(
404
+ (row["type"] for row in edge_type_rows), index=verb_index,
405
+ )
406
+ if normalize_verbs
407
+ else {}
408
+ )
409
+
410
+ removed_count = 0
411
+ renamed_edges = 0
412
+ if not dry_run:
413
+ for decision in removals:
414
+ node_id = decision["id"]
415
+ conn.execute(
416
+ "DELETE FROM edges WHERE from_node=? OR to_node=?",
417
+ (node_id, node_id),
418
+ )
419
+ conn.execute(
420
+ "DELETE FROM vector_embeddings WHERE item_id=?", (node_id,)
421
+ )
422
+ conn.execute("DELETE FROM nodes WHERE id=?", (node_id,))
423
+ self._v2_delete_nodes(conn, [node_id])
424
+ removed_count += 1
425
+ for original, canonical in verb_plan.items():
426
+ renamed_edges += conn.execute(
427
+ "SELECT COUNT(*) AS c FROM edges WHERE type=?", (original,)
428
+ ).fetchone()["c"]
429
+ # UNIQUE(from_node, to_node, type): merge rows that collide
430
+ # after the rename instead of failing the UPDATE.
431
+ conn.execute(
432
+ "UPDATE OR IGNORE edges SET type=? WHERE type=?",
433
+ (canonical, original),
434
+ )
435
+ conn.execute("DELETE FROM edges WHERE type=?", (original,))
436
+ # Stamp every applied run — even a no-op one means the graph
437
+ # was inspected, so the Command Center hygiene advisory
438
+ # (review 2026-07-25 Wave 2.5) stops re-suggesting for a while.
439
+ conn.execute(
440
+ "INSERT OR REPLACE INTO graph_meta(key, value) VALUES (?, ?)",
441
+ (_LAST_NOISE_CURATE_KEY, _now()),
442
+ )
443
+
444
+ return {
445
+ "status": "ok",
446
+ "dry_run": bool(dry_run),
447
+ "total_content_docs": int(total_docs or 0),
448
+ "concepts_examined": len(concepts),
449
+ "remove": removals,
450
+ "remove_total": len(plan["remove"]),
451
+ "kept": len(plan["keep"]),
452
+ "protected_user_nodes": sum(
453
+ 1 for item in plan["keep"] if item.get("reason") == "user_created_protected"
454
+ ),
455
+ "verb_normalizations": verb_plan,
456
+ "applied": {
457
+ "removed_nodes": removed_count,
458
+ "renamed_edges": renamed_edges,
459
+ },
460
+ "thresholds": {
461
+ "max_df_ratio": float(max_df_ratio),
462
+ "min_doc_frequency": int(min_doc_frequency),
463
+ "min_corpus_docs": int(min_corpus_docs),
464
+ },
465
+ }
466
+
467
+ def last_noise_curate_at(self) -> Optional[str]:
468
+ """Timestamp of the last applied (dry_run=False) noise-curate run.
469
+
470
+ ``None`` when the job never ran or the meta table is unreadable —
471
+ advisory readers treat both as "curation is due" (fail-open).
472
+ """
473
+ try:
474
+ with self._connect() as conn:
475
+ row = conn.execute(
476
+ "SELECT value FROM graph_meta WHERE key=?",
477
+ (_LAST_NOISE_CURATE_KEY,),
478
+ ).fetchone()
479
+ except sqlite3.Error:
480
+ return None
481
+ return str(row["value"]) if row and row["value"] else None
482
+
483
+ def mark_superseded(self, old_node_id: str, new_node_id: str) -> Dict[str, Any]:
484
+ """Record that ``old_node_id`` was replaced by ``new_node_id``.
485
+
486
+ The old node stays queryable (knowledge is durable); readers can follow
487
+ the revision chain via ``nodes_v2.superseded_by``.
488
+ """
489
+ with self._connect() as conn:
490
+ for node_id in (old_node_id, new_node_id):
491
+ exists = conn.execute(
492
+ "SELECT 1 FROM nodes_v2 WHERE id=?", (node_id,)
493
+ ).fetchone()
494
+ if not exists:
495
+ raise FileNotFoundError(node_id)
496
+ conn.execute(
497
+ "UPDATE nodes_v2 SET superseded_by=?, updated_at=? WHERE id=?",
498
+ (new_node_id, _now(), old_node_id),
499
+ )
500
+ return {"status": "ok", "node_id": old_node_id, "superseded_by": new_node_id}