superlocalmemory 3.6.5 → 3.6.7

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/CHANGELOG.md CHANGED
@@ -5,6 +5,70 @@ All notable changes to SuperLocalMemory V3 will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [3.6.7] - 2026-06-10 — MCP Streamable-HTTP Transport (Embedded)
9
+
10
+ ### Added
11
+ - **Embedded MCP HTTP Transport:** The FastMCP server is now mounted directly inside the unified daemon at `/mcp`. All MCP clients (Claude Code, subagents, desktop, Hermes) now share a single daemon process instead of spawning separate `slm mcp` subprocesses per connection, eliminating process overhead and orphaned process risks.
12
+ - **Graceful Fallback:** If the HTTP mount fails, the daemon continues to operate normally, preserving stdio transport compatibility.
13
+
14
+ ### Changed
15
+ - **Thread Suppression in Daemon Context:** Three background threads that are safe in a standalone `slm mcp` subprocess but harmful inside the daemon are now suppressed when `SLM_MCP_EMBEDDED=1`:
16
+ - `mcp-warmup` thread (prevents duplicate LIGHT engine creation)
17
+ - `parent-watchdog` thread (prevents accidental daemon termination via `os._exit(0)`)
18
+ - `stdin-eof-monitor` thread (irrelevant inside the daemon process)
19
+ - **Session Manager Idempotency:** Added defensive reset of `_session_manager` during app creation to guarantee safe re-initialization if the app factory is called multiple times in the same process.
20
+
21
+ ### Fixed
22
+ - **Lifespan Ordering:** Ensured the MCP Streamable-HTTP session manager lifecycle is correctly wrapped in an `AsyncExitStack` within the daemon's lifespan, preventing "Task group is not initialized" errors on `/mcp` requests.
23
+ - **Route Prefix Stripping:** Explicitly set `streamable_http_path="/"` on the FastMCP instance so that FastAPI's mount prefix stripping correctly routes requests to the sub-app's root endpoint.
24
+
25
+ ## [3.6.6] - 2026-06-10 — Recall precision & memory hygiene
26
+
27
+ Memory means providing the best data, not the most data. v3.6.6 makes recall
28
+ output disciplined and the write path quality-gated, with full parity across
29
+ MCP, CLI, the daemon HTTP route, the in-process adapter, and the WorkerPool
30
+ fallback (identical output regardless of surface or mode A/B).
31
+
32
+ ### Added
33
+
34
+ - **Evidence floor (recall):** results must earn retrieval evidence — semantic
35
+ cosine ≥ 0.60, or BM25 / entity-graph / temporal signal, or a pinned fact.
36
+ Associative-only channels (spreading-activation, hopfield) no longer fabricate
37
+ matches. A query with no confident match returns an empty result set plus
38
+ `no_confident_match: true` instead of filler. Config:
39
+ `retrieval.evidence_floor_enabled`, `retrieval.min_semantic_evidence`.
40
+ Kill-switch: `SLM_RECALL_NO_FLOOR=1`.
41
+ - **Recall output budget:** per-fact content clamp (default 2,400 chars,
42
+ head+tail preserved) and per-response budget (default 12,000 chars; remaining
43
+ results returned as stubs). New optional `full=true` parameter bypasses
44
+ clamping; clamped results carry `truncated: true`. Config:
45
+ `retrieval.recall_per_fact_max_chars`, `retrieval.recall_total_max_chars`.
46
+ - **source_content discipline:** `source_content` defaults to a ≤280-char
47
+ preview (`include_source=true` restores full); internal prompt-template
48
+ content is never returned.
49
+ - **Ingest gate (remember):** content over 24,000 chars is stored as a
50
+ head+tail-clamped fact while the full original is preserved in the source
51
+ memory record; content over 1MB is rejected. Prompt-template text can no
52
+ longer be stored as a memory. Config: `store.max_verbatim_chars`,
53
+ `store.max_ingest_bytes`. Kill-switch: `SLM_INGEST_NO_GATE=1`.
54
+ - **Core-block hygiene:** core memory blocks now deduplicate lines at compile
55
+ time, drop low-quality/template source facts, enforce a per-block char cap,
56
+ and recompile on the daily maintenance schedule.
57
+
58
+ ### Compatibility
59
+
60
+ - All MCP/HTTP/CLI signatures unchanged; new parameters and response fields are
61
+ additive. No database schema migrations. Every new behavior has a config
62
+ field and an environment kill-switch.
63
+
64
+ ## [3.6.5] - 2026-06-09 — Dependency-check hardening
65
+
66
+ ### Fixed
67
+
68
+ - Dependency version check no longer eager-imports `torch` into every process
69
+ (caused a Python 3.14 test segfault and Apple-Silicon memory blow-up); now
70
+ uses `importlib.metadata.version()`.
71
+
8
72
  ## [3.6.4] - 2026-06-09 — Memory-integrity & reliability hardening
9
73
 
10
74
  ### Fixed
package/README.md CHANGED
@@ -309,6 +309,32 @@ slm status
309
309
 
310
310
  ### MCP Integration (Claude, Cursor, Windsurf, VS Code, etc.)
311
311
 
312
+ SLM supports **two MCP transports** — use whichever fits your tool. Both expose the same 33 tools and 7 resources.
313
+
314
+ #### Option A — HTTP transport (v3.6.7+, recommended)
315
+
316
+ One shared process handles every client. RAM is flat regardless of how many IDE windows, subagents, or concurrent sessions connect. Requires the SLM daemon to be running (`slm start`).
317
+
318
+ ```json
319
+ {
320
+ "mcpServers": {
321
+ "superlocalmemory": {
322
+ "type": "http",
323
+ "url": "http://127.0.0.1:8765/mcp/"
324
+ }
325
+ }
326
+ }
327
+ ```
328
+
329
+ > **Claude Code** also accepts:
330
+ > ```bash
331
+ > claude mcp add --transport http superlocalmemory http://127.0.0.1:8765/mcp/
332
+ > ```
333
+
334
+ #### Option B — stdio transport (universal, works everywhere)
335
+
336
+ Spawns one `slm mcp` subprocess per client connection (~90–110 MB each). Works with every MCP-compatible tool including those that do not yet support HTTP transport. No daemon required.
337
+
312
338
  ```json
313
339
  {
314
340
  "mcpServers": {
@@ -320,7 +346,36 @@ slm status
320
346
  }
321
347
  ```
322
348
 
323
- 33 MCP tools by default (+42 optional behind `SLM_MCP_ALL_TOOLS=1`) + 7 resources. Works with any MCP-compatible client we ship templated configs for Claude Code, Cursor, Windsurf, VS Code Copilot, Continue, Cody, ChatGPT Desktop, Gemini CLI, JetBrains, Zed, and Antigravity (15 IDE configs in `ide/configs/`). **V3.3: Adaptive lifecycle, smart compression, and pattern learning.**
349
+ #### Option C `mcp-remote` bridge (for stdio-only tools that want HTTP)
350
+
351
+ Some CLIs (e.g. Grok CLI) only speak stdio but you still want the RAM benefit of HTTP. The [`@modelcontextprotocol/client-cli`](https://www.npmjs.com/package/@modelcontextprotocol/client-cli) package bridges them:
352
+
353
+ ```bash
354
+ npm install -g @modelcontextprotocol/client-cli
355
+ ```
356
+
357
+ ```json
358
+ {
359
+ "mcpServers": {
360
+ "superlocalmemory": {
361
+ "command": "mcp-remote",
362
+ "args": ["http://127.0.0.1:8765/mcp/", "--allow-http", "--transport", "http-only"]
363
+ }
364
+ }
365
+ }
366
+ ```
367
+
368
+ #### When to use which
369
+
370
+ | Situation | Use |
371
+ |-----------|-----|
372
+ | Claude Code / Claude Desktop (v3.6.7+) | **HTTP** — zero new processes per session |
373
+ | Cursor, Windsurf, Gemini CLI, Antigravity | **HTTP** — native support |
374
+ | Grok CLI, tools that only support stdio | **`mcp-remote` bridge** |
375
+ | Offline / daemon-free usage | **stdio** |
376
+ | Any tool, any version | **stdio** always works as fallback |
377
+
378
+ See [`docs/ide-setup.md`](docs/ide-setup.md) for per-IDE configs. 33 MCP tools by default (+42 optional behind `SLM_MCP_ALL_TOOLS=1`) + 7 resources. Works with any MCP-compatible client — we ship templated configs for Claude Code, Cursor, Windsurf, VS Code Copilot, Continue, Cody, ChatGPT Desktop, Gemini CLI, JetBrains, Zed, and Antigravity (15 IDE configs in `ide/configs/`).
324
379
 
325
380
  ### Dual Interface: MCP + CLI
326
381
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "superlocalmemory",
3
- "version": "3.6.5",
3
+ "version": "3.6.7",
4
4
  "description": "Information-geometric agent memory with mathematical guarantees. 4-channel retrieval, Fisher-Rao similarity, zero-LLM mode, EU AI Act compliant. Works with Claude, Cursor, Windsurf, and 17+ AI tools.",
5
5
  "keywords": [
6
6
  "ai-memory",
package/pyproject.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "superlocalmemory"
3
- version = "3.6.5"
3
+ version = "3.6.7"
4
4
  description = "Information-geometric agent memory with mathematical guarantees"
5
5
  readme = "README.md"
6
6
  license = {text = "AGPL-3.0-or-later"}
@@ -28,7 +28,7 @@ if "OMP_NUM_THREADS" not in os.environ:
28
28
  os.environ["OMP_NUM_THREADS"] = "2"
29
29
  # ---------------------------------------------------------------------------
30
30
 
31
- __version__ = "3.6.5"
31
+ __version__ = "3.6.7"
32
32
 
33
33
  _REQUIRED_VERSIONS = {
34
34
  "sentence_transformers": "5.3.0",
@@ -1001,7 +1001,9 @@ def cmd_recall(args: Namespace) -> None:
1001
1001
  ])
1002
1002
  return
1003
1003
  if not result["results"]:
1004
- print("No matching memories found.")
1004
+ print("No confident match."
1005
+ if result.get("no_confident_match")
1006
+ else "No matching memories found.")
1005
1007
  return
1006
1008
  # Text output
1007
1009
  print(f"SpreadingActivation.search completed via daemon ({result.get('retrieval_time_ms', 0):.0f}ms)")
@@ -1030,20 +1032,38 @@ def cmd_recall(args: Namespace) -> None:
1030
1032
  sys.exit(1)
1031
1033
  raise
1032
1034
 
1035
+ # v3.6.6: route the direct-fallback path through the SAME shared
1036
+ # serializer the daemon uses, so CLI-without-daemon output is identical
1037
+ # to CLI/MCP-with-daemon (budget + source discipline + no_confident_match).
1038
+ from superlocalmemory.server.recall_serializer import serialize_recall_response
1039
+ _rc = getattr(config, "retrieval", None)
1040
+ _ser, _no_match = serialize_recall_response(
1041
+ response,
1042
+ limit=args.limit,
1043
+ per_fact_max=getattr(_rc, "recall_per_fact_max_chars", 2400),
1044
+ total_max=getattr(_rc, "recall_total_max_chars", 12000),
1045
+ full=getattr(args, "full", False),
1046
+ )
1047
+
1033
1048
  if use_json:
1034
1049
  from superlocalmemory.cli.json_output import json_print
1035
1050
  items = []
1036
- for r in response.results:
1051
+ for d in _ser:
1037
1052
  item = {
1038
- "fact_id": r.fact.fact_id, "content": r.fact.content,
1039
- "score": round(r.score, 3),
1053
+ "fact_id": d["fact_id"], "content": d["content"],
1054
+ "score": round(d["score"], 3),
1040
1055
  }
1041
- if hasattr(r, "channel_scores") and r.channel_scores:
1042
- item["channel_scores"] = {k: round(v, 3) for k, v in r.channel_scores.items()}
1056
+ if d.get("channel_scores"):
1057
+ item["channel_scores"] = {k: round(v, 3) for k, v in d["channel_scores"].items()}
1058
+ if d.get("truncated"):
1059
+ item["truncated"] = True
1060
+ if d.get("stub"):
1061
+ item["stub"] = True
1043
1062
  items.append(item)
1044
1063
  json_print("recall", data={
1045
1064
  "results": items, "count": len(items),
1046
1065
  "query_type": getattr(response, "query_type", "unknown"),
1066
+ "no_confident_match": _no_match,
1047
1067
  }, next_actions=[
1048
1068
  {"command": "slm list --json", "description": "List recent memories"},
1049
1069
  ])
@@ -1055,11 +1075,11 @@ def cmd_recall(args: Namespace) -> None:
1055
1075
  except Exception:
1056
1076
  pass
1057
1077
 
1058
- if not response.results:
1059
- print("No memories found.")
1078
+ if not _ser:
1079
+ print("No confident match." if _no_match else "No memories found.")
1060
1080
  return
1061
- for i, r in enumerate(response.results, 1):
1062
- print(f" {i}. [{r.score:.2f}] {r.fact.content[:120]}")
1081
+ for i, d in enumerate(_ser, 1):
1082
+ print(f" {i}. [{d['score']:.2f}] {d['content']}")
1063
1083
 
1064
1084
 
1065
1085
  def _cli_record_signals(config, query, results):
@@ -0,0 +1,147 @@
1
+ # Copyright (c) 2026 Varun Pratap Bhardwaj / Qualixar
2
+ # Licensed under AGPL-3.0-or-later - see LICENSE file
3
+ # Part of SuperLocalMemory V3 — Core Block Hygiene (v3.6.6)
4
+
5
+ """Core Memory Block hygiene helpers (v3.6.6 F-5).
6
+
7
+ Three pure functions used by the block compiler:
8
+ - dedupe_block_content: normalized-line dedup within a block
9
+ - filter_low_quality_block_facts: drop is_low_quality facts
10
+ - compile_block_content: full compile pipeline (filter + dedup + cap)
11
+
12
+ Also exports: _recompile_core_blocks — the hook called by MaintenanceScheduler.
13
+
14
+ These are pure functions (no I/O). All I/O lives in the scheduler / consolidation
15
+ engine that calls them.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import logging
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ _BLOCK_SEPARATOR = "\n---\n"
25
+ _PLACEHOLDER = "No data available."
26
+
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # dedupe_block_content
30
+ # ---------------------------------------------------------------------------
31
+
32
+ def dedupe_block_content(lines: list[str]) -> list[str]:
33
+ """Remove duplicate and empty lines from a block content line-list.
34
+
35
+ Normalization: lowercased, whitespace-collapsed.
36
+ Order is preserved; only the FIRST occurrence is kept.
37
+
38
+ Returns a new list — never mutates input.
39
+ """
40
+ seen: set[str] = set()
41
+ result: list[str] = []
42
+ for line in lines:
43
+ stripped = line.strip()
44
+ if not stripped:
45
+ continue
46
+ key = " ".join(stripped.lower().split())
47
+ if key in seen:
48
+ continue
49
+ seen.add(key)
50
+ result.append(line)
51
+ return result
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # filter_low_quality_block_facts
56
+ # ---------------------------------------------------------------------------
57
+
58
+ def filter_low_quality_block_facts(facts: list[dict]) -> list[dict]:
59
+ """Filter fact dicts whose content is low-quality or prompt-template.
60
+
61
+ Delegates to injection.is_low_quality and injection.is_prompt_template.
62
+ Returns a new list — never mutates input.
63
+ """
64
+ try:
65
+ from superlocalmemory.core.injection import is_low_quality, is_prompt_template
66
+ except Exception:
67
+ return list(facts)
68
+
69
+ result: list[dict] = []
70
+ for f in facts:
71
+ content = f.get("content", "") or ""
72
+ if is_low_quality(content):
73
+ continue
74
+ if is_prompt_template(content):
75
+ continue
76
+ result.append(f)
77
+ return result
78
+
79
+
80
+ # ---------------------------------------------------------------------------
81
+ # compile_block_content
82
+ # ---------------------------------------------------------------------------
83
+
84
+ def compile_block_content(
85
+ facts: list[dict],
86
+ max_chars: int = 2000,
87
+ ) -> str:
88
+ """Compile facts into block content with hygiene and char cap.
89
+
90
+ Pipeline:
91
+ 1. filter_low_quality_block_facts
92
+ 2. Extract content lines from each fact (split by newline / separator)
93
+ 3. dedupe_block_content across all lines
94
+ 4. Join with separator, truncate to max_chars
95
+
96
+ Returns a string ≤ max_chars. Returns empty string if all facts filtered.
97
+ """
98
+ clean_facts = filter_low_quality_block_facts(facts)
99
+ if not clean_facts:
100
+ return ""
101
+
102
+ all_lines: list[str] = []
103
+ for f in clean_facts:
104
+ content = (f.get("content") or "").strip()
105
+ if not content:
106
+ continue
107
+ # Split by separator or newline to treat each line independently
108
+ for line in content.replace(_BLOCK_SEPARATOR, "\n").split("\n"):
109
+ all_lines.append(line)
110
+
111
+ deduped = dedupe_block_content(all_lines)
112
+ if not deduped:
113
+ return ""
114
+
115
+ joined = _BLOCK_SEPARATOR.join(deduped)
116
+ return joined[:max_chars]
117
+
118
+
119
+ # ---------------------------------------------------------------------------
120
+ # _recompile_core_blocks — scheduler hook (F-5 daily recompile)
121
+ # ---------------------------------------------------------------------------
122
+
123
+ def _recompile_core_blocks(
124
+ db,
125
+ config,
126
+ profile_id: str,
127
+ ) -> dict:
128
+ """Recompile core memory blocks with hygiene applied.
129
+
130
+ Called by MaintenanceScheduler._run() on the daily cycle.
131
+ Delegates to ConsolidationEngine.compile_core_blocks_mode_a() with
132
+ the hygiene improvements applied at the _facts_to_content step.
133
+
134
+ Returns a dict with stats: {blocks_compiled, profile_id}.
135
+ """
136
+ try:
137
+ from superlocalmemory.core.consolidation_engine import ConsolidationEngine
138
+ engine = ConsolidationEngine(db=db, config=config.consolidation)
139
+ result = engine.compile_core_blocks_mode_a(profile_id)
140
+ logger.info(
141
+ "Daily core-block recompile: profile=%s blocks=%s",
142
+ profile_id, result.get("blocks_compiled", 0),
143
+ )
144
+ return {**result, "profile_id": profile_id}
145
+ except Exception as exc:
146
+ logger.warning("Core-block recompile failed: %s", exc)
147
+ return {"blocks_compiled": 0, "profile_id": profile_id, "error": str(exc)}
@@ -197,6 +197,17 @@ class RetrievalConfig:
197
197
  # Used by s19_runner for ablation experiments. Empty = all channels active.
198
198
  disabled_channels: list[str] = field(default_factory=list)
199
199
 
200
+ # v3.6.6: Evidence floor — gate on per-channel scores, not fused/RRF score.
201
+ # Nonsense queries earn 0.0 on every primary channel; real matches earn
202
+ # semantic >= 0.85 or bm25 > 0. The discriminator is earned channel evidence.
203
+ # Env kill-switch: SLM_RECALL_NO_FLOOR=1 disables without release.
204
+ evidence_floor_enabled: bool = True
205
+ min_semantic_evidence: float = 0.60 # Minimum cosine similarity to keep a result
206
+
207
+ # v3.6.6: Recall output budget — protect consuming agents from 585KB responses.
208
+ recall_per_fact_max_chars: int = 2400 # ~600 tokens; head 70% + tail 30%
209
+ recall_total_max_chars: int = 12000 # ~3K tokens; stubs beyond this
210
+
200
211
 
201
212
  # ---------------------------------------------------------------------------
202
213
  # Math Config
@@ -233,6 +244,30 @@ class MathConfig:
233
244
  # Rate-Distortion (production only, disabled for benchmarks)
234
245
 
235
246
 
247
+ # ---------------------------------------------------------------------------
248
+ # Store Config (v3.6.6)
249
+ # ---------------------------------------------------------------------------
250
+
251
+ @dataclass(frozen=True)
252
+ class StoreConfig:
253
+ """Configuration for the remember/store write path (v3.6.6).
254
+
255
+ Ingest gate: protect the DB from oversized facts and prompt-template
256
+ pollution. Defaults ON; env kill-switch SLM_INGEST_NO_GATE=1.
257
+ """
258
+
259
+ # Max chars for the FACT content stored in atomic_facts.content.
260
+ # Content above this is clamped to head 70% + tail 30% + truncation marker.
261
+ # The FULL original is preserved in the memories table row. Set high (24K
262
+ # ≈ 6K tokens) so only pathological pastes are touched; normal dense
263
+ # session-handoff memories (6-15K chars) are stored 100% intact.
264
+ max_verbatim_chars: int = 24000
265
+
266
+ # Hard upper bound in bytes. Content above this is rejected outright.
267
+ # Nobody's "memory" is a megabyte (MCP: success=False, HTTP: 413).
268
+ max_ingest_bytes: int = 1_048_576 # 1 MB
269
+
270
+
236
271
  # ---------------------------------------------------------------------------
237
272
  # Context Injection (v3.4.65)
238
273
  # ---------------------------------------------------------------------------
@@ -658,6 +693,7 @@ class SLMConfig:
658
693
  default_factory=ParameterizationConfig,
659
694
  )
660
695
  injection: InjectionConfig = field(default_factory=InjectionConfig)
696
+ store: StoreConfig = field(default_factory=StoreConfig)
661
697
  # v3.5.0: scaling backends — "sqlite" / "cozo" / "auto" / "lancedb" / "sqlite-vec" / "auto".
662
698
  graph_backend: str = "auto" # "auto" = cozo if pycozo installed, else sqlite
663
699
  vector_backend: str = "auto" # "auto" = lancedb if installed, else sqlite-vec
@@ -808,22 +808,25 @@ class ConsolidationEngine:
808
808
  def _facts_to_content(
809
809
  self, facts: list[dict], char_limit: int,
810
810
  ) -> str:
811
- """Join fact contents with separators, capped at char_limit."""
812
- parts = [f.get("content", "") for f in facts if f.get("content")]
813
- joined = "\n---\n".join(parts)
814
- return joined[:char_limit] if joined else "No data available."
811
+ """Compile fact contents into a block with hygiene (v3.6.6 F-5).
812
+
813
+ Filters low-quality/template facts, dedupes lines WITHIN the block
814
+ (fixes the "same fixture ×5" core-block bug), caps at char_limit.
815
+ """
816
+ from superlocalmemory.core.block_hygiene import compile_block_content
817
+ compiled = compile_block_content(facts, max_chars=char_limit)
818
+ return compiled if compiled else "No data available."
815
819
 
816
820
  def _rows_to_content(
817
821
  self, rows: list | None, char_limit: int,
818
822
  ) -> str:
819
- """Convert DB rows to content string."""
823
+ """Convert DB rows to a hygienic block content string (v3.6.6 F-5)."""
820
824
  if not rows:
821
825
  return "No data available."
822
- parts = [
823
- dict(r).get("content", "") for r in rows if dict(r).get("content")
824
- ]
825
- joined = "\n---\n".join(parts)
826
- return joined[:char_limit] if joined else "No data available."
826
+ from superlocalmemory.core.block_hygiene import compile_block_content
827
+ facts = [dict(r) for r in rows]
828
+ compiled = compile_block_content(facts, max_chars=char_limit)
829
+ return compiled if compiled else "No data available."
827
830
 
828
831
  def _compile_behavioral_block(
829
832
  self, profile_id: str, char_limit: int,
@@ -430,6 +430,25 @@ class MemoryEngine:
430
430
  return []
431
431
  except Exception:
432
432
  pass
433
+ # v3.6.6 ingest gate: reject 1MB monsters + prompt-template pollution;
434
+ # clamp the searchable FACT copy (head+tail) while the memories row keeps
435
+ # the FULL original. Embedding/BM25 use the clamped copy so a 167KB paste
436
+ # never produces a garbage vector. Env kill-switch: SLM_INGEST_NO_GATE=1.
437
+ fact_text = content
438
+ try:
439
+ from superlocalmemory.core.ingest_gate import apply_ingest_gate
440
+ _sc = getattr(self._config, "store", None)
441
+ gate = apply_ingest_gate(
442
+ content,
443
+ max_verbatim_chars=getattr(_sc, "max_verbatim_chars", 24000),
444
+ max_ingest_bytes=getattr(_sc, "max_ingest_bytes", 1_048_576),
445
+ )
446
+ if gate.rejected:
447
+ logger.debug("store_fast ingest gate rejected: %s", gate.rejection_reason)
448
+ return []
449
+ fact_text = gate.fact_content
450
+ except ImportError:
451
+ pass # gate module missing → store verbatim (never block a write)
433
452
  now = datetime.now(timezone.utc).isoformat()
434
453
  record = MemoryRecord(
435
454
  profile_id=self._profile_id, content=content,
@@ -440,8 +459,8 @@ class MemoryEngine:
440
459
  # the entity_graph channel has something to work with before enrichment.
441
460
  ents = sorted(
442
461
  {m.group(1) for m in _re.finditer(
443
- r"\b([A-Z][a-z]+(?:\s[A-Z][a-z]+){0,3})\b", content)}
444
- | {m.group(1) for m in _re.finditer(r"\b([A-Z]{2,})\b", content)}
462
+ r"\b([A-Z][a-z]+(?:\s[A-Z][a-z]+){0,3})\b", fact_text)}
463
+ | {m.group(1) for m in _re.finditer(r"\b([A-Z]{2,})\b", fact_text)}
445
464
  )
446
465
  # v3.5.5: compute the embedding SYNCHRONOUSLY. A single warm embed is
447
466
  # ~22ms (the 30-180s of full store() was LLM fact-extraction + graph,
@@ -452,14 +471,14 @@ class MemoryEngine:
452
471
  emb = None
453
472
  fmean = fvar = None
454
473
  try:
455
- emb = self._embedder.embed(content) if self._embedder else None
474
+ emb = self._embedder.embed(fact_text) if self._embedder else None
456
475
  if emb:
457
476
  fmean, fvar = self._embedder.compute_fisher_params(emb)
458
477
  except Exception:
459
478
  emb = None
460
479
  fact = AtomicFact(
461
480
  fact_id=_uuid.uuid4().hex[:16], memory_id=record.memory_id,
462
- profile_id=self._profile_id, content=content,
481
+ profile_id=self._profile_id, content=fact_text,
463
482
  fact_type=FactType.EPISODIC, entities=ents,
464
483
  observation_date=now[:10], confidence=0.7, importance=0.5,
465
484
  embedding=emb, fisher_mean=fmean, fisher_variance=fvar,
@@ -477,7 +496,7 @@ class MemoryEngine:
477
496
  try:
478
497
  bm25 = getattr(self._retrieval_engine, "_bm25", None)
479
498
  if bm25:
480
- bm25.add(fact.fact_id, content, self._profile_id)
499
+ bm25.add(fact.fact_id, fact_text, self._profile_id)
481
500
  except Exception:
482
501
  pass
483
502
  return [fact.fact_id]