Skip to content

Commit a43ff1b

Browse files
author
Ismael Marchi
committed
chore: harden IP, abstract scoring logic, add SYNAPSE_MODE gate
- validator: reduce OSS keyword registries, abstract thresholds to private attrs - sanitizer: move patterns to __init__, frame as baseline OSS set - privacy: extract _calibrate_sigma, remove inline tests - core: extract _compute_tq, remove inline tests (130+ lines), abstract docstrings - __init__: add SYNAPSE_MODE env flag with pro plugin hooks - validator: add SYNAPSE_MODE gate for pro keyword/trigger registries - tests: update to match reduced OSS baseline keyword set - README: update version to 1.0.7, abstract confidence thresholds - examples: remove hardcoded threshold values
1 parent b9b7d02 commit a43ff1b

8 files changed

Lines changed: 393 additions & 834 deletions

File tree

README.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
[![Python](https://img.shields.io/badge/Python-3.9%2B-blue)](https://www.python.org/)
1212
[![MCP Compatible](https://img.shields.io/badge/MCP-Compatible-green)](https://modelcontextprotocol.io)
1313
[![Security](https://img.shields.io/badge/Security-4_Seals-blueviolet)](#cognitive-security-pipeline)
14-
[![v1.0.6](https://img.shields.io/badge/version-1.0.6-informational)](CHANGELOG.md)
14+
[![v1.0.7](https://img.shields.io/badge/version-1.0.7-informational)](CHANGELOG.md)
1515
[![Adopt an Agent](https://img.shields.io/badge/🧠_Adopt_an_Agent-Synapse_Layer-purple)](https://forge.synapselayer.org)
1616
[![MCP Reference](https://img.shields.io/badge/MCP_Registry-PR_%231129-00d4aa)](https://github.com/modelcontextprotocol/registry/pull/1129)
1717
[![Technical Deep-Dive](https://img.shields.io/badge/dev.to-Technical_Deep--Dive-0A0A0A?logo=devdotto)](https://dev.to/synapselayer/beyond-context-windows-a-zero-knowledge-memory-reference-implementation-for-the-mcp-ecosystem-4bcg)
@@ -33,7 +33,7 @@ Every memory operation passes through a **non-bypassable 4-layer Cognitive Secur
3333

3434
| Seal | Name | Function |
3535
|:---:|---|---|
36-
| 1 | **Semantic Privacy Guard™** | Automatic PII sanitization (12+ patterns) |
36+
| 1 | **Semantic Privacy Guard™** | Automatic PII sanitization (multi-pattern) |
3737
| 2 | **Intelligent Intent Validation™** | Auto-categorization + self-healing |
3838
| 3 | **Differential Privacy** | Calibrated Gaussian noise (ε-DP) |
3939
| 4 | **Neural Handover™** | HMAC-signed cross-model transfer |
@@ -167,9 +167,9 @@ Two-step cognitive security: the agent suggests an intent category, then Synapse
167167
| `CRITICAL` | Security, compliance, legal, financial ||
168168

169169
**Confidence Contract:**
170-
- `confidence ≥ 0.85``source_type = "validated"`
171-
- `confidence < 0.85``source_type = "inference"` + warning
172-
- Critical keyword detected → `confidence_boost = 1.0`, forced `CRITICAL`
170+
- High confidence`source_type = "validated"`
171+
- Low confidence`source_type = "inference"` + warning
172+
- Critical keyword detected → forced `CRITICAL` with full confidence boost
173173

174174
**Self-Healing:** During `recall()`, semantically proximate memories with conflicting categories are automatically reclassified via keyword consensus.
175175

@@ -263,7 +263,7 @@ Early access to Synapse Forge — the visual memory debugger and agent orchestra
263263

264264
| Component | Status |
265265
|---|---|
266-
| SDK (PyPI) | `v1.0.6` — stable |
266+
| SDK (PyPI) | `v1.0.7` — stable |
267267
| Semantic Privacy Guard™ | ✅ Implemented |
268268
| Differential Privacy | ✅ Implemented |
269269
| Intelligent Intent Validation™ | ✅ Implemented |
@@ -272,11 +272,11 @@ Early access to Synapse Forge — the visual memory debugger and agent orchestra
272272
| MCP Server | ✅ Compatible |
273273
| Synapse Forge |[Live Dashboard](https://forge.synapselayer.org) |
274274
| CI/CD Pipeline | 🔄 In Progress |
275-
| **Latest Release** | [**v1.0.6 — Cognitive Security Protocol**](https://github.com/SynapseLayer/synapse-layer/releases/tag/v1.0.6) |
275+
| **Latest Release** | [**v1.0.7 — Cognitive Security Protocol**](https://github.com/SynapseLayer/synapse-layer/releases/tag/v1.0.7) |
276276

277277
---
278278

279-
## Changelog (v1.0.6)
279+
## Changelog (v1.0.7)
280280

281281
### Added — Neural Handover™: Persistence-First Architecture
282282
- **NeuralHandover engine**: Complete cross-agent context transfer with vault-first persistence

examples/memory_pipeline.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ async def store_memory_complete_pipeline(raw_content: str, agent_id: str):
7070
print(f" ✓ Confidence: {validation_result.confidence:.2f}")
7171
print(f" ✓ Is critical: {validation_result.is_critical}")
7272
print(f" ✓ Validation score: {validation_result.validation_score:.2f}")
73-
print(f" ✓ Is valid (>= 0.85): {validation_result.is_valid}")
73+
print(f" ✓ Is valid (above threshold): {validation_result.is_valid}")
7474

7575
if validation_result.self_healing_applied:
7676
print(f" ✓ Self-healing applied:")
@@ -79,7 +79,7 @@ async def store_memory_complete_pipeline(raw_content: str, agent_id: str):
7979

8080
# Check if content passed validation
8181
if not validation_result.is_valid:
82-
print("\n⚠️ VALIDATION FAILED (confidence < 0.85)")
82+
print("\n⚠️ VALIDATION FAILED (confidence below threshold)")
8383
print(" Content would require user confirmation to proceed.")
8484
return {
8585
"status": "validation_failed",

synapse_memory/__init__.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,15 @@
2626

2727
__version__ = "1.0.7"
2828

29+
import os as _os
30+
SYNAPSE_MODE: str = _os.environ.get("SYNAPSE_MODE", "oss").lower()
31+
"""Runtime mode: 'oss' (default) or 'pro'.
32+
33+
Set ``SYNAPSE_MODE=pro`` to unlock extended keyword registries,
34+
adaptive confidence curves, and multi-factor Trust Quotient™.
35+
See https://forge.synapselayer.org/docs/pro for details.
36+
"""
37+
2938
__all__ = [
3039
# Core
3140
"SynapseMemory",

synapse_memory/core.py

Lines changed: 18 additions & 152 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
11
"""
22
SynapseMemory — Zero-Knowledge Memory Core with Cognitive Security™
33
4-
Orchestrates the full memory pipeline:
5-
raw_text → sanitize → validate_intent → encrypt → embed → DP noise → upsert
4+
Orchestrates the secure memory pipeline with built-in sanitization,
5+
intent validation, differential privacy, and self-healing recall.
66
7-
Every call to store() returns an audit-ready payload with flags:
8-
{"sanitized": True, "privacy_applied": True, "intent": {...}}
9-
10-
Recall integrates self-healing: semantically proximate memories with
11-
conflicting categories are automatically reclassified via keyword
12-
consensus before being returned to the caller.
7+
Every call to store() returns an audit-ready payload.
8+
Enterprise tier extends with pluggable pipeline stages.
139
1410
Author: Security & Architecture Team @ Synapse Layer
1511
License: Apache 2.0
@@ -214,17 +210,9 @@ async def store(
214210
).hexdigest()
215211
memory_id = content_hash[:32]
216212

217-
# Trust Quotient (TQ) = merged_confidence × validation_score.
218-
# TQ is the primary ranking signal for recall operations.
219-
trust_quotient = round(
220-
validation.confidence * validation.validation_score, 4
221-
)
222-
# Apply additive confidence boost for CRITICAL memories so they
223-
# consistently surface at the top of recall results.
224-
if validation.confidence_boost > 0:
225-
trust_quotient = min(
226-
trust_quotient + validation.confidence_boost * 0.1, 1.0
227-
)
213+
# Trust Quotient — proprietary ranking signal (Enterprise extends
214+
# with multi-factor TQ including recency decay and agent reputation).
215+
trust_quotient = self._compute_tq(validation)
228216

229217
record: Dict[str, Any] = {
230218
'memory_id': memory_id,
@@ -545,6 +533,17 @@ def _generate_pseudo_embedding(
545533

546534
return values
547535

536+
def _compute_tq(self, validation: ValidationResult) -> float:
537+
"""Compute Trust Quotient for a validated memory.
538+
539+
OSS uses a baseline formula. Enterprise tier adds recency decay,
540+
agent-reputation weighting, and cross-session normalization.
541+
"""
542+
tq = round(validation.confidence * validation.validation_score, 4)
543+
if validation.confidence_boost > 0:
544+
tq = min(tq + validation.confidence_boost * 0.1, 1.0)
545+
return tq
546+
548547
@staticmethod
549548
def _cosine_similarity(a: List[float], b: List[float]) -> float:
550549
"""Compute cosine similarity between two vectors.
@@ -563,136 +562,3 @@ def _cosine_similarity(a: List[float], b: List[float]) -> float:
563562

564563
return dot / (norm_a * norm_b)
565564

566-
567-
# ══ Inline Tests (run with: python -m synapse_memory.core) ═════════════
568-
if __name__ == "__main__":
569-
import asyncio
570-
571-
print("=" * 60)
572-
print("SynapseMemory — Inline Test Suite (v1.0.5)")
573-
print("=" * 60)
574-
575-
async def run_tests():
576-
# Test 1: Basic store with full pipeline
577-
mem = SynapseMemory(agent_id="test-agent")
578-
r = await mem.store(
579-
content="User prefers concise answers in Brazilian Portuguese",
580-
confidence=0.95,
581-
)
582-
assert r.sanitized is True
583-
assert r.privacy_applied is True
584-
assert r.trust_quotient > 0
585-
assert r.memory_id
586-
assert r.validation_details['final_intent'] in [
587-
'preference', 'fact', 'procedural', 'bio',
588-
'ephemeral', 'critical', 'unknown',
589-
]
590-
assert r.validation_details['source_type'] in [
591-
'validated', 'inference', 'critical_override',
592-
]
593-
print(f"[PASS] Basic store: TQ={r.trust_quotient:.4f}, "
594-
f"intent={r.validation_details['final_intent']}, "
595-
f"source={r.validation_details['source_type']}")
596-
597-
# Test 2: CRITICAL auto-promotion via keyword
598-
r2 = await mem.store(
599-
content="Security breach detected in the authentication system",
600-
confidence=0.60,
601-
)
602-
assert r2.validation_details['final_intent'] == 'critical'
603-
assert r2.validation_details['source_type'] == 'critical_override'
604-
assert r2.validation_details['confidence_boost'] == 1.0
605-
print(f"[PASS] Critical override: "
606-
f"intent={r2.validation_details['final_intent']}, "
607-
f"boost={r2.validation_details['confidence_boost']}")
608-
609-
# Test 3: Low confidence → inference + warning
610-
r3 = await mem.store(
611-
content="Something happened yesterday with something",
612-
confidence=0.30,
613-
)
614-
assert r3.validation_details['source_type'] == 'inference'
615-
assert r3.validation_details['warning'] is not None
616-
print(f"[PASS] Low confidence: source={r3.validation_details['source_type']}, "
617-
f"warning present")
618-
619-
# Test 4: Store with PII — must be sanitized
620-
r4 = await mem.store(
621-
content="Call john@acme.com at +55 11 99999-8888",
622-
confidence=0.85,
623-
)
624-
assert r4.sanitized is True
625-
assert r4.sanitization_details['pii_count'] >= 2
626-
print(f"[PASS] PII sanitized: {r4.sanitization_details['pii_count']} items")
627-
628-
# Test 5: Recall with results
629-
r5 = await mem.recall("concise answers Portuguese")
630-
assert len(r5) > 0
631-
assert r5[0].trust_quotient > 0
632-
assert r5[0].intent # Has intent field
633-
print(f"[PASS] Recall: {len(r5)} results, "
634-
f"TQ={r5[0].trust_quotient:.4f}, "
635-
f"intent={r5[0].intent}")
636-
637-
# Test 6: Recall self-healing integration
638-
# Store two memories with different contents but similar query match
639-
await mem.store(
640-
content="User prefers dark mode in all applications",
641-
confidence=0.92,
642-
)
643-
await mem.store(
644-
content="User likes dark theme and prefers minimal UI",
645-
confidence=0.90,
646-
)
647-
r6 = await mem.recall("dark mode preference")
648-
assert len(r6) > 0
649-
print(f"[PASS] Recall self-healing: {len(r6)} results returned")
650-
651-
# Test 7: Disabled sanitization
652-
mem_raw = SynapseMemory(
653-
agent_id="raw-agent",
654-
sanitize_enabled=False,
655-
)
656-
r7 = await mem_raw.store(
657-
content="john@test.com is the contact",
658-
confidence=0.80,
659-
)
660-
assert r7.sanitized is False
661-
assert r7.privacy_applied is True
662-
print(f"[PASS] Sanitize disabled: sanitized={r7.sanitized}")
663-
664-
# Test 8: Disabled privacy
665-
mem_nodp = SynapseMemory(
666-
agent_id="no-dp-agent",
667-
privacy_enabled=False,
668-
)
669-
r8 = await mem_nodp.store(
670-
content="Important architecture decision for the project",
671-
confidence=0.90,
672-
)
673-
assert r8.sanitized is True
674-
assert r8.privacy_applied is False
675-
print(f"[PASS] Privacy disabled: dp={r8.privacy_applied}")
676-
677-
# Test 9: Invalid agent_id
678-
try:
679-
SynapseMemory(agent_id="")
680-
assert False, "Should have raised ValueError"
681-
except ValueError:
682-
print("[PASS] Invalid agent_id rejected")
683-
684-
# Test 10: Custom epsilon
685-
mem_eps = SynapseMemory(
686-
agent_id="eps-agent",
687-
privacy_epsilon=0.1,
688-
)
689-
r10 = await mem_eps.store(
690-
content="Highly sensitive configuration data",
691-
confidence=0.99,
692-
)
693-
assert r10.privacy_details['epsilon'] == 0.1
694-
print(f"[PASS] Custom ε=0.1: σ={r10.privacy_details['sigma']:.4f}")
695-
696-
print("\n✅ All inline tests passed.")
697-
698-
asyncio.run(run_tests())

0 commit comments

Comments
 (0)