superlocalmemory 4.0.7 → 4.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +219 -1
  2. package/README.md +6 -6
  3. package/package.json +1 -1
  4. package/plugin/.claude-plugin/plugin.json +1 -1
  5. package/plugin/CLAUDE.md +3 -3
  6. package/plugin/agents/slm-governance-advisor.md +1 -1
  7. package/plugin/agents/slm-loop-runner.md +1 -1
  8. package/plugin/agents/slm-memory-advisor.md +1 -1
  9. package/plugin/agents/slm-optimize-advisor.md +1 -1
  10. package/plugin/requirements.txt +1 -1
  11. package/plugin/scripts/ensure-venv.sh +1 -1
  12. package/plugin/skills/slm-cache/SKILL.md +1 -1
  13. package/plugin/skills/slm-compress/SKILL.md +1 -1
  14. package/plugin/skills/slm-governance/SKILL.md +1 -1
  15. package/plugin/skills/slm-graph/SKILL.md +1 -1
  16. package/plugin/skills/slm-loop/SKILL.md +1 -1
  17. package/plugin/skills/slm-mesh/SKILL.md +1 -1
  18. package/plugin/skills/slm-profile/SKILL.md +1 -1
  19. package/plugin/skills/slm-recall/SKILL.md +1 -1
  20. package/plugin/skills/slm-remember/SKILL.md +1 -1
  21. package/plugin/skills/slm-scope/SKILL.md +1 -1
  22. package/plugin/skills/slm-session/SKILL.md +1 -1
  23. package/plugin/skills/slm-status/SKILL.md +3 -3
  24. package/plugin-src/rules/AGENTS.md +1 -1
  25. package/plugin-src/skills/slm-status/SKILL.md +2 -2
  26. package/pyproject.toml +1 -1
  27. package/scripts/postinstall.js +4 -0
  28. package/src/superlocalmemory/__init__.py +1 -1
  29. package/src/superlocalmemory/cli/_lazy_init.py +1 -1
  30. package/src/superlocalmemory/cli/commands.py +119 -9
  31. package/src/superlocalmemory/cli/db_migrate.py +0 -2
  32. package/src/superlocalmemory/cli/gdpr_io.py +1 -1
  33. package/src/superlocalmemory/cli/main.py +5 -5
  34. package/src/superlocalmemory/cli/service_installer.py +2 -1
  35. package/src/superlocalmemory/cli/setup_wizard.py +1 -1
  36. package/src/superlocalmemory/cli/summary_cmd.py +23 -3
  37. package/src/superlocalmemory/code_graph/bridge/maintenance.py +7 -1
  38. package/src/superlocalmemory/core/config.py +41 -7
  39. package/src/superlocalmemory/core/consolidation_engine.py +14 -15
  40. package/src/superlocalmemory/core/context_cache.py +0 -2
  41. package/src/superlocalmemory/core/engine.py +371 -63
  42. package/src/superlocalmemory/core/evidence_bundle.py +3 -1
  43. package/src/superlocalmemory/core/install_detector.py +131 -0
  44. package/src/superlocalmemory/core/progressive_abstraction.py +1 -1
  45. package/src/superlocalmemory/core/recall_worker.py +4 -0
  46. package/src/superlocalmemory/core/security_primitives.py +3 -6
  47. package/src/superlocalmemory/core/store_pipeline.py +94 -26
  48. package/src/superlocalmemory/core/topic_signature.py +0 -2
  49. package/src/superlocalmemory/core/transactions/concrete_owners.py +15 -8
  50. package/src/superlocalmemory/dynamics/eap_scheduler.py +17 -6
  51. package/src/superlocalmemory/encoding/graph_builder.py +2 -2
  52. package/src/superlocalmemory/encoding/scene_builder.py +8 -2
  53. package/src/superlocalmemory/evolution/skill_evolver.py +16 -1
  54. package/src/superlocalmemory/hooks/adapter_base.py +0 -2
  55. package/src/superlocalmemory/hooks/context_payload.py +0 -2
  56. package/src/superlocalmemory/hooks/hook_handlers.py +38 -11
  57. package/src/superlocalmemory/hooks/portable_kit.py +8 -8
  58. package/src/superlocalmemory/hooks/post_tool_async_hook.py +0 -2
  59. package/src/superlocalmemory/hooks/prewarm_auth.py +0 -2
  60. package/src/superlocalmemory/hooks/user_prompt_hook.py +0 -2
  61. package/src/superlocalmemory/infra/backup.py +44 -8
  62. package/src/superlocalmemory/integrations/bounded_loops_mcp.py +24 -7
  63. package/src/superlocalmemory/learning/arm_catalog.py +0 -2
  64. package/src/superlocalmemory/learning/bandit.py +0 -2
  65. package/src/superlocalmemory/learning/bandit_cache.py +0 -2
  66. package/src/superlocalmemory/learning/dedup_hnsw.py +11 -11
  67. package/src/superlocalmemory/learning/ensemble.py +0 -2
  68. package/src/superlocalmemory/learning/labeler.py +0 -2
  69. package/src/superlocalmemory/learning/legacy_migration.py +0 -2
  70. package/src/superlocalmemory/learning/model_cache.py +0 -2
  71. package/src/superlocalmemory/learning/pattern_miner.py +12 -7
  72. package/src/superlocalmemory/learning/ranker.py +0 -2
  73. package/src/superlocalmemory/learning/reward_archive.py +6 -1
  74. package/src/superlocalmemory/learning/reward_proxy.py +0 -2
  75. package/src/superlocalmemory/learning/signal_worker.py +0 -2
  76. package/src/superlocalmemory/math/fisher.py +1 -1
  77. package/src/superlocalmemory/math/hopfield.py +4 -1
  78. package/src/superlocalmemory/math/langevin.py +1 -1
  79. package/src/superlocalmemory/math/sheaf.py +7 -3
  80. package/src/superlocalmemory/mcp/cli_fallback.py +1 -1
  81. package/src/superlocalmemory/mcp/profiles.py +11 -4
  82. package/src/superlocalmemory/mcp/server.py +8 -1
  83. package/src/superlocalmemory/mcp/tools_active.py +56 -0
  84. package/src/superlocalmemory/mcp/tools_core.py +1 -1
  85. package/src/superlocalmemory/mcp/tools_summaries.py +147 -0
  86. package/src/superlocalmemory/optimize/cache/manager.py +2 -2
  87. package/src/superlocalmemory/optimize/compress/ccr.py +1 -1
  88. package/src/superlocalmemory/optimize/compress/router.py +1 -1
  89. package/src/superlocalmemory/optimize/proxy/_helpers.py +2 -2
  90. package/src/superlocalmemory/optimize/proxy/server.py +1 -1
  91. package/src/superlocalmemory/optimize/proxy/vertex_surface.py +2 -2
  92. package/src/superlocalmemory/optimize/storage/db.py +2 -2
  93. package/src/superlocalmemory/retrieval/agentic.py +1 -1
  94. package/src/superlocalmemory/retrieval/ann_index.py +9 -2
  95. package/src/superlocalmemory/retrieval/bm25_channel.py +2 -2
  96. package/src/superlocalmemory/retrieval/bridge_discovery.py +2 -2
  97. package/src/superlocalmemory/retrieval/engine.py +272 -43
  98. package/src/superlocalmemory/retrieval/entity_channel.py +1 -1
  99. package/src/superlocalmemory/retrieval/hopfield_channel.py +8 -2
  100. package/src/superlocalmemory/retrieval/profile_channel.py +1 -1
  101. package/src/superlocalmemory/retrieval/quantization_aware_search.py +1 -1
  102. package/src/superlocalmemory/retrieval/remote_reranker.py +2 -2
  103. package/src/superlocalmemory/retrieval/reranker.py +3 -3
  104. package/src/superlocalmemory/retrieval/semantic_channel.py +3 -3
  105. package/src/superlocalmemory/retrieval/spreading_activation.py +8 -8
  106. package/src/superlocalmemory/retrieval/strategy.py +94 -0
  107. package/src/superlocalmemory/retrieval/temporal_channel.py +167 -10
  108. package/src/superlocalmemory/retrieval/temporal_validity_filter.py +1 -1
  109. package/src/superlocalmemory/retrieval/vector_store.py +88 -10
  110. package/src/superlocalmemory/server/consolidation_runner.py +140 -0
  111. package/src/superlocalmemory/server/recall_serializer.py +44 -2
  112. package/src/superlocalmemory/server/routes/agents.py +52 -8
  113. package/src/superlocalmemory/server/routes/brain.py +110 -2
  114. package/src/superlocalmemory/server/routes/memories.py +153 -0
  115. package/src/superlocalmemory/server/routes/prewarm.py +4 -4
  116. package/src/superlocalmemory/server/routes/v3_api.py +24 -46
  117. package/src/superlocalmemory/server/unified_daemon.py +566 -7
  118. package/src/superlocalmemory/storage/_schema_version.py +46 -3
  119. package/src/superlocalmemory/storage/backup.py +531 -0
  120. package/src/superlocalmemory/storage/database.py +11 -4
  121. package/src/superlocalmemory/storage/embedding_codec.py +129 -0
  122. package/src/superlocalmemory/storage/embedding_migrator.py +5 -3
  123. package/src/superlocalmemory/storage/migration_runner.py +142 -2
  124. package/src/superlocalmemory/storage/migrations/__init__.py +1 -1
  125. package/src/superlocalmemory/storage/migrations.py +15 -1
  126. package/src/superlocalmemory/storage/models.py +7 -0
  127. package/src/superlocalmemory/storage/quantized_store.py +4 -2
  128. package/src/superlocalmemory/summaries/base.py +159 -0
  129. package/src/superlocalmemory/summaries/daily_reflection.py +55 -8
  130. package/src/superlocalmemory/summaries/project_work_log.py +23 -7
  131. package/src/superlocalmemory/summaries/session_summary.py +10 -6
  132. package/src/superlocalmemory/ui/css/legacy-dashboard.css +1 -1
  133. package/src/superlocalmemory/ui/css/neural-glass.css +1 -1
  134. package/src/superlocalmemory/ui/index.html +9 -3
  135. package/src/superlocalmemory/ui/js/core.js +1 -1
  136. package/src/superlocalmemory/ui/js/od-boundedloops.js +324 -0
  137. package/src/superlocalmemory/ui/js/od-brain.js +1 -1
  138. package/src/superlocalmemory/ui/js/od-memories.js +337 -12
  139. package/src/superlocalmemory/ui/js/od-mesh.js +97 -5
  140. package/src/superlocalmemory/ui/js/od-operations.js +1 -150
  141. package/src/superlocalmemory/ui/js/od-optimize.js +36 -9
  142. package/src/superlocalmemory/ui/js/od-shell.js +10 -0
@@ -4,8 +4,6 @@
4
4
 
5
5
  """Shared security primitives for SLM v3.4.22.
6
6
 
7
- LLD reference: `.backup/active-brain/lld/LLD-07-schema-migrations-and-security-primitives.md`
8
- Section: 6.1 through 6.10.
9
7
 
10
8
  Every file write, subprocess spawn, and secret-bearing string across SLM
11
9
  daemon, adapters, hooks, and binary installer routes through this module.
@@ -155,10 +153,9 @@ def safe_resolve(base: Path, rel: str | Path) -> Path:
155
153
  # enforces the LLD-00 regex AND the base-containment check. Callers in
156
154
  # LLD-09 (session state files) and LLD-11 (evolution.lock) MUST use this.
157
155
  #
158
- # Naming deviation from IMPLEMENTATION-MANIFEST P0.2: the manifest reused
159
- # the name ``safe_resolve`` but the existing path-style helper is used in
160
- # 9+ call sites. A separate name avoids breakage. See
161
- # ``.backup/active-brain/MANIFEST-DEVIATION.md`` P0.2 entry.
156
+ # Naming deviation note: the name ``safe_resolve`` was already used by an
157
+ # existing path-style helper that has 9+ call sites. A separate name
158
+ # (``safe_resolve_identifier``) avoids silent breakage at those call sites.
162
159
 
163
160
  _SAFE_ID_RE = re.compile(r"^[a-zA-Z0-9_-]{1,128}$")
164
161
 
@@ -311,8 +311,13 @@ def enrich_fact(
311
311
  # Vector dual-write helper (P1-2 / embeddings-vector-01)
312
312
  # ---------------------------------------------------------------------------
313
313
 
314
- def _upsert_fact_vectors(fact, profile_id, ann_index, vector_store, embedder=None):
315
- """Dual-write a fact's embedding to the ANN index + sqlite-vec store.
314
+ def _upsert_fact_vectors(fact, profile_id, ann_index, vector_store, embedder=None) -> bool:
315
+ """Dual-write a fact's embedding to the sqlite-vec projection and the ANN index.
316
+
317
+ Write order mirrors _attach_vector: the sqlite-vec projection is attempted
318
+ first because that is what a meaning-based search reads. The ANN index is
319
+ updated only when the projection accepts the vector. Returns True when the
320
+ fact is now findable by meaning (the projection accepted the vector).
316
321
 
317
322
  Embeds on-demand when the fact has no embedding (e.g. consolidated
318
323
  summary facts created without one), so UPDATE/SUPERSEDE and consolidated
@@ -325,18 +330,44 @@ def _upsert_fact_vectors(fact, profile_id, ann_index, vector_store, embedder=Non
325
330
  except Exception as _emb_exc: # pragma: no cover - defensive
326
331
  _reraise_materialization_deferral(_emb_exc)
327
332
  logger.debug("on-demand embed failed for %s: %s", fact.fact_id, _emb_exc)
328
- return
333
+ return False
329
334
  if not getattr(fact, "embedding", None):
330
- return
331
- if ann_index:
332
- ann_index.add(fact.fact_id, fact.embedding)
333
- # V3.2: VectorStore upsert (sqlite-vec) -- dual-write (Rule 12)
335
+ return False
336
+
337
+ projected = False
338
+ # Projection first: what a meaning-based search reads.
334
339
  if vector_store and getattr(vector_store, "available", False):
335
- vector_store.upsert(
336
- fact_id=fact.fact_id,
337
- profile_id=profile_id,
338
- embedding=fact.embedding,
339
- )
340
+ try:
341
+ projected = bool(vector_store.upsert(
342
+ fact_id=fact.fact_id,
343
+ profile_id=profile_id,
344
+ embedding=fact.embedding,
345
+ ))
346
+ if not projected:
347
+ logger.warning(
348
+ "vector projection refused for %s — stored but not "
349
+ "findable by meaning", fact.fact_id[:12],
350
+ )
351
+ except Exception as _vs_exc:
352
+ logger.warning(
353
+ "vector projection failed for %s (%s: %s) — stored but not "
354
+ "findable by meaning",
355
+ fact.fact_id[:12], type(_vs_exc).__name__, _vs_exc,
356
+ )
357
+
358
+ # ANN index only when the projection accepted the vector so both
359
+ # representations stay consistent. Writing ANN without a vector-store
360
+ # entry creates a ghost that disappears on restart (ANN is rebuilt from
361
+ # the vector store at startup).
362
+ if projected and ann_index:
363
+ try:
364
+ ann_index.add(fact.fact_id, fact.embedding)
365
+ except Exception:
366
+ logger.warning(
367
+ "in-memory index rejected %s", fact.fact_id[:12], exc_info=True,
368
+ )
369
+
370
+ return projected
340
371
 
341
372
 
342
373
  class _TombstoneReadError(Exception):
@@ -741,6 +772,15 @@ def run_store(
741
772
  materialization_progress["relational_started"] = True
742
773
 
743
774
  is_queryable_promotion = fact.fact_id in queryable_ids
775
+ # When a promoted fact is being materialised the embedding column is
776
+ # written in a separate step AFTER the projection attempt so that the
777
+ # two representations stay in the correct order: projection first,
778
+ # canonical column second (mirroring _attach_vector's invariant).
779
+ # Writing the column before the projection and then failing the
780
+ # projection leaves the fact with embedding IS NOT NULL but no entry
781
+ # in fact_embeddings — invisible to meaning-search and invisible to
782
+ # every repair pass that selects WHERE embedding IS NULL.
783
+ _deferred_canonical_embedding = None # set below if promotion path taken
744
784
  if is_queryable_promotion:
745
785
  db.update_fact(fact.fact_id, {
746
786
  "content": fact.content,
@@ -757,15 +797,22 @@ def run_store(
757
797
  "access_count": fact.access_count,
758
798
  "source_turn_ids_json": fact.source_turn_ids,
759
799
  "session_id": fact.session_id,
760
- "embedding": fact.embedding,
761
- "fisher_mean": fact.fisher_mean,
762
- "fisher_variance": fact.fisher_variance,
800
+ # embedding / fisher fields omitted here — written after
801
+ # the projection attempt below so canonical is never ahead
802
+ # of the projection.
763
803
  "lifecycle": fact.lifecycle,
764
804
  "langevin_position": fact.langevin_position,
765
805
  "emotional_valence": fact.emotional_valence,
766
806
  "emotional_arousal": fact.emotional_arousal,
767
807
  "signal_type": fact.signal_type,
768
808
  })
809
+ if fact.embedding:
810
+ _deferred_canonical_embedding = (
811
+ fact.fact_id,
812
+ fact.embedding,
813
+ fact.fisher_mean,
814
+ fact.fisher_variance,
815
+ )
769
816
  if consolidator:
770
817
  try:
771
818
  action = consolidator.consolidate(
@@ -793,6 +840,9 @@ def run_store(
793
840
  target_id = action.existing_fact_id
794
841
  if is_queryable_promotion and target_id:
795
842
  db.delete_fact(fact.fact_id)
843
+ # The original promoted fact was deleted; its deferred
844
+ # canonical embedding write must not happen.
845
+ _deferred_canonical_embedding = None
796
846
  existing_fact = db.get_fact(target_id) if target_id else None
797
847
  if existing_fact is None:
798
848
  continue
@@ -838,9 +888,31 @@ def run_store(
838
888
  if materialization_progress is not None:
839
889
  materialization_progress["fact_ids"] = tuple(stored_ids)
840
890
 
841
- # Dual-write embedding to ANN index + vector store (embed on-demand if
842
- # a consolidated ADD fact arrived without one). See _upsert_fact_vectors.
891
+ # Projection first (vector store then ANN index, on-demand embed for
892
+ # consolidated facts that arrived without one).
843
893
  _upsert_fact_vectors(fact, profile_id, ann_index, vector_store, embedder)
894
+
895
+ # Canonical embedding write: deferred to here from the queryable-
896
+ # promotion block above so the projection is always attempted first.
897
+ # The column is written regardless of whether the projection accepted
898
+ # the vector (the vector is real data; withholding it would force
899
+ # every repair pass to re-compute a model call that the same
900
+ # installation condition would refuse again anyway).
901
+ if _deferred_canonical_embedding is not None:
902
+ _dc_fid, _dc_emb, _dc_fmean, _dc_fvar = _deferred_canonical_embedding
903
+ try:
904
+ db.update_fact(_dc_fid, {
905
+ "embedding": _dc_emb,
906
+ "fisher_mean": _dc_fmean,
907
+ "fisher_variance": _dc_fvar,
908
+ })
909
+ except Exception as _dc_exc:
910
+ logger.warning(
911
+ "canonical embedding write failed for %s: %s",
912
+ _dc_fid[:12], _dc_exc,
913
+ )
914
+ _deferred_canonical_embedding = None
915
+
844
916
  # Phase 2: Generate contextual description (after consolidator, before graph_builder)
845
917
  if context_generator:
846
918
  try:
@@ -1139,15 +1211,11 @@ def run_store_fact_direct(
1139
1211
  )
1140
1212
  fact.canonical_entities = list(canonical.values())
1141
1213
  db.store_fact(fact)
1142
- if fact.embedding and ann_index:
1143
- ann_index.add(fact.fact_id, fact.embedding)
1144
- # V3.2: VectorStore upsert (dual-write)
1145
- if fact.embedding and vector_store and vector_store.available:
1146
- vector_store.upsert(
1147
- fact_id=fact.fact_id,
1148
- profile_id=profile_id,
1149
- embedding=fact.embedding,
1150
- )
1214
+ # Projection first (vector store), ANN only on success — matching
1215
+ # _attach_vector's invariant. The return value (projected) is not used
1216
+ # here because run_store_fact_direct is a fire-and-forget path with no
1217
+ # receipt to update; the caller is responsible for any enrichment status.
1218
+ _upsert_fact_vectors(fact, profile_id, ann_index, vector_store)
1151
1219
  if graph_builder:
1152
1220
  graph_builder.build_edges(fact, profile_id)
1153
1221
  # The graph projection must run after GraphBuilder: syncing immediately
@@ -4,8 +4,6 @@
4
4
 
5
5
  """Topic signature — deterministic, Unicode-safe, ReDoS-resistant 16-char hex.
6
6
 
7
- LLD reference: `.backup/active-brain/lld/LLD-01-context-cache-and-hot-path-hooks.md`
8
- Section 4.2.
9
7
 
10
8
  Hot-path contract:
11
9
  - stdlib-only imports (no third-party packages).
@@ -15,6 +15,7 @@ from superlocalmemory.core.transactions.owners import (
15
15
  OwnerResult,
16
16
  )
17
17
  from superlocalmemory.core.transactions.service import MemoryTransactionService
18
+ from superlocalmemory.storage.embedding_codec import decode_embedding
18
19
 
19
20
  REQUIRED_ADMISSION_OWNERS: tuple[str, ...] = ("bm25", "temporal", "vector")
20
21
 
@@ -438,10 +439,16 @@ class VectorOwner(_FactScopedOwner):
438
439
  for row in rows:
439
440
  record = dict(row)
440
441
  fid = record.get("fact_id")
441
- embedding = record.get("embedding")
442
- if fid is None or not embedding:
442
+ raw_embedding = record.get("embedding")
443
+ if fid is None or not raw_embedding:
443
444
  continue
444
- result[fid] = _fingerprint("vector", str(embedding))
445
+ # Decode so TEXT and BLOB rows produce the same fingerprint for the
446
+ # same embedding values. A ValueError here (corrupt buffer) must
447
+ # propagate — a bad fingerprint is worse than no fingerprint.
448
+ decoded = decode_embedding(raw_embedding, fact_id=fid)
449
+ if decoded is None:
450
+ continue
451
+ result[fid] = _fingerprint("vector", str(decoded))
445
452
  return result
446
453
 
447
454
  def _table_present(
@@ -496,11 +503,11 @@ class VectorOwner(_FactScopedOwner):
496
503
  raw = dict(rows[0]).get("embedding")
497
504
  if not raw:
498
505
  return False
499
- try:
500
- embedding = json.loads(raw)
501
- except (TypeError, json.JSONDecodeError):
502
- return False
503
- if not isinstance(embedding, list) or not embedding:
506
+ # decode_embedding accepts both TEXT (JSON) and BLOB (float32 binary);
507
+ # ValueError for corrupt data propagates — a heal that silently
508
+ # returns False on corruption is indistinguishable from "not present".
509
+ embedding = decode_embedding(raw, fact_id=fact_id)
510
+ if not embedding:
504
511
  return False
505
512
  ok = self._vector_store.upsert(
506
513
  fact_id=fact_id, profile_id=context.profile_id, embedding=embedding,
@@ -29,12 +29,14 @@ from __future__ import annotations
29
29
 
30
30
  import json
31
31
  import logging
32
+ import sqlite3
32
33
  from typing import TYPE_CHECKING
33
34
 
34
35
  import numpy as np
35
36
  from numpy.typing import NDArray
36
37
 
37
38
  from superlocalmemory.core.config import QuantizationConfig
39
+ from superlocalmemory.storage.embedding_codec import decode_embedding
38
40
 
39
41
  if TYPE_CHECKING:
40
42
  from superlocalmemory.math.ebbinghaus import EbbinghausCurve
@@ -262,7 +264,13 @@ class EAPScheduler:
262
264
  Tries embedding_metadata -> fact_embeddings (vec0 table).
263
265
  Falls back to atomic_facts.embedding JSON column.
264
266
  """
265
- # Try atomic_facts.embedding (JSON column)
267
+ # Try atomic_facts.embedding (TEXT JSON or BLOB float32).
268
+ # Two-stage error handling:
269
+ # - DB query failures (any exception from execute) → log + return None.
270
+ # - Format errors from decode_embedding (ValueError) → propagate.
271
+ # A corrupt embedding must NOT be silently collapsed to None because
272
+ # the caller cannot distinguish "embedding absent" from "data lost".
273
+ raw = None
266
274
  try:
267
275
  rows = self._db.execute(
268
276
  "SELECT embedding FROM atomic_facts WHERE fact_id = ?",
@@ -270,14 +278,17 @@ class EAPScheduler:
270
278
  )
271
279
  if rows:
272
280
  raw = dict(rows[0]).get("embedding")
273
- if raw and raw != "null":
274
- data = json.loads(raw) if isinstance(raw, str) else raw
275
- if data:
276
- return np.array(data, dtype=np.float64)
277
- except Exception as exc:
281
+ except Exception as exc: # noqa: BLE001 — isolates DB failure from decode failure
278
282
  logger.debug(
279
283
  "Could not load embedding from atomic_facts for %s: %s",
280
284
  fact_id, exc,
281
285
  )
286
+ return None
287
+
288
+ if raw and raw != "null":
289
+ # ValueError from decode_embedding propagates intentionally.
290
+ vec = decode_embedding(raw, fact_id=fact_id)
291
+ if vec:
292
+ return np.array(vec, dtype=np.float64)
282
293
 
283
294
  return None
@@ -9,7 +9,7 @@ last 50 memories; this version searches ALL facts per canonical entity.
9
9
 
10
10
  Edge types: ENTITY (shared entity, weight 1.0), TEMPORAL (exp-decay,
11
11
  1-week window), SEMANTIC (ANN cosine > 0.7), CAUSAL (causal markers,
12
- weight 0.8). CONTRADICTION exposed for external Sheaf module (Wave 4).
12
+ weight 0.8). CONTRADICTION exposed for external Sheaf module (added in v3.5).
13
13
 
14
14
  Part of Qualixar | Author: Varun Pratap Bhardwaj
15
15
  License: AGPL-3.0-or-later
@@ -101,7 +101,7 @@ class GraphBuilder:
101
101
  self, fact_id_a: str, fact_id_b: str, profile_id: str,
102
102
  severity: float = 1.0,
103
103
  ) -> GraphEdge:
104
- """Add a contradiction edge. Called by Sheaf module (Wave 4)."""
104
+ """Add a contradiction edge. Called by the Sheaf module (introduced in v3.5)."""
105
105
  edge = GraphEdge(
106
106
  profile_id=profile_id,
107
107
  source_id=fact_id_a,
@@ -15,6 +15,8 @@ Part of Qualixar | Author: Varun Pratap Bhardwaj
15
15
  from __future__ import annotations
16
16
 
17
17
  import json
18
+
19
+ from superlocalmemory.storage.embedding_codec import decode_embedding
18
20
  import logging
19
21
  from datetime import UTC, datetime
20
22
 
@@ -357,8 +359,12 @@ class SceneBuilder:
357
359
  embedding = None
358
360
  if raw_embedding:
359
361
  try:
360
- embedding = json.loads(raw_embedding)
361
- except (TypeError, ValueError, json.JSONDecodeError):
362
+ embedding = decode_embedding(
363
+ raw_embedding, fact_id=str(data.get("scene_id", "<scene>")),
364
+ )
365
+ except ValueError:
366
+ # A malformed stored value, not an absent one. Scenes are an
367
+ # optimisation, so one bad row must not sink the batch.
362
368
  embedding = None
363
369
  result[str(data["scene_id"])] = embedding
364
370
  return result
@@ -140,9 +140,24 @@ class SkillEvolver:
140
140
  # automatically. Tests inject their own.
141
141
  if budget is None:
142
142
  slm_home = canonical_data_root()
143
+ # ``learning_db`` must be learning.db: migration M010 creates
144
+ # evolution_llm_cost_log there. Every production caller
145
+ # (consolidation_engine, routes/evolution, MCP, CLI) passes
146
+ # memory.db as db_path, so handing db_path straight to the budget
147
+ # pointed it at a database where that table does not exist. Every
148
+ # evolution cycle then died with "no such table:
149
+ # evolution_llm_cost_log" — swallowed at debug level in
150
+ # consolidation step 11, so skill evolution silently never ran.
151
+ #
152
+ # Redirect only for the exact production filename. Tests pass
153
+ # ":memory:" or their own tmp file and must keep the old behaviour,
154
+ # rather than having a learning.db invented beside them.
155
+ learning_db = Path(self._db_path)
156
+ if learning_db.name == "memory.db":
157
+ learning_db = learning_db.parent / "learning.db"
143
158
  budget = EvolutionBudget(
144
159
  profile_id=profile_id,
145
- learning_db=Path(self._db_path),
160
+ learning_db=learning_db,
146
161
  lock_dir=slm_home,
147
162
  )
148
163
  self._budget = budget
@@ -4,8 +4,6 @@
4
4
 
5
5
  """Cross-platform adapter base — shared Protocol and atomic write primitive.
6
6
 
7
- LLD reference: ``.backup/active-brain/lld/LLD-05-cross-platform-adapters.md``
8
- Sections: 2 (component catalog), 4.4 (atomic write), 9.3 (sync log contract).
9
7
 
10
8
  Every adapter (Cursor, Antigravity, Copilot) implements the ``Adapter``
11
9
  Protocol. The shared ``_atomic_write`` primitive enforces the hard-rule
@@ -4,8 +4,6 @@
4
4
 
5
5
  """Shared content builder — single source for every adapter body.
6
6
 
7
- LLD reference: ``.backup/active-brain/lld/LLD-05-cross-platform-adapters.md``
8
- Section 3 (Content Builder). One builder → five formatters. Every string is
9
7
  passed through ``redact_secrets`` before entering the dataclass, so no
10
8
  adapter ever writes an unredacted secret.
11
9
 
@@ -768,7 +768,29 @@ def _run_quiet(cmd: list[str], timeout: int = 5, postprocess=None) -> str:
768
768
 
769
769
 
770
770
  def _maybe_consolidate() -> None:
771
- """Run cognitive consolidation if last run was >24h ago. Non-blocking."""
771
+ """Ask the daemon for a full consolidation if the last one was >24h ago.
772
+
773
+ Three things were wrong here before 4.0.8, and together they meant the
774
+ behavioural half of consolidation never ran on a real install:
775
+
776
+ 1. **It ran the wrong pipeline.** ``slm consolidate --cognitive`` invokes
777
+ ``CognitiveConsolidator.run_pipeline()``. Behavioural assertion mining,
778
+ soft prompts, skill performance and skill evolution are steps 8-11 of
779
+ ``ConsolidationEngine.consolidate()`` — a different class entirely. On a
780
+ store with thousands of tool events, ``behavioral_assertions`` stayed at
781
+ zero rows while the miner, run once by hand, produced 9 immediately.
782
+ 2. **It marked success before trying.** The 24h timestamp was written
783
+ *before* the subprocess launched, so a run that failed instantly still
784
+ bought a full day of silence. The marker is now written only after the
785
+ daemon confirms it scheduled the work.
786
+ 3. **It could not fail visibly.** stdout and stderr went to DEVNULL and the
787
+ handler ended in a bare ``except: pass``, so nothing anywhere recorded a
788
+ failure. Errors now surface on stderr, where the hook runner logs them.
789
+
790
+ Non-blocking: the daemon schedules the pass and returns immediately, so
791
+ session end is never held up by a run that takes minutes. The daemon's own
792
+ periodic timer is the backstop for sessions where this hook never fires.
793
+ """
772
794
  try:
773
795
  last_ts = 0
774
796
  last_consolidation = _last_consolidation_path()
@@ -780,16 +802,21 @@ def _maybe_consolidate() -> None:
780
802
  if (now - last_ts) < 86400: # 24 hours
781
803
  return
782
804
 
783
- # Update timestamp FIRST to prevent concurrent runs
805
+ started = _daemon_post(
806
+ "/api/v3/consolidation/trigger",
807
+ {"lightweight": False, "background": True},
808
+ )
809
+ if not started:
810
+ # No marker written — the next session end retries. The daemon's
811
+ # consolidation lock makes a duplicate request a cheap no-op.
812
+ print(
813
+ "slm: consolidation could not be scheduled (daemon unreachable)",
814
+ file=sys.stderr,
815
+ )
816
+ return
817
+
784
818
  os.makedirs(os.path.dirname(last_consolidation), exist_ok=True)
785
819
  with open(last_consolidation, "w") as f:
786
820
  f.write(str(now))
787
-
788
- # Run consolidation in background (don't block session end)
789
- subprocess.Popen(
790
- ["slm", "consolidate", "--cognitive"],
791
- stdout=subprocess.DEVNULL,
792
- stderr=subprocess.DEVNULL,
793
- )
794
- except Exception:
795
- pass
821
+ except Exception as exc:
822
+ print(f"slm: consolidation trigger failed: {exc}", file=sys.stderr)
@@ -2,16 +2,16 @@
2
2
  # Licensed under AGPL-3.0-or-later - see LICENSE file
3
3
  # Part of SuperLocalMemory V3 | https://qualixar.com
4
4
 
5
- """WP-08 portable kit — ``slm connect <ide>`` MCP-wiring.
5
+ """Portable kit — ``slm connect <ide>`` MCP-wiring.
6
6
 
7
7
  Writes SLM's MCP block into the target IDE config via MERGE-NOT-CLOBBER:
8
8
  - Only touches the ``superlocalmemory`` server key.
9
9
  - All other servers + top-level keys are preserved byte-for-byte.
10
10
  - Atomic write (.tmp + os.replace); aborts on parse error (file untouched).
11
- - claude-code is OUT: short-circuits to a WP-06 plugin pointer, no config written.
11
+ - claude-code is OUT: short-circuits to a plugin pointer, no config written.
12
12
  - AGENTS.md is appended with <!-- SLM-START/END --> markers (never overwrite).
13
13
 
14
- IDE_MATRIX verified against ide/configs/* templates (read-only, WP-04 owns).
14
+ IDE_MATRIX verified against ide/configs/* templates (read-only; configs are the authoritative source).
15
15
  """
16
16
 
17
17
  from __future__ import annotations
@@ -39,7 +39,7 @@ SLM_MARKER_END = "<!-- SLM-END -->"
39
39
  VALID_TRANSPORTS: frozenset[str] = frozenset({"stdio", "http", "http-mcp-remote"})
40
40
 
41
41
  CLAUDE_CODE_PLUGIN_POINTER = (
42
- "slm connect claude-code: Claude Code is configured via the SLM plugin (WP-06).\n"
42
+ "slm connect claude-code: Claude Code is configured via the SLM plugin (see plugin/ directory).\n"
43
43
  "Run: slm plugin install OR see plugin-src/ for manual installation.\n"
44
44
  "No MCP config file is written by this command."
45
45
  )
@@ -206,17 +206,17 @@ IDE_MATRIX: dict[str, IDEDescriptor] = {
206
206
  },
207
207
  caveats="contextProviders is a LIST; append+dedupe by serverName",
208
208
  ),
209
- # --- OUT: claude-code defers to WP-06 ---
209
+ # --- OUT: claude-code defers to the plugin installer ---
210
210
  "claude-code": IDEDescriptor(
211
211
  ide_id="claude-code",
212
- display="Claude Code (WP-06 plugin)",
212
+ display="Claude Code (plugin)",
213
213
  mcp_path_global="",
214
214
  mcp_path_project=None,
215
215
  server_key="",
216
216
  fmt="",
217
217
  agents_md_path=None,
218
218
  server_block={},
219
- caveats="OUT — WP-06 plugin pointer only; no MCP config written",
219
+ caveats="OUT — plugin pointer only; no MCP config written",
220
220
  ),
221
221
  # --- EXPERIMENTAL (gated, not wired by default) ---
222
222
  # chatgpt-desktop, perplexity, cody: gated behind --experimental
@@ -702,7 +702,7 @@ if __name__ == "__main__": # pragma: no cover
702
702
  metavar="IDE",
703
703
  help=(
704
704
  "IDE ids to connect. Pass 'all' to connect every supported IDE "
705
- "(excluding claude-code which uses the WP-06 plugin)."
705
+ "(excluding claude-code which uses the plugin installer)."
706
706
  ),
707
707
  )
708
708
  _parser.add_argument("--home", help="Override home directory (test hook).")
@@ -4,8 +4,6 @@
4
4
 
5
5
  """PostToolUse async:true hook — fire-and-forget prewarm via stdlib urllib.
6
6
 
7
- LLD reference: `.backup/active-brain/lld/LLD-01-context-cache-and-hot-path-hooks.md`
8
- Section 4.4.
9
7
 
10
8
  HARD RULES (enforced by tests):
11
9
  - stdlib only — ``urllib.request``, NOT ``httpx`` / ``requests``.
@@ -4,8 +4,6 @@
4
4
 
5
5
  """Authentication primitives for the /internal/prewarm daemon route.
6
6
 
7
- LLD reference: `.backup/active-brain/lld/LLD-01-context-cache-and-hot-path-hooks.md`
8
- Section 4.5.
9
7
 
10
8
  Four gates, applied in order, BEFORE any engine work:
11
9
  1. Loopback-only — client address must be 127.0.0.1 / ::1.
@@ -4,8 +4,6 @@
4
4
 
5
5
  """UserPromptSubmit hook — Python fallback (compiled binary preferred).
6
6
 
7
- LLD reference: `.backup/active-brain/lld/LLD-01-context-cache-and-hot-path-hooks.md`
8
- Section 4.3.
9
7
 
10
8
  HARD RULES (enforced by tests):
11
9
  - stdlib-only imports at module load (SLM modules delayed-imported).
@@ -16,6 +16,7 @@ import hashlib
16
16
  import json
17
17
  import logging
18
18
  import shutil
19
+ import tempfile
19
20
  import sqlite3
20
21
  import time
21
22
  import uuid
@@ -735,15 +736,50 @@ class BackupManager:
735
736
  target = self.db_path.parent / target_name
736
737
 
737
738
  try:
738
- self.create_backup(label="pre-restore")
739
+ # Stage the source OUTSIDE backup_dir before anything else runs.
740
+ #
741
+ # create_backup() below calls _enforce_retention(), which globs this
742
+ # same directory and unlinks the oldest files — including, when the
743
+ # backup being restored is the oldest, the source itself. A plain
744
+ # sqlite3.connect() on that now-missing path RECREATES it as an
745
+ # empty database, which is then copied over the live store while the
746
+ # call returns True, leaving a zero-byte file under the original
747
+ # name so a second attempt also appears to succeed.
748
+ #
749
+ # Reproduced before this fix: 11 snapshots, max_backups=10, a
750
+ # 500-fact store restored to 0 tables, restore_backup() -> True.
751
+ with tempfile.TemporaryDirectory(prefix="slm-restore-") as staging:
752
+ staged = Path(staging) / filename
753
+
754
+ # mode=ro fails loudly on a missing file instead of creating one.
755
+ src_ro = sqlite3.connect(f"file:{backup_path}?mode=ro", uri=True)
756
+ try:
757
+ if not [r[0] for r in src_ro.execute(
758
+ "SELECT name FROM sqlite_master WHERE type='table'")]:
759
+ logger.error(
760
+ "Restore rejected: %s contains no tables — refusing to "
761
+ "overwrite %s with an empty database",
762
+ filename, target_name,
763
+ )
764
+ return False
765
+ staged_dst = sqlite3.connect(str(staged))
766
+ try:
767
+ src_ro.backup(staged_dst)
768
+ finally:
769
+ staged_dst.close()
770
+ finally:
771
+ src_ro.close()
739
772
 
740
- src = sqlite3.connect(str(backup_path))
741
- dst = sqlite3.connect(str(target))
742
- try:
743
- src.backup(dst)
744
- finally:
745
- dst.close()
746
- src.close()
773
+ self.create_backup(label="pre-restore")
774
+
775
+ # Restore from the staged copy, which retention cannot reach.
776
+ src = sqlite3.connect(f"file:{staged}?mode=ro", uri=True)
777
+ dst = sqlite3.connect(str(target))
778
+ try:
779
+ src.backup(dst)
780
+ finally:
781
+ dst.close()
782
+ src.close()
747
783
 
748
784
  logger.info("Restored: %s -> %s", filename, target.name)
749
785