superlocalmemory 3.7.0 → 3.7.2

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 (45) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +2 -2
  3. package/package.json +2 -2
  4. package/plugin/.claude-plugin/plugin.json +1 -1
  5. package/plugin/requirements.txt +1 -1
  6. package/plugin/scripts/slm-launch +11 -3
  7. package/plugin/scripts/slm-launch.bat +8 -2
  8. package/plugin-src/.mcp.json +12 -0
  9. package/plugin-src/agents/slm-memory-advisor.md +44 -0
  10. package/plugin-src/agents/slm-optimize-advisor.md +38 -0
  11. package/plugin-src/hooks/.gitkeep +0 -0
  12. package/plugin-src/hooks/hooks.json +23 -0
  13. package/plugin-src/manifest.json +25 -0
  14. package/plugin-src/requirements.txt +1 -0
  15. package/plugin-src/rules/CLAUDE.md.fragment +44 -0
  16. package/plugin-src/scripts/ensure-venv.bat +122 -0
  17. package/plugin-src/scripts/ensure-venv.sh +105 -0
  18. package/plugin-src/scripts/slm-launch +23 -0
  19. package/plugin-src/scripts/slm-launch.bat +23 -0
  20. package/plugin-src/settings.json +16 -0
  21. package/plugin-src/skills/slm-cache/SKILL.md +140 -0
  22. package/plugin-src/skills/slm-compress/SKILL.md +143 -0
  23. package/plugin-src/skills/slm-graph/SKILL.md +300 -0
  24. package/plugin-src/skills/slm-recall/SKILL.md +204 -0
  25. package/plugin-src/skills/slm-remember/SKILL.md +194 -0
  26. package/plugin-src/skills/slm-session/SKILL.md +207 -0
  27. package/plugin-src/skills/slm-status/SKILL.md +149 -0
  28. package/pyproject.toml +1 -1
  29. package/src/superlocalmemory/__init__.py +1 -1
  30. package/src/superlocalmemory/cli/_lazy_init.py +4 -2
  31. package/src/superlocalmemory/core/embedding_worker.py +7 -1
  32. package/src/superlocalmemory/core/embeddings.py +8 -0
  33. package/src/superlocalmemory/core/engine.py +1 -3
  34. package/src/superlocalmemory/core/engine_wiring.py +30 -28
  35. package/src/superlocalmemory/core/ram_lock.py +42 -4
  36. package/src/superlocalmemory/evolution/budget.py +43 -8
  37. package/src/superlocalmemory/hooks/claude_code_hooks.py +1 -1
  38. package/src/superlocalmemory/hooks/context_payload.py +1 -1
  39. package/src/superlocalmemory/mcp/http_transport.py +1 -1
  40. package/src/superlocalmemory/mcp/tools_core.py +48 -31
  41. package/src/superlocalmemory/mesh/broker.py +111 -61
  42. package/src/superlocalmemory/optimize/proxy/server.py +1 -1
  43. package/src/superlocalmemory/retrieval/spreading_activation.py +53 -3
  44. package/src/superlocalmemory/server/routes/brain.py +1 -1
  45. package/src/superlocalmemory/server/unified_daemon.py +24 -7
@@ -19,7 +19,7 @@ import time
19
19
  import uuid
20
20
  from datetime import datetime, timezone
21
21
  from pathlib import Path
22
- from typing import Any
22
+ from typing import Any, Callable, TypeVar
23
23
 
24
24
  logger = logging.getLogger("superlocalmemory.mesh")
25
25
  import os as _os
@@ -38,6 +38,11 @@ MAX_MESSAGE_SIZE = 4096 # 4KB cap — mesh messages are notifications, not data
38
38
  MESSAGE_TTL_HOURS = 48 # Offline messages expire after 48h
39
39
  MAX_QUEUED_PER_TARGET = 50 # Max unread messages per broadcast/project target
40
40
 
41
+ _T = TypeVar("_T")
42
+ _WRITE_RETRY_ATTEMPTS = 6
43
+ _WRITE_RETRY_BASE_SECONDS = 0.025
44
+ _WRITE_BUSY_TIMEOUT_MS = 250
45
+
41
46
 
42
47
  class MeshBroker:
43
48
  """Lightweight mesh broker for SLM's unified daemon.
@@ -109,22 +114,64 @@ class MeshBroker:
109
114
  # -- Connection helper --
110
115
 
111
116
  def _conn(self) -> sqlite3.Connection:
112
- conn = sqlite3.connect(self._db_path)
113
- conn.execute("PRAGMA journal_mode=WAL")
114
- conn.execute("PRAGMA busy_timeout=5000")
117
+ # WAL is configured during database initialization and persists with the
118
+ # database. Reissuing journal_mode=WAL for every short-lived mesh
119
+ # connection is itself a schema-level write that can contend with the
120
+ # daemon. Mesh writes below use bounded whole-transaction retries.
121
+ conn = sqlite3.connect(
122
+ self._db_path,
123
+ timeout=_WRITE_BUSY_TIMEOUT_MS / 1000,
124
+ )
125
+ conn.execute(f"PRAGMA busy_timeout={_WRITE_BUSY_TIMEOUT_MS}")
115
126
  conn.row_factory = sqlite3.Row
116
127
  return conn
117
128
 
129
+ @staticmethod
130
+ def _is_transient_lock(exc: sqlite3.OperationalError) -> bool:
131
+ message = str(exc).lower()
132
+ return "database is locked" in message or "database is busy" in message
133
+
134
+ def _write_with_retry(
135
+ self,
136
+ operation: Callable[[sqlite3.Connection], _T],
137
+ ) -> _T:
138
+ """Run one idempotent mesh mutation with a bounded SQLite retry budget.
139
+
140
+ SQLite WAL lets reads continue while a write is in progress, but it
141
+ still permits a single writer. Retrying the entire short transaction on
142
+ a fresh connection avoids leaking a transient writer collision to an
143
+ agent heartbeat or mesh command.
144
+ """
145
+ last_error: sqlite3.OperationalError | None = None
146
+ for attempt in range(_WRITE_RETRY_ATTEMPTS):
147
+ conn = self._conn()
148
+ try:
149
+ return operation(conn)
150
+ except sqlite3.OperationalError as exc:
151
+ if not self._is_transient_lock(exc):
152
+ raise
153
+ last_error = exc
154
+ try:
155
+ conn.rollback()
156
+ except sqlite3.Error:
157
+ pass
158
+ finally:
159
+ conn.close()
160
+
161
+ if attempt < _WRITE_RETRY_ATTEMPTS - 1:
162
+ time.sleep(_WRITE_RETRY_BASE_SECONDS * (2 ** attempt))
163
+
164
+ assert last_error is not None
165
+ raise last_error
166
+
118
167
  # -- Peers --
119
168
 
120
169
  def register_peer(self, session_id: str, summary: str = "",
121
170
  host: str = "", port: int = 0,
122
171
  project_path: str = "", agent_type: str = "unknown") -> dict:
123
- conn = self._conn()
124
- try:
172
+ def _register(conn: sqlite3.Connection) -> dict:
125
173
  now = datetime.now(timezone.utc).isoformat()
126
- if not host:
127
- host = self._host
174
+ effective_host = host or self._host
128
175
  # Idempotent: update if same session_id exists
129
176
  existing = conn.execute(
130
177
  "SELECT peer_id FROM mesh_peers WHERE session_id = ?",
@@ -135,7 +182,7 @@ class MeshBroker:
135
182
  conn.execute(
136
183
  "UPDATE mesh_peers SET summary=?, host=?, port=?, last_heartbeat=?, "
137
184
  "status='active', project_path=?, agent_type=? WHERE peer_id=?",
138
- (summary, host, port, now, project_path, agent_type, peer_id),
185
+ (summary, effective_host, port, now, project_path, agent_type, peer_id),
139
186
  )
140
187
  else:
141
188
  peer_id = str(uuid.uuid4())[:12]
@@ -143,7 +190,7 @@ class MeshBroker:
143
190
  "INSERT INTO mesh_peers (peer_id, session_id, summary, status, host, port, "
144
191
  "registered_at, last_heartbeat, project_path, agent_type) "
145
192
  "VALUES (?, ?, ?, 'active', ?, ?, ?, ?, ?, ?)",
146
- (peer_id, session_id, summary, host, port, now, now, project_path, agent_type),
193
+ (peer_id, session_id, summary, effective_host, port, now, now, project_path, agent_type),
147
194
  )
148
195
  self._log_event(conn, "peer_registered", peer_id, {
149
196
  "session_id": session_id, "project_path": project_path,
@@ -153,12 +200,11 @@ class MeshBroker:
153
200
  # v3.4.6: Deliver pending broadcast/project messages on registration
154
201
  pending = self._get_pending_for_peer(conn, peer_id, project_path)
155
202
  return {"peer_id": peer_id, "ok": True, "pending_messages": len(pending)}
156
- finally:
157
- conn.close()
203
+
204
+ return self._write_with_retry(_register)
158
205
 
159
206
  def deregister_peer(self, peer_id: str) -> dict:
160
- conn = self._conn()
161
- try:
207
+ def _deregister(conn: sqlite3.Connection) -> dict:
162
208
  row = conn.execute("SELECT 1 FROM mesh_peers WHERE peer_id=?", (peer_id,)).fetchone()
163
209
  if not row:
164
210
  return {"ok": False, "error": "peer not found"}
@@ -166,12 +212,11 @@ class MeshBroker:
166
212
  self._log_event(conn, "peer_deregistered", peer_id)
167
213
  conn.commit()
168
214
  return {"ok": True}
169
- finally:
170
- conn.close()
215
+
216
+ return self._write_with_retry(_deregister)
171
217
 
172
218
  def heartbeat(self, peer_id: str) -> dict:
173
- conn = self._conn()
174
- try:
219
+ def _heartbeat(conn: sqlite3.Connection) -> dict:
175
220
  now = datetime.now(timezone.utc).isoformat()
176
221
  cursor = conn.execute(
177
222
  "UPDATE mesh_peers SET last_heartbeat=?, status='active' WHERE peer_id=?",
@@ -181,12 +226,11 @@ class MeshBroker:
181
226
  return {"ok": False, "error": "peer not found"}
182
227
  conn.commit()
183
228
  return {"ok": True}
184
- finally:
185
- conn.close()
229
+
230
+ return self._write_with_retry(_heartbeat)
186
231
 
187
232
  def update_summary(self, peer_id: str, summary: str) -> dict:
188
- conn = self._conn()
189
- try:
233
+ def _update_summary(conn: sqlite3.Connection) -> dict:
190
234
  cursor = conn.execute(
191
235
  "UPDATE mesh_peers SET summary=? WHERE peer_id=?",
192
236
  (summary, peer_id),
@@ -195,8 +239,8 @@ class MeshBroker:
195
239
  return {"ok": False, "error": "peer not found"}
196
240
  conn.commit()
197
241
  return {"ok": True}
198
- finally:
199
- conn.close()
242
+
243
+ return self._write_with_retry(_update_summary)
200
244
 
201
245
  def list_peers(self) -> list[dict]:
202
246
  conn = self._conn()
@@ -219,8 +263,19 @@ class MeshBroker:
219
263
  return {"ok": False, "error": f"message too large ({len(content)} bytes, max {MAX_MESSAGE_SIZE}). "
220
264
  "Mesh messages are notifications — reference a file path instead."}
221
265
 
222
- conn = self._conn()
223
- try:
266
+ # Remote delivery is an external side effect, so do it outside the
267
+ # retry envelope. Local writes below are retried as a whole short
268
+ # transaction when another daemon-owned operation has SQLite's writer.
269
+ if to_peer in self._remote_peers and self._sync_client:
270
+ return self._sync_client.send_to_remote(to_peer, {
271
+ "from_peer": from_peer,
272
+ "to": to_peer,
273
+ "content": content,
274
+ "type": msg_type,
275
+ })
276
+
277
+ def _send(conn: sqlite3.Connection) -> dict:
278
+ nonlocal to_peer, project_path
224
279
  now = datetime.now(timezone.utc).isoformat()
225
280
  expires_at = self._compute_expires(now)
226
281
 
@@ -233,14 +288,6 @@ class MeshBroker:
233
288
  to_peer = "project"
234
289
  else:
235
290
  target_type = "peer"
236
- # Check if this is a remote peer — proxy to remote SLM
237
- if to_peer in self._remote_peers and self._sync_client:
238
- return self._sync_client.send_to_remote(to_peer, {
239
- "from_peer": from_peer,
240
- "to": to_peer,
241
- "content": content,
242
- "type": msg_type,
243
- })
244
291
  # Verify recipient exists for direct messages
245
292
  if not conn.execute("SELECT 1 FROM mesh_peers WHERE peer_id=?", (to_peer,)).fetchone():
246
293
  return {"ok": False, "error": "recipient peer not found"}
@@ -272,8 +319,8 @@ class MeshBroker:
272
319
  conn.commit()
273
320
  return {"ok": True, "id": cursor.lastrowid, "target_type": target_type,
274
321
  "expires_at": expires_at}
275
- finally:
276
- conn.close()
322
+
323
+ return self._write_with_retry(_send)
277
324
 
278
325
  def get_inbox(self, peer_id: str, project_path: str = "") -> list[dict]:
279
326
  """Get all messages for this peer: direct + broadcast + project."""
@@ -331,8 +378,7 @@ class MeshBroker:
331
378
  conn.close()
332
379
 
333
380
  def mark_read(self, peer_id: str, message_ids: list[int]) -> dict:
334
- conn = self._conn()
335
- try:
381
+ def _mark_read(conn: sqlite3.Connection) -> dict:
336
382
  now = datetime.now(timezone.utc).isoformat()
337
383
  for msg_id in message_ids:
338
384
  # Check if this is a direct message or broadcast/project
@@ -356,8 +402,8 @@ class MeshBroker:
356
402
  )
357
403
  conn.commit()
358
404
  return {"ok": True, "marked": len(message_ids)}
359
- finally:
360
- conn.close()
405
+
406
+ return self._write_with_retry(_mark_read)
361
407
 
362
408
  # -- State --
363
409
 
@@ -370,8 +416,7 @@ class MeshBroker:
370
416
  conn.close()
371
417
 
372
418
  def set_state(self, key: str, value: str, set_by: str) -> dict:
373
- conn = self._conn()
374
- try:
419
+ def _set_state(conn: sqlite3.Connection) -> dict:
375
420
  now = datetime.now(timezone.utc).isoformat()
376
421
  conn.execute(
377
422
  "INSERT INTO mesh_state (key, value, set_by, updated_at) VALUES (?, ?, ?, ?) "
@@ -380,8 +425,8 @@ class MeshBroker:
380
425
  )
381
426
  conn.commit()
382
427
  return {"ok": True}
383
- finally:
384
- conn.close()
428
+
429
+ return self._write_with_retry(_set_state)
385
430
 
386
431
  def get_state_key(self, key: str) -> dict | None:
387
432
  conn = self._conn()
@@ -396,8 +441,23 @@ class MeshBroker:
396
441
  # -- Locks --
397
442
 
398
443
  def lock_action(self, file_path: str, locked_by: str, action: str) -> dict:
399
- conn = self._conn()
400
- try:
444
+ if action == "query":
445
+ conn = self._conn()
446
+ try:
447
+ row = conn.execute(
448
+ "SELECT locked_by, locked_at FROM mesh_locks WHERE file_path=?",
449
+ (file_path,),
450
+ ).fetchone()
451
+ if row:
452
+ return {"locked": True, "by": row["locked_by"], "since": row["locked_at"]}
453
+ return {"locked": False}
454
+ finally:
455
+ conn.close()
456
+
457
+ if action not in {"acquire", "release"}:
458
+ return {"ok": False, "error": f"unknown action: {action}"}
459
+
460
+ def _lock_action(conn: sqlite3.Connection) -> dict:
401
461
  now = datetime.now(timezone.utc).isoformat()
402
462
 
403
463
  if action == "acquire":
@@ -429,18 +489,9 @@ class MeshBroker:
429
489
  return {"ok": False, "action": "not_released",
430
490
  "error": "no lock held by this peer for that file"}
431
491
 
432
- elif action == "query":
433
- row = conn.execute(
434
- "SELECT locked_by, locked_at FROM mesh_locks WHERE file_path=?",
435
- (file_path,),
436
- ).fetchone()
437
- if row:
438
- return {"locked": True, "by": row["locked_by"], "since": row["locked_at"]}
439
- return {"locked": False}
492
+ raise AssertionError("validated action was not handled")
440
493
 
441
- return {"ok": False, "error": f"unknown action: {action}"}
442
- finally:
443
- conn.close()
494
+ return self._write_with_retry(_lock_action)
444
495
 
445
496
  # -- Helpers (v3.4.6) --
446
497
 
@@ -527,8 +578,7 @@ class MeshBroker:
527
578
  logger.debug("Mesh cleanup error: %s", exc)
528
579
 
529
580
  def _run_cleanup(self) -> None:
530
- conn = self._conn()
531
- try:
581
+ def _cleanup(conn: sqlite3.Connection) -> None:
532
582
  now = datetime.now(timezone.utc)
533
583
  now_iso = now.isoformat()
534
584
  # Mark stale peers (no heartbeat for 5 min)
@@ -572,5 +622,5 @@ class MeshBroker:
572
622
  (now_iso,),
573
623
  )
574
624
  conn.commit()
575
- finally:
576
- conn.close()
625
+
626
+ self._write_with_retry(_cleanup)
@@ -17,7 +17,7 @@ from superlocalmemory.optimize.proxy.lifecycle import HookChain
17
17
 
18
18
  logger = logging.getLogger("slm.optimize.proxy")
19
19
 
20
- _PROXY_VERSION = "3.7.0"
20
+ _PROXY_VERSION = "3.7.1"
21
21
  _REQUEST_TIMEOUT_S = 300.0
22
22
  _CONNECT_TIMEOUT_S = 10.0
23
23
  _MAX_CONNECTIONS = 100
@@ -93,7 +93,7 @@ class SpreadingActivation:
93
93
  def __init__(
94
94
  self,
95
95
  db: Any,
96
- vector_store: Any,
96
+ vector_store: Any | None,
97
97
  config: SpreadingActivationConfig | None = None,
98
98
  ) -> None:
99
99
  self._db = db
@@ -122,8 +122,11 @@ class SpreadingActivation:
122
122
  include_shared = bool(getattr(self, "include_shared", False))
123
123
  try:
124
124
  # Step 0: Get seed nodes from VectorStore KNN
125
- seed_results = self._vector_store.search(
126
- query, top_k=self._config.top_m, profile_id=profile_id,
125
+ seed_results = self._seed_search(
126
+ query,
127
+ profile_id,
128
+ include_global=include_global,
129
+ include_shared=include_shared,
127
130
  )
128
131
  # Owner-partitioned vector indexes cannot discover opted-in peers.
129
132
  # Add visible external embeddings with the same cosine seed signal.
@@ -216,6 +219,53 @@ class SpreadingActivation:
216
219
  )
217
220
  return []
218
221
 
222
+ def _seed_search(
223
+ self,
224
+ query: Any,
225
+ profile_id: str,
226
+ *,
227
+ include_global: bool,
228
+ include_shared: bool,
229
+ ) -> list[tuple[str, float]]:
230
+ """Return bounded semantic graph seeds from vec0 or canonical SQLite.
231
+
232
+ sqlite-vec is an acceleration projection, not a prerequisite for the
233
+ graph retrieval layer. When it is unavailable on a platform, use the
234
+ canonical stored embeddings and the same cosine signal as the
235
+ cross-profile supplement below. This keeps spreading activation
236
+ present and truthful rather than silently removing a retrieval layer.
237
+ """
238
+ if self._vector_store is not None and getattr(
239
+ self._vector_store, "available", False,
240
+ ):
241
+ return self._vector_store.search(
242
+ query, top_k=self._config.top_m, profile_id=profile_id,
243
+ )
244
+
245
+ q_vec = np.array(query, dtype=np.float32)
246
+ q_norm = float(np.linalg.norm(q_vec))
247
+ if q_norm <= 1e-8:
248
+ return []
249
+ facts = self._db.get_all_facts(
250
+ profile_id,
251
+ include_global=include_global,
252
+ include_shared=include_shared,
253
+ )
254
+ scored: list[tuple[str, float]] = []
255
+ for fact in facts:
256
+ embedding = getattr(fact, "embedding", None)
257
+ if embedding is None:
258
+ continue
259
+ fact_vec = np.array(embedding, dtype=np.float32)
260
+ if fact_vec.shape != q_vec.shape:
261
+ continue
262
+ denominator = q_norm * float(np.linalg.norm(fact_vec))
263
+ if denominator <= 1e-8:
264
+ continue
265
+ score = (float(np.dot(q_vec, fact_vec) / denominator) + 1.0) / 2.0
266
+ scored.append((fact.fact_id, score))
267
+ return sorted(scored, key=lambda item: item[1], reverse=True)[:self._config.top_m]
268
+
219
269
  def _propagate(
220
270
  self,
221
271
  seeds: list[tuple[str, float]],
@@ -64,7 +64,7 @@ router = APIRouter(prefix="/api/v3", tags=["brain"])
64
64
  # LLD-03 v2 stratum space = 4 query types × 3 entity bins × 4 time buckets.
65
65
  _STRATA_TOTAL: int = 48
66
66
 
67
- _VERSION: str = "3.7.0"
67
+ _VERSION: str = "3.7.1"
68
68
 
69
69
  # Banned metric names (LLD-04 U4). Kept as a tuple for grep visibility;
70
70
  # the source-level test asserts we don't accidentally reintroduce them.
@@ -2138,18 +2138,33 @@ def _register_daemon_routes(application: FastAPI) -> None:
2138
2138
  ))
2139
2139
 
2140
2140
  result = command.materialize(receipt.operation_id) if wait else receipt
2141
- if result.state is IngestionState.FAILED:
2142
- raise RuntimeError(result.last_error or "materialization failed")
2143
-
2144
2141
  fact_ids = list(result.fact_ids)
2142
+ # The queryable write is a separate durable transaction. A cold
2143
+ # optional enrichment dependency (most often the local embedding
2144
+ # worker) may need its bounded retry window, but must not turn an
2145
+ # already-admitted fact into an HTTP 500. Keep the operation's
2146
+ # failed state truthful so the daemon materializer retries it; the
2147
+ # response communicates that the fact is queryable, not complete.
2148
+ enrichment_deferred = (
2149
+ result.state is IngestionState.FAILED and bool(fact_ids)
2150
+ )
2151
+ if result.state is IngestionState.FAILED and not enrichment_deferred:
2152
+ raise RuntimeError(result.last_error or "materialization failed")
2153
+ completed = result.state is IngestionState.COMPLETE
2145
2154
  _emit_event(
2146
- "memory.stored" if wait else "memory.queued",
2155
+ "memory.stored" if completed else "memory.queued",
2147
2156
  payload={
2148
2157
  "operation_id": result.operation_id,
2149
2158
  "fact_ids": fact_ids,
2150
2159
  "tags": req.tags or "",
2151
2160
  "content_preview": req.content[:120],
2152
- "path": "remember_sync" if wait else "remember_queryable",
2161
+ "path": (
2162
+ "remember_sync"
2163
+ if completed
2164
+ else "remember_sync_deferred"
2165
+ if enrichment_deferred
2166
+ else "remember_queryable"
2167
+ ),
2153
2168
  },
2154
2169
  )
2155
2170
  return {
@@ -2160,11 +2175,13 @@ def _register_daemon_routes(application: FastAPI) -> None:
2160
2175
  # One-release compatibility alias. The durable operation ID is
2161
2176
  # opaque and replaces the integer pending.db row identifier.
2162
2177
  "pending_id": result.operation_id,
2163
- "status": "stored" if wait else "queryable",
2178
+ "status": "stored" if completed else "queryable",
2164
2179
  "materialization_state": result.state.value,
2165
2180
  "note": (
2166
2181
  "canonical ingestion complete"
2167
- if wait
2182
+ if completed
2183
+ else "queryable now; canonical enrichment will retry"
2184
+ if enrichment_deferred
2168
2185
  else "queryable now; canonical enrichment pending"
2169
2186
  ),
2170
2187
  }