prism-mcp-server 8.0.3 → 9.0.4
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/README.md +80 -9
- package/dist/cli.js +0 -0
- package/dist/config.js +42 -5
- package/dist/dashboard/server.js +118 -0
- package/dist/dashboard/ui.js +211 -1
- package/dist/memory/cognitiveBudget.js +224 -0
- package/dist/memory/surprisalGate.js +119 -0
- package/dist/memory/synapseEngine.js +15 -0
- package/dist/memory/valenceEngine.js +234 -0
- package/dist/scholar/webScholar.js +7 -6
- package/dist/server.js +60 -19
- package/dist/storage/index.js +53 -9
- package/dist/storage/sqlite.js +101 -9
- package/dist/storage/supabase.js +74 -5
- package/dist/storage/supabaseMigrations.js +30 -0
- package/dist/sync/factory.js +5 -1
- package/dist/tools/graphHandlers.js +24 -2
- package/dist/tools/ledgerHandlers.js +122 -4
- package/dist/utils/universalImporter.js +0 -0
- package/package.json +13 -3
- package/dist/dashboard/ui.tmp.js +0 -3475
- package/dist/test-cli.js +0 -18
- package/dist/tools/sessionMemoryHandlers.js +0 -2633
- package/dist/utils/embeddingApi.js +0 -104
- package/dist/utils/googleAi.js +0 -88
- package/dist/utils/testUniversalImporter.js +0 -10
- package/dist/verification/renameDetector.js +0 -170
package/README.md
CHANGED
|
@@ -8,11 +8,11 @@
|
|
|
8
8
|
[](https://www.typescriptlang.org/)
|
|
9
9
|
[](CONTRIBUTING.md)
|
|
10
10
|
|
|
11
|
-

|
|
11
|
+

|
|
12
12
|
|
|
13
13
|
**Your AI agent forgets everything between sessions. Prism fixes that — then teaches it to think.**
|
|
14
14
|
|
|
15
|
-
Prism
|
|
15
|
+
Prism v9.0 is the **Autonomous Cognitive OS** for AI agents. Built on a true cognitive architecture inspired by human brain mechanics, Prism gives agents affect-tagged memory, token-economic cost awareness, and multi-hop graph reasoning — your agent now follows causal trains of thought across memory, forms principles from experience, economizes what it stores, and knows when it lacks information. **Your agents don't just remember; they think.**
|
|
16
16
|
|
|
17
17
|
```bash
|
|
18
18
|
npx -y prism-mcp-server
|
|
@@ -28,6 +28,7 @@ Works with **Claude Desktop · Claude Code · Cursor · Windsurf · Cline · Gem
|
|
|
28
28
|
- [Setup Guides](#setup-guides)
|
|
29
29
|
- [Universal Import: Bring Your History](#universal-import-bring-your-history)
|
|
30
30
|
- [What Makes Prism Different](#what-makes-prism-different)
|
|
31
|
+
- [Autonomous Cognitive OS (v9.0)](#-autonomous-cognitive-os-v90)
|
|
31
32
|
- [Synapse Engine (v8.0)](#synapse-engine-v80)
|
|
32
33
|
- [Cognitive Architecture (v7.8)](#cognitive-architecture-v78)
|
|
33
34
|
- [Data Privacy & Egress](#data-privacy--egress)
|
|
@@ -39,6 +40,7 @@ Works with **Claude Desktop · Claude Code · Cursor · Windsurf · Cline · Gem
|
|
|
39
40
|
- [Architecture](#architecture)
|
|
40
41
|
- [Scientific Foundation](#scientific-foundation)
|
|
41
42
|
- [Milestones & Roadmap](#milestones--roadmap)
|
|
43
|
+
- [Enterprise & Commercial Support](#enterprise--commercial-support)
|
|
42
44
|
- [Troubleshooting FAQ](#troubleshooting-faq)
|
|
43
45
|
|
|
44
46
|
---
|
|
@@ -415,6 +417,12 @@ npx -y prism-mcp-server universal-import --format gemini --path ./gemini_history
|
|
|
415
417
|
## What Makes Prism Different
|
|
416
418
|
|
|
417
419
|
|
|
420
|
+
### 💰 Token-Economic Memory & Surprisal Gates (v9.0)
|
|
421
|
+
Standard agents dump repetitive garbage into vector databases until they bankrupt your API budget and choke their own context windows. Prism introduces a **Persistent Cognitive Budget** with Universal Basic Income (UBI). Before saving, Prism calculates the semantic novelty (Surprisal) of the thought. Redundant boilerplate is penalized with a 2× cost multiplier; novel insights are rewarded. The agent is mathematically forced to learn compression.
|
|
422
|
+
|
|
423
|
+
### 🎭 Affect-Tagged Emotional Routing (v9.0)
|
|
424
|
+
Standard RAG retrieves documents based on similarity, not success rate. Prism tags experience events with **Valence** (-1.0 to +1.0). Highly emotional memories (catastrophic failures or massive successes) receive an affective salience boost during retrieval. If an agent heads down an architectural path that previously caused outages, Prism injects a preemptive `⚠️ Historical Friction` warning, giving your AI a "gut feeling" about bad code.
|
|
425
|
+
|
|
418
426
|
### 🧠 Your Agent Learns From Mistakes
|
|
419
427
|
When you correct your agent, Prism tracks it. Corrections accumulate **importance** over time. High-importance lessons auto-surface as warnings in future sessions — and can even sync to your `.cursorrules` file for permanent enforcement. Your agent literally gets smarter the more you use it.
|
|
420
428
|
|
|
@@ -460,6 +468,41 @@ When you trigger a Dark Factory pipeline, Prism doesn't just run your task — i
|
|
|
460
468
|
|
|
461
469
|
---
|
|
462
470
|
|
|
471
|
+
## 🤖 Autonomous Cognitive OS (v9.0)
|
|
472
|
+
|
|
473
|
+
> *Memory isn't just about storing data; it's about economics and emotion. v9.0 transforms Prism from a passive memory database into a living Cognitive Operating System that forces agents to learn compression and develop intuition.*
|
|
474
|
+
|
|
475
|
+
Most AI agents have an infinite memory budget. They dump massive, repetitive logs into vector databases until the context window chokes. Prism v9.0 fixes this by introducing **Token-Economic Reinforcement Learning** and **Affect-Tagged Memory**.
|
|
476
|
+
|
|
477
|
+
### 1. Memory-as-an-Economy (The Surprisal Gate)
|
|
478
|
+
Prism gives your project a strict **Cognitive Budget** (e.g., 2,000 tokens). Every time the agent saves a memory, it costs tokens.
|
|
479
|
+
|
|
480
|
+
But not all memories are priced equally:
|
|
481
|
+
* Prism intercepts the save and runs a **Vector-Based Surprisal** calculation against recent memories.
|
|
482
|
+
* **High Surprisal (Novel thought):** Costs 0.5× tokens. The agent is rewarded for new insights.
|
|
483
|
+
* **Low Surprisal (Boilerplate):** Costs 2.0× tokens. The agent is penalized for repeating itself.
|
|
484
|
+
* **Universal Basic Income (UBI):** The budget recovers passively over time (+100 tokens/hour) or when the agent successfully completes autonomous evaluations.
|
|
485
|
+
|
|
486
|
+
**The Result:** You don't need to prompt the agent to "be concise." The physics of the system force the LLM to learn data compression to avoid bankruptcy.
|
|
487
|
+
|
|
488
|
+
### 2. Affect-Tagged Memory (Giving AI a "Gut Feeling")
|
|
489
|
+
Vector math measures *semantic similarity*, not *sentiment*. If an agent searches for "Authentication Architecture," standard RAG will return two past approaches—it doesn't know that Approach A caused a 3-day production outage, while Approach B worked perfectly.
|
|
490
|
+
|
|
491
|
+
* **Affective Salience:** Prism automatically tags experience events with a `valence` score (-1.0 for failure, +1.0 for success).
|
|
492
|
+
* **Emotional Retrieval:** At retrieval time, the absolute magnitude (`|valence|`) significantly boosts the memory's ranking score. Extreme failures and extreme successes surface to the top.
|
|
493
|
+
* **UX Warnings:** If the retrieved memories are historically negative, Prism intercepts the prompt injection: `⚠️ Caution: This topic is strongly correlated with historical failures. Review past decisions before proceeding.`
|
|
494
|
+
|
|
495
|
+
### The Paradigm Shift
|
|
496
|
+
|
|
497
|
+
| Feature | Standard RAG / Agents | Prism v9.0 |
|
|
498
|
+
| :--- | :--- | :--- |
|
|
499
|
+
| **Storage Limit** | Infinite (bloats context) | Bounded Token Economy |
|
|
500
|
+
| **Data Quality** | Saves repetitive boilerplate | Surprisal Gate penalizes redundancy |
|
|
501
|
+
| **Sentiment** | Treats all data as neutral facts | Affect-Tagged (Warns agent of past trauma) |
|
|
502
|
+
| **Recovery** | Manual deletion | Universal Basic Income (UBI) over time |
|
|
503
|
+
|
|
504
|
+
---
|
|
505
|
+
|
|
463
506
|
## Synapse Engine (v8.0)
|
|
464
507
|
|
|
465
508
|
> *Standard RAG retrieves documents. GraphRAG traverses relationships. The Synapse Engine does both — a pure, storage-agnostic multi-hop propagation engine that turns your agent's memory into an associative reasoning network.*
|
|
@@ -739,8 +782,9 @@ The Generator strips the `console.log`, resubmits, and the next `EVALUATE` retur
|
|
|
739
782
|
|
|
740
783
|
## What's New
|
|
741
784
|
|
|
742
|
-
> **Current release:
|
|
785
|
+
> **Current release: v9.0.4 — Autonomous Cognitive OS**
|
|
743
786
|
|
|
787
|
+
- 🧠 **v9.0.0 — Autonomous Cognitive OS:** Affect-Tagged Memory (valence engine — emotional salience boosts retrieval), Token-Economic Cognitive Budget (UBI + cost-per-save incentivizes novel memories), Surprisal Gate (vector-based novelty scoring). Full SQLite + Supabase parity with auto-migration 42. Hybrid scoring: `0.65 × similarity + 0.25 × activation + 0.10 × |valence|`. All features opt-out via env. **Post-review hardening:** 8 architectural fixes including delta-based concurrent budget writes, energy-weighted valence propagation, and anti-exploit budget decoupling. Graceful degradation: budget exhaustion warns but never blocks.
|
|
744
788
|
- ⚡ **v8.0.0 — Synapse Engine:** Pure, storage-agnostic multi-hop graph propagation engine replaces the legacy SQL-coupled spreading activation. O(T × M) bounded ACT-R energy propagation with dampened fan effect, asymmetric bidirectional flow, cyclic loop prevention, and sigmoid normalization. Full integration into both SQLite and Supabase backends. 5 new config knobs. Battle-hardened with NaN guards, config clamping, non-fatal enrichment, and 16 passing tests. **Memory search now follows the causal graph, not just keywords.** → [Synapse Engine](#synapse-engine-v80)
|
|
745
789
|
- 🧠 **v7.8.x — Cognitive Architecture:** Episodic-to-Semantic consolidation (Hebbian learning), ACT-R Spreading Activation with multi-hop causal reasoning, Uncertainty-Aware Rejection Gate, and Dynamic Fast Weight Decay. Validated by **LoCoMo-Plus benchmark**. → [Cognitive Architecture](#cognitive-architecture-v78)
|
|
746
790
|
- 🌐 **v7.7.0 — Cloud-Native SSE Transport:** Full unauthenticated and authenticated Server-Sent Events MCP support for seamless network deployments.
|
|
@@ -1113,8 +1157,10 @@ Prism has evolved from smart session logging into a **cognitive memory architect
|
|
|
1113
1157
|
| **v7.8** | Dynamic Fast Weight Decay — `is_rollup` semantic nodes decay 50% slower (`ageModifier = 0.5`) than episodic entries, creating Long-Term Context anchors | ACT-R base-level activation with differential decay rates | ✅ Shipped |
|
|
1114
1158
|
| **v7.8** | LoCoMo Benchmark Harness — deterministic integration suite (`tests/benchmarks/locomo.ts`, 20 assertions) benchmarking multi-hop compaction structures via `MockLLM` | Long-Context Memory evaluation (cognitive benchmarking) | ✅ Shipped |
|
|
1115
1159
|
| **v7.8** | LoCoMo-Plus Benchmark — 16-assertion suite (`tests/benchmarks/locomo-plus.ts`) adapted from arXiv 2602.10715 validating cue–trigger semantic disconnect bridging via graph traversal and Hebbian consolidation; reports Precision@1/3/5/10 and MRR | LoCoMo-Plus (Li et al., ARR 2026), cue–trigger disconnect research | ✅ Shipped |
|
|
1116
|
-
| **
|
|
1117
|
-
| **
|
|
1160
|
+
| **v9.0** | Affect-Tagged Memory — valence-weighted retrieval; emotional salience boosts recall | Affect-modulated retrieval (neuroscience), Somatic marker hypothesis (Damasio) | ✅ Shipped |
|
|
1161
|
+
| **v9.0** | Token-Economic Cognitive Budget — UBI + cost-per-save token economy | Behavioral economics, bounded rationality (Simon) | ✅ Shipped |
|
|
1162
|
+
| **v9.0** | Surprisal Gate — novelty-based cost multiplier (high surprisal = cheap storage) | Bayesian surprise, predictive coding (Friston) | ✅ Shipped |
|
|
1163
|
+
| **v10+** | Zero-Search Retrieval — no index, no ANN, just ask the vector | Holographic Reduced Representations | 🔭 Horizon |
|
|
1118
1164
|
|
|
1119
1165
|
> Informed by Anderson's ACT-R (Adaptive Control of Thought—Rational), Collins & Loftus spreading activation networks (1975), Kanerva's SDM (1988), Hebb's learning rule, Li et al. LoCoMo-Plus (ARR 2026), and LeCun's "Why AI Systems Don't Learn" (Dupoux, LeCun, Malik).
|
|
1120
1166
|
|
|
@@ -1122,10 +1168,11 @@ Prism has evolved from smart session logging into a **cognitive memory architect
|
|
|
1122
1168
|
|
|
1123
1169
|
## Milestones & Roadmap
|
|
1124
1170
|
|
|
1125
|
-
> **Current:
|
|
1171
|
+
> **Current: v9.0.0** — Autonomous Cognitive OS ([CHANGELOG](CHANGELOG.md))
|
|
1126
1172
|
|
|
1127
1173
|
| Release | Headline |
|
|
1128
1174
|
|---------|----------|
|
|
1175
|
+
| **v9.0** | 🧠 Autonomous Cognitive OS — Affect-Tagged Memory (valence engine), Token-Economic Cognitive Budget, Surprisal Gate |
|
|
1129
1176
|
| **v8.0** | ⚡ Synapse Engine — Pure multi-hop GraphRAG propagation, storage-agnostic, NaN-hardened, `[🌐 Synapse]` discovery tags |
|
|
1130
1177
|
| **v7.8** | 🧠 Cognitive Architecture — Hebbian consolidation, multi-hop reasoning, rejection gate, dynamic decay |
|
|
1131
1178
|
| **v7.7** | 🌐 Cloud-Native SSE Transport |
|
|
@@ -1139,8 +1186,9 @@ Prism has evolved from smart session logging into a **cognitive memory architect
|
|
|
1139
1186
|
| **v6.2** | 🧩 Synthesize & Prune |
|
|
1140
1187
|
|
|
1141
1188
|
### Future Tracks
|
|
1142
|
-
- **
|
|
1143
|
-
- **
|
|
1189
|
+
- **v9.1: Predictive Push Memory** — Proactive context injection before the agent even asks — anticipating what it will need next.
|
|
1190
|
+
- **v9.4: Counterfactual Memory Branches** — "What if" reasoning over alternative decision paths.
|
|
1191
|
+
- **v10+: Zero-Search Retrieval** — Direct vector-addressed recall via Holographic Reduced Representations.
|
|
1144
1192
|
|
|
1145
1193
|
👉 **[Full ROADMAP.md →](ROADMAP.md)**
|
|
1146
1194
|
|
|
@@ -1177,10 +1225,33 @@ A: Run `npm run build && npm test`, then open the Mind Palace dashboard (`localh
|
|
|
1177
1225
|
|
|
1178
1226
|
---
|
|
1179
1227
|
|
|
1228
|
+
## Enterprise & Commercial Support
|
|
1229
|
+
|
|
1230
|
+
Prism is the **cognitive infrastructure layer** for production AI agent deployments. If your organization is building agent-powered products, we offer:
|
|
1231
|
+
|
|
1232
|
+
### 🏢 Enterprise Integration
|
|
1233
|
+
- **Dedicated integration engineering** — Custom deployment into your existing agent stack (LangChain, LlamaIndex, CrewAI, AutoGen, custom MCP pipelines)
|
|
1234
|
+
- **On-premises deployment** — Air-gapped installations with full SQLite local mode, zero cloud dependency
|
|
1235
|
+
- **SSO & RBAC** — Enterprise authentication and role-based access control for multi-team Hivemind deployments
|
|
1236
|
+
- **SLA-backed support** — Priority issue resolution, architecture review, and upgrade planning
|
|
1237
|
+
|
|
1238
|
+
### 🔬 Research & Institutional Partnerships
|
|
1239
|
+
- **Academic collaborations** — Prism's cognitive architecture is grounded in peer-reviewed research (ACT-R, Hebbian learning, SDM, HDC). We partner with research labs working on agent memory, cognitive modeling, and neurosymbolic AI.
|
|
1240
|
+
- **Grant-funded integrations** — We work with institutions applying for NSF, DARPA, or EU Horizon grants that require production-grade agent memory infrastructure.
|
|
1241
|
+
|
|
1242
|
+
### 📬 Contact
|
|
1243
|
+
- **Enterprise inquiries:** [enterprise@prism-mcp.dev](mailto:enterprise@prism-mcp.dev)
|
|
1244
|
+
- **Partnership proposals:** [partnerships@prism-mcp.dev](mailto:partnerships@prism-mcp.dev)
|
|
1245
|
+
- **GitHub Issues:** [github.com/dcostenco/prism-mcp/issues](https://github.com/dcostenco/prism-mcp/issues) (community support)
|
|
1246
|
+
|
|
1247
|
+
> 💡 **Open Source commitment:** Prism MCP remains MIT-licensed and free for individual developers, startups, and research teams. Enterprise services fund continued open-source development.
|
|
1248
|
+
|
|
1249
|
+
---
|
|
1250
|
+
|
|
1180
1251
|
## License
|
|
1181
1252
|
|
|
1182
1253
|
MIT
|
|
1183
1254
|
|
|
1184
1255
|
---
|
|
1185
1256
|
|
|
1186
|
-
<sub>**Keywords:** MCP server, Model Context Protocol, Claude Desktop memory, persistent session memory, AI agent memory, cognitive architecture, ACT-R spreading activation, Hebbian learning, episodic semantic consolidation, multi-hop reasoning, uncertainty rejection gate, local-first, SQLite MCP, Mind Palace, time travel, visual memory, VLM image captioning, OpenTelemetry, GDPR, agent telepathy, multi-agent sync, behavioral memory, cursorrules, Ollama MCP, Brave Search MCP, TurboQuant, progressive context loading, knowledge management, LangChain retriever, LangGraph agent</sub>
|
|
1257
|
+
<sub>**Keywords:** MCP server, Model Context Protocol, Claude Desktop memory, persistent session memory, AI agent memory, cognitive architecture, ACT-R spreading activation, Hebbian learning, episodic semantic consolidation, multi-hop reasoning, uncertainty rejection gate, local-first, SQLite MCP, Mind Palace, time travel, visual memory, VLM image captioning, OpenTelemetry, GDPR, agent telepathy, multi-agent sync, behavioral memory, cursorrules, Ollama MCP, Brave Search MCP, TurboQuant, progressive context loading, knowledge management, LangChain retriever, LangGraph agent, enterprise AI agent infrastructure, autonomous cognitive OS, affect-tagged memory, valence engine, cognitive budget, surprisal gate</sub>
|
package/dist/cli.js
CHANGED
|
File without changes
|
package/dist/config.js
CHANGED
|
@@ -78,7 +78,10 @@ export const VOYAGE_API_KEY = process.env.VOYAGE_API_KEY;
|
|
|
78
78
|
//
|
|
79
79
|
// Set PRISM_STORAGE=local to use SQLite (once implemented).
|
|
80
80
|
// Set PRISM_STORAGE=supabase to use Supabase REST API (default).
|
|
81
|
-
|
|
81
|
+
// NOTE: This constant captures the env-var snapshot at import time.
|
|
82
|
+
// The actual storage backend decision is made in storage/index.ts,
|
|
83
|
+
// which consults prism-config.db first, then process.env, then defaults to "local".
|
|
84
|
+
export const PRISM_STORAGE = process.env.PRISM_STORAGE || "local";
|
|
82
85
|
// Logged at debug level — see debug() at bottom of file
|
|
83
86
|
// ─── Optional: Supabase (Session Memory Module) ───────────────
|
|
84
87
|
// When both SUPABASE_URL and SUPABASE_KEY are set, session memory tools
|
|
@@ -136,8 +139,22 @@ export const PRISM_DEBUG_LOGGING = process.env.PRISM_DEBUG_LOGGING === "true";
|
|
|
136
139
|
// The role parameter on existing tools (session_save_ledger, etc.)
|
|
137
140
|
// is always available regardless of this flag — adding a parameter
|
|
138
141
|
// doesn't increase tool count.
|
|
139
|
-
//
|
|
140
|
-
|
|
142
|
+
//
|
|
143
|
+
// SOURCE OF TRUTH: The Mind Palace dashboard (Settings → Hivemind Mode)
|
|
144
|
+
// persists this flag to prism-config.db via getSettingSync() at call time.
|
|
145
|
+
//
|
|
146
|
+
// ⚠️ IMPORTANT: This _ENV constant captures ONLY the env-var fallback.
|
|
147
|
+
// config.ts is evaluated at ESM import time, BEFORE initConfigStorage()
|
|
148
|
+
// populates the settings cache. Use getSettingSync("hivemind_enabled",
|
|
149
|
+
// String(PRISM_ENABLE_HIVEMIND_ENV)) at each call site for the live value.
|
|
150
|
+
export const PRISM_ENABLE_HIVEMIND_ENV = process.env.PRISM_ENABLE_HIVEMIND === "true";
|
|
151
|
+
// ─── v3.0: Task Router Feature Flag ──────────────────────────
|
|
152
|
+
// Routes tasks to the local Claw agent when enabled.
|
|
153
|
+
// SOURCE OF TRUTH: dashboard (Settings → Task Router) → prism-config.db.
|
|
154
|
+
// Same _ENV pattern: use getSettingSync() at call sites.
|
|
155
|
+
// REMOVED: PRISM_TASK_ROUTER_ENABLED used to call getSettingSync() at import time,
|
|
156
|
+
// which always returned the fallback due to the ESM race condition (settingsCache=null).
|
|
157
|
+
// Use PRISM_TASK_ROUTER_ENABLED_ENV (line ~368) and getSettingSync() at call sites instead.
|
|
141
158
|
// ─── v4.1: Auto-Load Projects ────────────────────────────────
|
|
142
159
|
// Auto-load is configured exclusively via the Mind Palace dashboard
|
|
143
160
|
// ("Auto-Load Projects" checkboxes in Settings). The setting is stored
|
|
@@ -262,8 +279,10 @@ export const PRISM_VERIFICATION_DEFAULT_SEVERITY = (process.env.PRISM_VERIFICATI
|
|
|
262
279
|
// ─── v7.3: Dark Factory Orchestration ─────────────────────────
|
|
263
280
|
// Autonomous pipeline runner: PLAN → EXECUTE → VERIFY → iterate.
|
|
264
281
|
// Opt-in because it executes LLM calls in the background.
|
|
265
|
-
/** Master switch for the Dark Factory background runner.
|
|
266
|
-
|
|
282
|
+
/** Master switch for the Dark Factory background runner.
|
|
283
|
+
* ⚠️ ENV-only fallback. Use getSettingSync("dark_factory_enabled",
|
|
284
|
+
* String(PRISM_DARK_FACTORY_ENABLED_ENV)) at call sites. */
|
|
285
|
+
export const PRISM_DARK_FACTORY_ENABLED_ENV = process.env.PRISM_DARK_FACTORY_ENABLED === "true"; // Opt-in
|
|
267
286
|
/** Poll interval for the runner loop (ms). Default: 30s. */
|
|
268
287
|
export const PRISM_DARK_FACTORY_POLL_MS = parseInt(process.env.PRISM_DARK_FACTORY_POLL_MS || "30000", 10);
|
|
269
288
|
/** Default max wall-clock time per pipeline (ms). Default: 15 minutes. */
|
|
@@ -282,3 +301,21 @@ export const PRISM_SYNAPSE_SPREAD_FACTOR = parseFloat(process.env.PRISM_SYNAPSE_
|
|
|
282
301
|
export const PRISM_SYNAPSE_LATERAL_INHIBITION = parseInt(process.env.PRISM_SYNAPSE_LATERAL_INHIBITION || "7", 10);
|
|
283
302
|
/** Soft cap on active nodes per iteration (prevents explosion). (Default: 20) */
|
|
284
303
|
export const PRISM_SYNAPSE_SOFT_CAP = parseInt(process.env.PRISM_SYNAPSE_SOFT_CAP || "20", 10);
|
|
304
|
+
// ─── v9.0: Affect-Tagged Memory (Valence Engine) ─────────────
|
|
305
|
+
// Derives emotional valence from experience events and uses
|
|
306
|
+
// Affective Salience (|valence| boosts retrieval) for ranking.
|
|
307
|
+
/** Master switch for affect-tagged memory. (Default: true) */
|
|
308
|
+
export const PRISM_VALENCE_ENABLED = (process.env.PRISM_VALENCE_ENABLED ?? "true") !== "false";
|
|
309
|
+
/** Weight of |valence| in hybrid scoring formula. (Default: 0.1) */
|
|
310
|
+
export const PRISM_VALENCE_WEIGHT = parseFloat(process.env.PRISM_VALENCE_WEIGHT || "0.1");
|
|
311
|
+
/** Average valence below this threshold triggers a UX warning. (Default: -0.3) */
|
|
312
|
+
export const PRISM_VALENCE_WARNING_THRESHOLD = parseFloat(process.env.PRISM_VALENCE_WARNING_THRESHOLD || "-0.3");
|
|
313
|
+
// ─── v9.0: Token-Economic RL (Cognitive Budget) ──────────────
|
|
314
|
+
// Implements a strict token economy for agent memory operations.
|
|
315
|
+
// Budget is persistent (stored in session_handoffs.cognitive_budget).
|
|
316
|
+
/** Master switch for the cognitive budget system. (Default: true) */
|
|
317
|
+
export const PRISM_COGNITIVE_BUDGET_ENABLED = (process.env.PRISM_COGNITIVE_BUDGET_ENABLED ?? "true") !== "false";
|
|
318
|
+
/** Initial budget size per project in tokens. (Default: 2000) */
|
|
319
|
+
export const PRISM_COGNITIVE_BUDGET_SIZE = parseInt(process.env.PRISM_COGNITIVE_BUDGET_SIZE || "2000", 10);
|
|
320
|
+
/** Master switch for the surprisal gate. (Default: true) */
|
|
321
|
+
export const PRISM_SURPRISAL_GATE_ENABLED = (process.env.PRISM_SURPRISAL_GATE_ENABLED ?? "true") !== "false";
|
package/dist/dashboard/server.js
CHANGED
|
@@ -20,6 +20,9 @@ import * as http from "http";
|
|
|
20
20
|
import * as path from "path";
|
|
21
21
|
import * as os from "os";
|
|
22
22
|
import * as fs from "fs";
|
|
23
|
+
import * as pg from "pg";
|
|
24
|
+
import { fileURLToPath } from "url";
|
|
25
|
+
import { dirname, resolve } from "path";
|
|
23
26
|
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
|
24
27
|
import { createServer, getAllPossibleTools } from "../server.js";
|
|
25
28
|
import { getStorage } from "../storage/index.js";
|
|
@@ -34,6 +37,13 @@ import { redactSettings } from "../tools/commonHelpers.js";
|
|
|
34
37
|
import { handleGraphRoutes } from "./graphRouter.js";
|
|
35
38
|
import { safeCompare, generateToken, isAuthenticated, createRateLimiter, } from "./authUtils.js";
|
|
36
39
|
const PORT = parseInt(process.env.PRISM_DASHBOARD_PORT || "3000", 10);
|
|
40
|
+
/**
|
|
41
|
+
* v9.2: SSE stream registry for migration progress.
|
|
42
|
+
* Key = progressKey (timestamp string from the client).
|
|
43
|
+
* Value = the ServerResponse that is kept open as an SSE stream.
|
|
44
|
+
* Entries are deleted when the stream ends or the client disconnects.
|
|
45
|
+
*/
|
|
46
|
+
const migrationProgressStreams = new Map();
|
|
37
47
|
/** Read HTTP request body as string (Buffer-based to avoid GC thrash on large imports) */
|
|
38
48
|
function readBody(req) {
|
|
39
49
|
return new Promise((resolve, reject) => {
|
|
@@ -575,6 +585,11 @@ return false;}
|
|
|
575
585
|
try {
|
|
576
586
|
const { getAllSettings } = await import("../storage/configStorage.js");
|
|
577
587
|
const settings = await getAllSettings();
|
|
588
|
+
// Since v3.0, the DB is the exclusive source of truth for dashboard UI state.
|
|
589
|
+
// Values from process.env are seeded into the DB on first startup via
|
|
590
|
+
// migrateEnvToConfigStorage(), but we no longer override DB settings here.
|
|
591
|
+
// This ensures that dashboard changes safely persist across restarts even
|
|
592
|
+
// if legacy .env values remain.
|
|
578
593
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
579
594
|
return res.end(JSON.stringify({ settings }));
|
|
580
595
|
}
|
|
@@ -602,6 +617,109 @@ return false;}
|
|
|
602
617
|
return res.end(JSON.stringify({ error: "Invalid JSON body" }));
|
|
603
618
|
}
|
|
604
619
|
}
|
|
620
|
+
// ─── API: Migration Progress SSE Stream (v9.2) ───────────
|
|
621
|
+
// Client subscribes with GET /api/migration/progress?key=<progressKey>
|
|
622
|
+
// Server pushes { step, total, label, pct?, done?, error? } events.
|
|
623
|
+
// The stream is closed server-side once setup-supabase completes.
|
|
624
|
+
if (url.pathname === "/api/migration/progress" && req.method === "GET") {
|
|
625
|
+
const key = url.searchParams.get("key") || "";
|
|
626
|
+
res.writeHead(200, {
|
|
627
|
+
"Content-Type": "text/event-stream",
|
|
628
|
+
"Cache-Control": "no-cache",
|
|
629
|
+
"Connection": "keep-alive",
|
|
630
|
+
"X-Accel-Buffering": "no",
|
|
631
|
+
});
|
|
632
|
+
res.write("retry: 1000\n\n"); // 1s reconnect delay
|
|
633
|
+
// Register the response so setup-supabase can push events
|
|
634
|
+
migrationProgressStreams.set(key, res);
|
|
635
|
+
req.on("close", () => {
|
|
636
|
+
migrationProgressStreams.delete(key);
|
|
637
|
+
});
|
|
638
|
+
return; // keep connection open — do NOT call res.end() here
|
|
639
|
+
}
|
|
640
|
+
// ─── API: Supabase Initial Setup (v9.1) ─────────────────
|
|
641
|
+
if (url.pathname === "/api/setup-supabase" && req.method === "POST") {
|
|
642
|
+
// Hoist progressKey so the catch block can reference it for SSE error reporting
|
|
643
|
+
let progressKey;
|
|
644
|
+
try {
|
|
645
|
+
const body = await readBody(req);
|
|
646
|
+
const parsed = JSON.parse(body);
|
|
647
|
+
const { url: supaUrl, serviceKey, dbPassword } = parsed;
|
|
648
|
+
progressKey = parsed.progressKey;
|
|
649
|
+
if (!supaUrl || !serviceKey || !dbPassword) {
|
|
650
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
651
|
+
return res.end(JSON.stringify({ error: "Missing url, serviceKey, or dbPassword" }));
|
|
652
|
+
}
|
|
653
|
+
// Helper: push SSE progress event to the subscribed client
|
|
654
|
+
function emitProgress(step, total, label, extra = {}) {
|
|
655
|
+
const stream = migrationProgressStreams.get(progressKey || "");
|
|
656
|
+
if (!stream)
|
|
657
|
+
return;
|
|
658
|
+
const pct = Math.round((step / total) * 100);
|
|
659
|
+
const payload = JSON.stringify({ step, total, label, pct, ...extra });
|
|
660
|
+
stream.write(`data: ${payload}\n\n`);
|
|
661
|
+
}
|
|
662
|
+
const TOTAL_STEPS = 6;
|
|
663
|
+
emitProgress(1, TOTAL_STEPS, "Connecting to Supabase database…");
|
|
664
|
+
// 1. Build DB connection string
|
|
665
|
+
const parsedUrl = new URL(supaUrl);
|
|
666
|
+
const host = parsedUrl.host; // e.g. pjddaprqhwqxtcpdmprk.supabase.co
|
|
667
|
+
const projectRef = host.split(".")[0];
|
|
668
|
+
const dbHost = `db.${projectRef}.supabase.co`;
|
|
669
|
+
const connectionString = `postgresql://postgres:${encodeURIComponent(dbPassword)}@${dbHost}:5432/postgres`;
|
|
670
|
+
emitProgress(2, TOTAL_STEPS, "Authenticating…");
|
|
671
|
+
// 2. Connect via pg
|
|
672
|
+
const client = new pg.Client({ connectionString });
|
|
673
|
+
await client.connect();
|
|
674
|
+
try {
|
|
675
|
+
emitProgress(3, TOTAL_STEPS, "Applying migration schema (027)…");
|
|
676
|
+
// 3. Inject auto-migration infrastructure
|
|
677
|
+
const currentDir = dirname(fileURLToPath(import.meta.url));
|
|
678
|
+
const sqlPath = resolve(currentDir, "../../supabase/migrations/027_auto_migration_infra.sql");
|
|
679
|
+
const sql = fs.readFileSync(sqlPath, "utf-8");
|
|
680
|
+
await client.query(sql);
|
|
681
|
+
emitProgress(4, TOTAL_STEPS, "Applying v9.0 schema columns…");
|
|
682
|
+
// 4. Also safely inject v9.0 columns just in case the backend tries to write them right away
|
|
683
|
+
await client.query(`
|
|
684
|
+
ALTER TABLE session_ledger ADD COLUMN IF NOT EXISTS valence REAL DEFAULT NULL;
|
|
685
|
+
CREATE INDEX IF NOT EXISTS idx_ledger_valence ON session_ledger(valence) WHERE valence IS NOT NULL;
|
|
686
|
+
ALTER TABLE session_handoffs ADD COLUMN IF NOT EXISTS cognitive_budget REAL DEFAULT NULL;
|
|
687
|
+
`);
|
|
688
|
+
}
|
|
689
|
+
finally {
|
|
690
|
+
await client.end();
|
|
691
|
+
}
|
|
692
|
+
emitProgress(5, TOTAL_STEPS, "Persisting credentials…");
|
|
693
|
+
// 5. Persist values using configStorage
|
|
694
|
+
const { setSetting } = await import("../storage/configStorage.js");
|
|
695
|
+
await setSetting("PRISM_STORAGE", "supabase");
|
|
696
|
+
await setSetting("SUPABASE_URL", supaUrl);
|
|
697
|
+
await setSetting("SUPABASE_KEY", serviceKey);
|
|
698
|
+
await setSetting("SUPABASE_SERVICE_ROLE_KEY", serviceKey);
|
|
699
|
+
emitProgress(6, TOTAL_STEPS, "Complete!", { done: true });
|
|
700
|
+
// Close the SSE stream
|
|
701
|
+
const sseStream = migrationProgressStreams.get(progressKey || "");
|
|
702
|
+
if (sseStream) {
|
|
703
|
+
sseStream.end();
|
|
704
|
+
migrationProgressStreams.delete(progressKey || "");
|
|
705
|
+
}
|
|
706
|
+
// 6. Return success
|
|
707
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
708
|
+
return res.end(JSON.stringify({ ok: true, message: "Supabase successfully configured! Please restart Prism." }));
|
|
709
|
+
}
|
|
710
|
+
catch (err) {
|
|
711
|
+
console.error("[Dashboard] Supabase Setup error:", err);
|
|
712
|
+
// Emit error event to the progress stream (progressKey is captured from the outer scope)
|
|
713
|
+
const errStream = migrationProgressStreams.get(progressKey || "");
|
|
714
|
+
if (errStream) {
|
|
715
|
+
errStream.write(`data: ${JSON.stringify({ error: true, label: err.message || "Setup failed", done: false })}\n\n`);
|
|
716
|
+
errStream.end();
|
|
717
|
+
migrationProgressStreams.delete(progressKey || "");
|
|
718
|
+
}
|
|
719
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
720
|
+
return res.end(JSON.stringify({ error: err.message || "Failed to setup Supabase" }));
|
|
721
|
+
}
|
|
722
|
+
}
|
|
605
723
|
// ─── API: Memory Analytics (v3.1) ────────────────────
|
|
606
724
|
if (url.pathname === "/api/analytics" && req.method === "GET") {
|
|
607
725
|
const projectName = url.searchParams.get("project");
|