prism-mcp-server 9.0.4 → 9.0.5
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 +44 -139
- package/dist/config.js +5 -56
- package/dist/darkfactory/runner.js +0 -7
- package/dist/darkfactory/safetyController.js +2 -10
- package/dist/dashboard/authUtils.js +30 -2
- package/dist/dashboard/server.js +14 -131
- package/dist/dashboard/ui.js +7 -283
- package/dist/memory/spreadingActivation.js +107 -0
- package/dist/observability/graphMetrics.js +0 -44
- package/dist/scholar/webScholar.js +6 -7
- package/dist/sdm/sdmEngine.js +3 -27
- package/dist/server.js +19 -60
- package/dist/storage/index.js +9 -53
- package/dist/storage/sqlite.js +24 -226
- package/dist/storage/supabase.js +10 -233
- package/dist/storage/supabaseMigrations.js +0 -30
- package/dist/sync/factory.js +1 -5
- package/dist/tools/graphHandlers.js +138 -41
- package/dist/tools/hygieneHandlers.js +33 -61
- package/dist/tools/ledgerHandlers.js +4 -122
- package/dist/utils/actrActivation.js +0 -2
- package/dist/utils/executor.js +0 -1
- package/dist/utils/llm/adapters/traced.js +0 -35
- package/dist/utils/llm/adapters/voyage.js +41 -67
- package/dist/utils/llm/factory.js +14 -38
- package/dist/utils/llm/provider.js +0 -2
- package/package.json +4 -13
package/README.md
CHANGED
|
@@ -8,11 +8,11 @@
|
|
|
8
8
|
[](https://www.typescriptlang.org/)
|
|
9
9
|
[](CONTRIBUTING.md)
|
|
10
10
|
|
|
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 v7.8 is a true **Cognitive Architecture** inspired by human brain mechanics. Beyond flat vector search, your agent now forms principles from experience, follows causal trains of thought, and possesses the self-awareness to know when it lacks information. **Your agents don't just remember; they learn.**
|
|
16
16
|
|
|
17
17
|
```bash
|
|
18
18
|
npx -y prism-mcp-server
|
|
@@ -20,7 +20,7 @@ npx -y prism-mcp-server
|
|
|
20
20
|
|
|
21
21
|
Works with **Claude Desktop · Claude Code · Cursor · Windsurf · Cline · Gemini · Antigravity** — **any MCP client.**
|
|
22
22
|
|
|
23
|
-
## Table of Contents
|
|
23
|
+
## 📖 Table of Contents
|
|
24
24
|
|
|
25
25
|
- [Why Prism?](#why-prism)
|
|
26
26
|
- [Quick Start](#quick-start)
|
|
@@ -28,9 +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
|
-
- [
|
|
32
|
-
- [Synapse Engine (v8.0)](#synapse-engine-v80)
|
|
33
|
-
- [Cognitive Architecture (v7.8)](#cognitive-architecture-v78)
|
|
31
|
+
- [Cognitive Architecture (v7.8)](#-cognitive-architecture-v78)
|
|
34
32
|
- [Data Privacy & Egress](#data-privacy--egress)
|
|
35
33
|
- [Use Cases](#use-cases)
|
|
36
34
|
- [What's New](#whats-new)
|
|
@@ -40,7 +38,6 @@ Works with **Claude Desktop · Claude Code · Cursor · Windsurf · Cline · Gem
|
|
|
40
38
|
- [Architecture](#architecture)
|
|
41
39
|
- [Scientific Foundation](#scientific-foundation)
|
|
42
40
|
- [Milestones & Roadmap](#milestones--roadmap)
|
|
43
|
-
- [Enterprise & Commercial Support](#enterprise--commercial-support)
|
|
44
41
|
- [Troubleshooting FAQ](#troubleshooting-faq)
|
|
45
42
|
|
|
46
43
|
---
|
|
@@ -55,15 +52,15 @@ Every time you start a new conversation with an AI coding assistant, it starts f
|
|
|
55
52
|
|
|
56
53
|
Prism has three pillars:
|
|
57
54
|
|
|
58
|
-
1. **🧠 Cognitive Memory** — Memories are ranked like a human brain: recently and frequently accessed context surfaces first, while stale context fades naturally via ACT-R activation decay. Raw experience consolidates into semantic principles through Hebbian learning. The result is retrieval quality that no flat vector search can match. *(See [Cognitive Architecture](
|
|
55
|
+
1. **🧠 Cognitive Memory** — Memories are ranked like a human brain: recently and frequently accessed context surfaces first, while stale context fades naturally via ACT-R activation decay. Raw experience consolidates into semantic principles through Hebbian learning. The result is retrieval quality that no flat vector search can match. *(See [Cognitive Architecture](#-cognitive-architecture-v78) and [Scientific Foundation](#-scientific-foundation).)*
|
|
59
56
|
|
|
60
|
-
2.
|
|
57
|
+
2. **🔗 Multi-Hop Reasoning** — When your agent searches for "Error X", Prism doesn't just find logs mentioning "Error X". Spreading activation traverses the causal graph and brings back "Workaround Y", which is connected to "Architecture Decision Z" — a literal train of thought. *(See [Cognitive Architecture](#-cognitive-architecture-v78).)*
|
|
61
58
|
|
|
62
|
-
3. **🏭 Autonomous Execution (Dark Factory)** — When you're ready, Prism can run coding tasks end-to-end with a fail-closed pipeline where an adversarial evaluator catches bugs the generator missed — before you ever see the PR. *(See [Dark Factory](
|
|
59
|
+
3. **🏭 Autonomous Execution (Dark Factory)** — When you're ready, Prism can run coding tasks end-to-end with a fail-closed pipeline where an adversarial evaluator catches bugs the generator missed — before you ever see the PR. *(See [Dark Factory](#-dark-factory--adversarial-autonomous-pipelines).)*
|
|
63
60
|
|
|
64
61
|
---
|
|
65
62
|
|
|
66
|
-
## Quick Start
|
|
63
|
+
## 🚀 Quick Start
|
|
67
64
|
|
|
68
65
|
### Prerequisites
|
|
69
66
|
|
|
@@ -137,7 +134,7 @@ Then open `http://localhost:3001` instead.
|
|
|
137
134
|
|
|
138
135
|
---
|
|
139
136
|
|
|
140
|
-
## The Magic Moment
|
|
137
|
+
## ✨ The Magic Moment
|
|
141
138
|
|
|
142
139
|
> **Session 1** (Monday evening):
|
|
143
140
|
> ```
|
|
@@ -158,7 +155,7 @@ Then open `http://localhost:3001` instead.
|
|
|
158
155
|
|
|
159
156
|
---
|
|
160
157
|
|
|
161
|
-
## Setup Guides
|
|
158
|
+
## 📖 Setup Guides
|
|
162
159
|
|
|
163
160
|
<details>
|
|
164
161
|
<summary><strong>Claude Desktop</strong></summary>
|
|
@@ -381,7 +378,7 @@ Prism can be deployed natively to cloud platforms like [Render](https://render.c
|
|
|
381
378
|
|
|
382
379
|
---
|
|
383
380
|
|
|
384
|
-
## Universal Import: Bring Your History
|
|
381
|
+
## 📥 Universal Import: Bring Your History
|
|
385
382
|
|
|
386
383
|
Switching to Prism? Don't leave months of AI session history behind. Prism can **ingest historical sessions from Claude Code, Gemini, and OpenAI** and give your Mind Palace an instant head start — no manual re-entry required.
|
|
387
384
|
|
|
@@ -414,15 +411,9 @@ npx -y prism-mcp-server universal-import --format gemini --path ./gemini_history
|
|
|
414
411
|
|
|
415
412
|
---
|
|
416
413
|
|
|
417
|
-
## What Makes Prism Different
|
|
414
|
+
## ✨ What Makes Prism Different
|
|
418
415
|
|
|
419
416
|
|
|
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
|
-
|
|
426
417
|
### 🧠 Your Agent Learns From Mistakes
|
|
427
418
|
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.
|
|
428
419
|
|
|
@@ -463,34 +454,33 @@ OpenTelemetry spans for every MCP tool call, LLM hop, and background worker. Rou
|
|
|
463
454
|
### 🌐 Autonomous Web Scholar
|
|
464
455
|
Prism researches while you sleep. A background pipeline searches the web, scrapes articles, synthesizes findings via LLM, and injects results directly into your semantic memory — fully searchable on your next session. Brave Search → Firecrawl scrape → LLM synthesis → Prism ledger. Task-aware, Hivemind-integrated, and zero-config when API keys are missing (falls back to Yahoo + Readability).
|
|
465
456
|
|
|
466
|
-
### Dark Factory — Adversarial Autonomous Pipelines
|
|
457
|
+
### 🏭 Dark Factory — Adversarial Autonomous Pipelines
|
|
467
458
|
When you trigger a Dark Factory pipeline, Prism doesn't just run your task — it fights itself to produce high-quality output. A `PLAN_CONTRACT` step locks a machine-parseable rubric before any code is written. After execution, an **Adversarial Evaluator** (in a fully isolated context) scores the output against the rubric. It cannot pass the Generator without providing exact file and line evidence for every failing criterion. Failed evaluations inject the critique directly into the Generator's retry prompt so it's never flying blind. The result: security issues, regressions, and lazy debug logs caught autonomously — before you ever see the PR. → [See it in action](examples/adversarial-eval-demo/README.md)
|
|
468
459
|
|
|
469
460
|
---
|
|
470
461
|
|
|
471
462
|
## 🤖 Autonomous Cognitive OS (v9.0)
|
|
472
463
|
|
|
473
|
-
> *Memory isn't just about storing data; it's about economics and emotion. v9.0 transforms
|
|
464
|
+
> *Memory isn't just about storing data; it's about economics and emotion. Prism v9.0 transforms passive memory into a living Cognitive Operating System that forces agents to learn compression and develop intuition.*
|
|
474
465
|
|
|
475
|
-
Most AI agents have an infinite memory budget. They dump massive, repetitive logs into vector databases until
|
|
466
|
+
Most AI agents have an infinite memory budget. They dump massive, repetitive logs into vector databases until they bankrupt your API budget and choke their own context windows. Prism v9.0 fixes this by introducing **Token-Economic Reinforcement Learning** and **Affect-Tagged Memory**.
|
|
476
467
|
|
|
477
|
-
###
|
|
478
|
-
Prism
|
|
468
|
+
### 💰 Memory-as-an-Economy (The Surprisal Gate)
|
|
469
|
+
Prism assigns every project a strict **Cognitive Budget** (e.g., 2,000 tokens) that persists across sessions. Every time the agent saves a memory, it costs tokens.
|
|
479
470
|
|
|
480
|
-
But not all memories are priced equally:
|
|
481
|
-
* Prism intercepts the save and runs a **Vector-Based Surprisal** calculation against recent memories.
|
|
471
|
+
But not all memories are priced equally. Prism intercepts the save and runs a **Vector-Based Surprisal** calculation against recent memories:
|
|
482
472
|
* **High Surprisal (Novel thought):** Costs 0.5× tokens. The agent is rewarded for new insights.
|
|
483
473
|
* **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)
|
|
474
|
+
* **Universal Basic Income (UBI):** The budget recovers passively over time (+100 tokens/hour).
|
|
485
475
|
|
|
486
|
-
**
|
|
476
|
+
If an agent is too verbose, it goes into **Cognitive Debt**. 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
477
|
|
|
488
|
-
###
|
|
478
|
+
### 🎭 Affect-Tagged Memory (Giving AI a "Gut Feeling")
|
|
489
479
|
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
480
|
|
|
491
481
|
* **Affective Salience:** Prism automatically tags experience events with a `valence` score (-1.0 for failure, +1.0 for success).
|
|
492
482
|
* **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
|
|
483
|
+
* **UX Warnings:** If an agent retrieves memories that are historically negative, Prism intercepts the prompt injection: `⚠️ Caution: This topic is strongly correlated with historical failures. Review past decisions before proceeding.` Your AI now has a "gut feeling" about bad code.
|
|
494
484
|
|
|
495
485
|
### The Paradigm Shift
|
|
496
486
|
|
|
@@ -503,54 +493,7 @@ Vector math measures *semantic similarity*, not *sentiment*. If an agent searche
|
|
|
503
493
|
|
|
504
494
|
---
|
|
505
495
|
|
|
506
|
-
##
|
|
507
|
-
|
|
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.*
|
|
509
|
-
|
|
510
|
-
The Synapse Engine (v8.0) replaces the legacy SQL-coupled spreading activation with a **pure functional graph propagation core** inspired by ACT-R cognitive architecture. It is Prism's native, low-latency GraphRAG solution — no external graph database required.
|
|
511
|
-
|
|
512
|
-
### Before vs After
|
|
513
|
-
|
|
514
|
-
| | **v7.x (Standard RAG)** | **v8.0 (Synapse Engine)** |
|
|
515
|
-
|---|---|---|
|
|
516
|
-
| **Query** | "Tell me about Project Apollo" | "Tell me about Project Apollo" |
|
|
517
|
-
| **Retrieval** | Returns the design doc (1 hop, cosine match) | Returns the design doc → follows `caused_by` edge to a developer's debugging session → discovers an old Slack thread about a critical auth bug |
|
|
518
|
-
| **Agent output** | Summarizes the design doc | Summarizes the design doc **and warns about the unresolved auth issue** |
|
|
519
|
-
| **Discovery tag** | — | `[🌐 Synapse]` marks the auth bug node, proving the engine found context the user didn't ask for |
|
|
520
|
-
|
|
521
|
-
### How It Works
|
|
522
|
-
|
|
523
|
-
```
|
|
524
|
-
Query: "Project Apollo status"
|
|
525
|
-
│
|
|
526
|
-
┌───────────┼───────────────┐
|
|
527
|
-
▼ ▼ ▼
|
|
528
|
-
[Design [Sprint [Deployment
|
|
529
|
-
Doc] Retro] Log]
|
|
530
|
-
│ 1.0 │ 0.8 │ 0.6 ← semantic anchors
|
|
531
|
-
│ │ │
|
|
532
|
-
▼ ▼ ▼
|
|
533
|
-
[Dev [Auth Bug [Perf ← Synapse discovered
|
|
534
|
-
Profile Thread 🌐] Regression 🌐] (multi-hop)
|
|
535
|
-
0.42] 0.38] 0.31]
|
|
536
|
-
```
|
|
537
|
-
|
|
538
|
-
**Key design decisions:**
|
|
539
|
-
|
|
540
|
-
| Mechanism | Purpose |
|
|
541
|
-
|---|---|
|
|
542
|
-
| **Dampened Fan Effect** (`1/ln(degree+e)`) | Prevents hub nodes from flooding results |
|
|
543
|
-
| **Asymmetric Propagation** (fwd 100%, back 50%) | Preserves causal directionality |
|
|
544
|
-
| **Cyclic Loop Prevention** (`visitedEdges` set) | Prevents infinite energy amplification |
|
|
545
|
-
| **Sigmoid Normalization** | Structural scores can't overwhelm semantic base |
|
|
546
|
-
| **Lateral Inhibition** | Caps output to top-K most energized nodes |
|
|
547
|
-
| **Hybrid Scoring** (70% semantic / 30% structural) | Base relevance always matters |
|
|
548
|
-
|
|
549
|
-
> 💡 Synapse is **non-fatal** — if the graph traversal fails for any reason, search gracefully returns the original semantic matches. Zero risk of degraded search.
|
|
550
|
-
|
|
551
|
-
---
|
|
552
|
-
|
|
553
|
-
## Cognitive Architecture (v7.8)
|
|
496
|
+
## 🧠 Cognitive Architecture (v7.8)
|
|
554
497
|
|
|
555
498
|
> *Prism v7.8 is our biggest leap forward yet. We have moved beyond flat vector search and implemented a true Cognitive Architecture inspired by human brain mechanics. With the new ACT-R Spreading Activation Engine, Episodic-to-Semantic memory consolidation, and Uncertainty-Aware Rejection Gates, Prism doesn't just store logs anymore — it forms principles, follows causal trains of thought, and possesses the self-awareness to know when it lacks information.*
|
|
556
499
|
|
|
@@ -615,7 +558,7 @@ Standard RAG (Retrieval-Augmented Generation) is now a commodity. Everyone has v
|
|
|
615
558
|
|
|
616
559
|
---
|
|
617
560
|
|
|
618
|
-
## Data Privacy & Egress
|
|
561
|
+
## 🔒 Data Privacy & Egress
|
|
619
562
|
|
|
620
563
|
**Where is my data stored?**
|
|
621
564
|
|
|
@@ -646,7 +589,7 @@ Prism will recreate the directory with empty databases on next startup.
|
|
|
646
589
|
|
|
647
590
|
---
|
|
648
591
|
|
|
649
|
-
## Use Cases
|
|
592
|
+
## 🎯 Use Cases
|
|
650
593
|
|
|
651
594
|
- **Long-running feature work** — Save state at end of day, restore full context next morning. No re-explaining.
|
|
652
595
|
- **Multi-agent collaboration** — Dev, QA, and PM agents share real-time context without stepping on each other's memory.
|
|
@@ -675,7 +618,7 @@ Then continue a specific thread with a follow-up message to the selected agent,
|
|
|
675
618
|
|
|
676
619
|
---
|
|
677
620
|
|
|
678
|
-
## Adversarial Evaluation in Action
|
|
621
|
+
## ⚔️ Adversarial Evaluation in Action
|
|
679
622
|
|
|
680
623
|
> **Split-Brain Anti-Sycophancy** — the signature feature of v7.4.0.
|
|
681
624
|
|
|
@@ -780,13 +723,11 @@ The Generator strips the `console.log`, resubmits, and the next `EVALUATE` retur
|
|
|
780
723
|
|
|
781
724
|
---
|
|
782
725
|
|
|
783
|
-
## What's New
|
|
726
|
+
## 🆕 What's New
|
|
784
727
|
|
|
785
|
-
> **Current release:
|
|
728
|
+
> **Current release: v7.8.2 — Cognitive Architecture**
|
|
786
729
|
|
|
787
|
-
- 🧠 **
|
|
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)
|
|
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)
|
|
730
|
+
- 🧠 **v7.8.0 — Cognitive Architecture:** The biggest leap forward yet. Moved beyond flat vector search into a true cognitive architecture inspired by human brain mechanics. Episodic-to-Semantic memory consolidation (Hebbian learning), ACT-R Spreading Activation with multi-hop causal reasoning, Uncertainty-Aware Rejection Gate (your agent can say "I don't know"), and Dynamic Fast Weight Decay (semantic memories outlive episodic chatter by 2×). **Your agents don't just remember; they learn.** → [Cognitive Architecture](#-cognitive-architecture-v78)
|
|
790
731
|
- 🌐 **v7.7.0 — Cloud-Native SSE Transport:** Full unauthenticated and authenticated Server-Sent Events MCP support for seamless network deployments.
|
|
791
732
|
- 🩺 **v7.5.0 — Intent Health Dashboard + Security Hardening:** Real-time 0–100 project health scoring (staleness × TODO load × decisions). 10 XSS injection vectors patched. Algorithm hardened with NaN guards and score ceiling.
|
|
792
733
|
- ⚔️ **v7.4.0 — Adversarial Evaluation:** Split-brain anti-sycophancy pipeline. Generator and evaluator in isolated roles with evidence-bound findings.
|
|
@@ -796,7 +737,7 @@ The Generator strips the `console.log`, resubmits, and the next `EVALUATE` retur
|
|
|
796
737
|
|
|
797
738
|
---
|
|
798
739
|
|
|
799
|
-
## How Prism Compares
|
|
740
|
+
## ⚔️ How Prism Compares
|
|
800
741
|
|
|
801
742
|
Standard memory servers (like Mem0, Zep, or the baseline Anthropic MCP) act as passive filing cabinets — they wait for the LLM to search them. **Prism is an active cognitive architecture.** Designed specifically for the **Model Context Protocol (MCP)**, Prism doesn't just store vectors — it consolidates experience into principles, traverses causal graphs for multi-hop reasoning, and rejects queries it can't confidently answer.
|
|
802
743
|
|
|
@@ -848,7 +789,7 @@ Every other AI coding pipeline has a fatal flaw: it asks the same model that wro
|
|
|
848
789
|
|
|
849
790
|
---
|
|
850
791
|
|
|
851
|
-
## Tool Reference
|
|
792
|
+
## 🔧 Tool Reference
|
|
852
793
|
|
|
853
794
|
Prism ships 30+ tools, but **90% of your workflow uses just three:**
|
|
854
795
|
|
|
@@ -1030,11 +971,6 @@ Requires `PRISM_DARK_FACTORY_ENABLED=true`.
|
|
|
1030
971
|
| `PRISM_ACTR_WEIGHT_ACTIVATION` | No | Composite score ACT-R activation weight (default: `0.3`) |
|
|
1031
972
|
| `PRISM_ACTR_ACCESS_LOG_RETENTION_DAYS` | No | Days before access logs are pruned by background scheduler (default: `90`) |
|
|
1032
973
|
| `PRISM_DARK_FACTORY_ENABLED` | No | `"true"` to enable Dark Factory autonomous pipeline tools (`session_start_pipeline`, `session_check_pipeline_status`, `session_abort_pipeline`) |
|
|
1033
|
-
| `PRISM_SYNAPSE_ENABLED` | No | `"true"` (default) to enable Synapse Engine graph propagation in search results |
|
|
1034
|
-
| `PRISM_SYNAPSE_ITERATIONS` | No | Propagation iterations (default: `3`). Higher = deeper graph traversal |
|
|
1035
|
-
| `PRISM_SYNAPSE_SPREAD_FACTOR` | No | Energy decay multiplier per hop (default: `0.8`). Range: 0.0–1.0 |
|
|
1036
|
-
| `PRISM_SYNAPSE_LATERAL_INHIBITION` | No | Max nodes returned by Synapse (default: `7`, min: `1`) |
|
|
1037
|
-
| `PRISM_SYNAPSE_SOFT_CAP` | No | Max candidate pool size during propagation (default: `20`, min: `1`) |
|
|
1038
974
|
|
|
1039
975
|
</details>
|
|
1040
976
|
|
|
@@ -1062,11 +998,10 @@ Prism is a **stdio-based MCP server** that manages persistent agent memory. Here
|
|
|
1062
998
|
│ └──────┬───────┘ └──────────────┘ └────────────────┘ │
|
|
1063
999
|
│ ↕ │
|
|
1064
1000
|
│ ┌────────────────────────────────────────────────────┐ │
|
|
1065
|
-
│ │ Cognitive Engine (
|
|
1066
|
-
│ │ •
|
|
1001
|
+
│ │ Cognitive Engine (v7.8) │ │
|
|
1002
|
+
│ │ • ACT-R Spreading Activation (multi-hop) │ │
|
|
1067
1003
|
│ │ • Episodic → Semantic Consolidation (Hebbian) │ │
|
|
1068
1004
|
│ │ • Uncertainty-Aware Rejection Gate │ │
|
|
1069
|
-
│ │ • LoCoMo-Plus Benchmark Validation │ │
|
|
1070
1005
|
│ │ • Dynamic Fast Weight Decay (dual-rate) │ │
|
|
1071
1006
|
│ │ • HDC Cognitive Routing (XOR binding) │ │
|
|
1072
1007
|
│ └──────┬─────────────────────────────────────────────┘ │
|
|
@@ -1110,7 +1045,7 @@ Prism is a **stdio-based MCP server** that manages persistent agent memory. Here
|
|
|
1110
1045
|
|
|
1111
1046
|
### Auto-Load Architecture
|
|
1112
1047
|
|
|
1113
|
-
Each MCP client has its own mechanism for ensuring Prism context loads on session start. See the platform-specific [Setup Guides](
|
|
1048
|
+
Each MCP client has its own mechanism for ensuring Prism context loads on session start. See the platform-specific [Setup Guides](#-setup-guides) above for detailed instructions:
|
|
1114
1049
|
|
|
1115
1050
|
- **Claude Code** — Lifecycle hooks (`SessionStart` / `Stop`)
|
|
1116
1051
|
- **Gemini / Antigravity** — Three-layer architecture (User Rules + AGENTS.md + Startup Skill)
|
|
@@ -1121,7 +1056,7 @@ All platforms benefit from the **server-side fallback** (v5.2.1): if `session_lo
|
|
|
1121
1056
|
|
|
1122
1057
|
---
|
|
1123
1058
|
|
|
1124
|
-
## Scientific Foundation
|
|
1059
|
+
## 🧬 Scientific Foundation
|
|
1125
1060
|
|
|
1126
1061
|
Prism has evolved from smart session logging into a **cognitive memory architecture** — grounded in real research, not marketing. Every retrieval decision is backed by peer-reviewed models from cognitive psychology, neuroscience, and distributed computing.
|
|
1127
1062
|
|
|
@@ -1155,25 +1090,19 @@ Prism has evolved from smart session logging into a **cognitive memory architect
|
|
|
1155
1090
|
| **v7.8** | Multi-Hop Causal Reasoning — spreading activation traverses `caused_by`/`led_to` edges with damped fan effect (`1/ln(fan+e)`) and lateral inhibition | ACT-R spreading activation (Anderson), Collins & Loftus (1975) | ✅ Shipped |
|
|
1156
1091
|
| **v7.8** | Uncertainty-Aware Rejection Gate — dual-signal (similarity floor + gap distance) safety layer prevents hallucination from low-confidence retrievals | Metacognition research, uncertainty quantification | ✅ Shipped |
|
|
1157
1092
|
| **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 |
|
|
1158
|
-
| **v7.
|
|
1159
|
-
| **
|
|
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 |
|
|
1093
|
+
| **v7.x** | Affect-Tagged Memory — sentiment shapes what gets recalled | Affect-modulated retrieval (neuroscience) | 🔭 Horizon |
|
|
1094
|
+
| **v8+** | Zero-Search Retrieval — no index, no ANN, just ask the vector | Holographic Reduced Representations | 🔭 Horizon |
|
|
1164
1095
|
|
|
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,
|
|
1096
|
+
> 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, and LeCun's "Why AI Systems Don't Learn" (Dupoux, LeCun, Malik).
|
|
1166
1097
|
|
|
1167
1098
|
---
|
|
1168
1099
|
|
|
1169
|
-
## Milestones & Roadmap
|
|
1100
|
+
## 📦 Milestones & Roadmap
|
|
1170
1101
|
|
|
1171
|
-
> **Current:
|
|
1102
|
+
> **Current: v7.8.2** — Cognitive Architecture ([CHANGELOG](CHANGELOG.md))
|
|
1172
1103
|
|
|
1173
1104
|
| Release | Headline |
|
|
1174
1105
|
|---------|----------|
|
|
1175
|
-
| **v9.0** | 🧠 Autonomous Cognitive OS — Affect-Tagged Memory (valence engine), Token-Economic Cognitive Budget, Surprisal Gate |
|
|
1176
|
-
| **v8.0** | ⚡ Synapse Engine — Pure multi-hop GraphRAG propagation, storage-agnostic, NaN-hardened, `[🌐 Synapse]` discovery tags |
|
|
1177
1106
|
| **v7.8** | 🧠 Cognitive Architecture — Hebbian consolidation, multi-hop reasoning, rejection gate, dynamic decay |
|
|
1178
1107
|
| **v7.7** | 🌐 Cloud-Native SSE Transport |
|
|
1179
1108
|
| **v7.5** | 🩺 Intent Health Dashboard + Security Hardening |
|
|
@@ -1186,14 +1115,13 @@ Prism has evolved from smart session logging into a **cognitive memory architect
|
|
|
1186
1115
|
| **v6.2** | 🧩 Synthesize & Prune |
|
|
1187
1116
|
|
|
1188
1117
|
### Future Tracks
|
|
1189
|
-
- **
|
|
1190
|
-
- **
|
|
1191
|
-
- **v10+: Zero-Search Retrieval** — Direct vector-addressed recall via Holographic Reduced Representations.
|
|
1118
|
+
- **v7.x: Affect-Tagged Memory** — Recall prioritization improves by weighting memories with affective/contextual valence.
|
|
1119
|
+
- **v8+: Zero-Search Retrieval** — Direct vector-addressed recall reduces retrieval indirection.
|
|
1192
1120
|
|
|
1193
1121
|
👉 **[Full ROADMAP.md →](ROADMAP.md)**
|
|
1194
1122
|
|
|
1195
1123
|
|
|
1196
|
-
## Troubleshooting FAQ
|
|
1124
|
+
## ❓ Troubleshooting FAQ
|
|
1197
1125
|
|
|
1198
1126
|
**Q: Why is the dashboard project selector stuck on "Loading projects..."?**
|
|
1199
1127
|
A: Fixed in v7.3.3. The root cause was a multi-layer quote-escaping trap in the `abortPipeline` onclick handler that generated a `SyntaxError` in the browser, silently killing the entire dashboard IIFE. Update to v7.3.3+ (`npx -y prism-mcp-server`). If still stuck, check that Supabase env values are properly set (unresolved placeholders like `${SUPABASE_URL}` cause `/api/projects` to return empty). Prism auto-falls back to local SQLite when Supabase is misconfigured.
|
|
@@ -1225,33 +1153,10 @@ A: Run `npm run build && npm test`, then open the Mind Palace dashboard (`localh
|
|
|
1225
1153
|
|
|
1226
1154
|
---
|
|
1227
1155
|
|
|
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
|
-
|
|
1251
1156
|
## License
|
|
1252
1157
|
|
|
1253
1158
|
MIT
|
|
1254
1159
|
|
|
1255
1160
|
---
|
|
1256
1161
|
|
|
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
|
|
1162
|
+
<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>
|
package/dist/config.js
CHANGED
|
@@ -78,10 +78,7 @@ 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
|
-
|
|
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";
|
|
81
|
+
export const PRISM_STORAGE = process.env.PRISM_STORAGE || "supabase";
|
|
85
82
|
// Logged at debug level — see debug() at bottom of file
|
|
86
83
|
// ─── Optional: Supabase (Session Memory Module) ───────────────
|
|
87
84
|
// When both SUPABASE_URL and SUPABASE_KEY are set, session memory tools
|
|
@@ -139,22 +136,8 @@ export const PRISM_DEBUG_LOGGING = process.env.PRISM_DEBUG_LOGGING === "true";
|
|
|
139
136
|
// The role parameter on existing tools (session_save_ledger, etc.)
|
|
140
137
|
// is always available regardless of this flag — adding a parameter
|
|
141
138
|
// doesn't increase tool count.
|
|
142
|
-
//
|
|
143
|
-
|
|
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.
|
|
139
|
+
// Set PRISM_ENABLE_HIVEMIND=true to unlock the Agent Registry tools.
|
|
140
|
+
export const PRISM_ENABLE_HIVEMIND = process.env.PRISM_ENABLE_HIVEMIND === "true";
|
|
158
141
|
// ─── v4.1: Auto-Load Projects ────────────────────────────────
|
|
159
142
|
// Auto-load is configured exclusively via the Mind Palace dashboard
|
|
160
143
|
// ("Auto-Load Projects" checkboxes in Settings). The setting is stored
|
|
@@ -279,43 +262,9 @@ export const PRISM_VERIFICATION_DEFAULT_SEVERITY = (process.env.PRISM_VERIFICATI
|
|
|
279
262
|
// ─── v7.3: Dark Factory Orchestration ─────────────────────────
|
|
280
263
|
// Autonomous pipeline runner: PLAN → EXECUTE → VERIFY → iterate.
|
|
281
264
|
// Opt-in because it executes LLM calls in the background.
|
|
282
|
-
/** Master switch for the Dark Factory background runner.
|
|
283
|
-
|
|
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
|
|
265
|
+
/** Master switch for the Dark Factory background runner. */
|
|
266
|
+
export const PRISM_DARK_FACTORY_ENABLED = process.env.PRISM_DARK_FACTORY_ENABLED === "true"; // Opt-in
|
|
286
267
|
/** Poll interval for the runner loop (ms). Default: 30s. */
|
|
287
268
|
export const PRISM_DARK_FACTORY_POLL_MS = parseInt(process.env.PRISM_DARK_FACTORY_POLL_MS || "30000", 10);
|
|
288
269
|
/** Default max wall-clock time per pipeline (ms). Default: 15 minutes. */
|
|
289
270
|
export const PRISM_DARK_FACTORY_MAX_RUNTIME_MS = parseInt(process.env.PRISM_DARK_FACTORY_MAX_RUNTIME_MS || "900000", 10);
|
|
290
|
-
// ─── v8.0: Synapse — Spreading Activation Engine ──────────────
|
|
291
|
-
// Multi-hop energy propagation through memory_links graph.
|
|
292
|
-
// Enabled by default. Set PRISM_SYNAPSE_ENABLED=false to fall back
|
|
293
|
-
// to 1-hop candidateScopedSpreadingActivation (v7.0 behavior).
|
|
294
|
-
/** Master switch for the Synapse engine. Enabled by default (opt-out). */
|
|
295
|
-
export const PRISM_SYNAPSE_ENABLED = (process.env.PRISM_SYNAPSE_ENABLED ?? "true") !== "false";
|
|
296
|
-
/** Number of propagation iterations (depth). Higher = deeper traversal, more latency. (Default: 3) */
|
|
297
|
-
export const PRISM_SYNAPSE_ITERATIONS = parseInt(process.env.PRISM_SYNAPSE_ITERATIONS || "3", 10);
|
|
298
|
-
/** Energy attenuation per hop. Must be < 1.0 for convergence. (Default: 0.8) */
|
|
299
|
-
export const PRISM_SYNAPSE_SPREAD_FACTOR = parseFloat(process.env.PRISM_SYNAPSE_SPREAD_FACTOR || "0.8");
|
|
300
|
-
/** Hard cap on final output nodes (lateral inhibition). (Default: 7) */
|
|
301
|
-
export const PRISM_SYNAPSE_LATERAL_INHIBITION = parseInt(process.env.PRISM_SYNAPSE_LATERAL_INHIBITION || "7", 10);
|
|
302
|
-
/** Soft cap on active nodes per iteration (prevents explosion). (Default: 20) */
|
|
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";
|
|
@@ -599,13 +599,6 @@ async function runnerTick() {
|
|
|
599
599
|
const harnessPath = path.join(path.resolve(spec.workingDirectory), 'verification_harness.json');
|
|
600
600
|
if (fs.existsSync(harnessPath)) {
|
|
601
601
|
try {
|
|
602
|
-
// MED-5 FIX: Guard against LLM-generated files that are malformed or
|
|
603
|
-
// excessively large. Cap at 1MB to prevent heap exhaustion.
|
|
604
|
-
const MAX_HARNESS_SIZE = 1_000_000;
|
|
605
|
-
const stat = fs.statSync(harnessPath);
|
|
606
|
-
if (stat.size > MAX_HARNESS_SIZE) {
|
|
607
|
-
throw new Error(`Verification harness too large (${stat.size} bytes, max ${MAX_HARNESS_SIZE}). Possible corrupt LLM output.`);
|
|
608
|
-
}
|
|
609
602
|
const rawHarness = fs.readFileSync(harnessPath, 'utf8');
|
|
610
603
|
const harnessData = JSON.parse(rawHarness);
|
|
611
604
|
// GAP-5 fix: Persist the harness so CLI drift detection works for DarkFactory runs
|
|
@@ -45,16 +45,8 @@ export class SafetyController {
|
|
|
45
45
|
if (!spec.workingDirectory)
|
|
46
46
|
return true;
|
|
47
47
|
// Resolve symlinks and protect against ../ escapes.
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
// EDGE-2 FIX: macOS (HFS+/APFS) and Windows (NTFS) use case-insensitive
|
|
51
|
-
// filesystems by default. Without case normalization, "/App/Workspace"
|
|
52
|
-
// and "/app/workspace" are treated as different paths — allowing a scope
|
|
53
|
-
// escape via case mismatch.
|
|
54
|
-
if (process.platform === 'darwin' || process.platform === 'win32') {
|
|
55
|
-
resolvedTarget = resolvedTarget.toLowerCase();
|
|
56
|
-
resolvedWorkspace = resolvedWorkspace.toLowerCase();
|
|
57
|
-
}
|
|
48
|
+
const resolvedTarget = path.resolve(targetPath);
|
|
49
|
+
const resolvedWorkspace = path.resolve(spec.workingDirectory);
|
|
58
50
|
// Path Traversal Guard: A naive startsWith() check is vulnerable to
|
|
59
51
|
// prefix collisions — e.g. /app/workspace-hacked passes startsWith('/app/workspace').
|
|
60
52
|
// We require EITHER exact match OR the target starts with workspace + path separator.
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Dashboard authentication helpers extracted from server.ts for direct unit testing.
|
|
3
3
|
*/
|
|
4
4
|
import { randomBytes } from "crypto";
|
|
5
|
+
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
5
6
|
// ─────────────────────────────────────────────────────────────────
|
|
6
7
|
// TIMING-SAFE COMPARISON
|
|
7
8
|
// ─────────────────────────────────────────────────────────────────
|
|
@@ -34,6 +35,18 @@ export function generateToken() {
|
|
|
34
35
|
return randomBytes(32).toString("hex");
|
|
35
36
|
}
|
|
36
37
|
// ─────────────────────────────────────────────────────────────────
|
|
38
|
+
// JWKS SETUP
|
|
39
|
+
// ─────────────────────────────────────────────────────────────────
|
|
40
|
+
let jwksCache = null;
|
|
41
|
+
export function initJWKS(uri) {
|
|
42
|
+
try {
|
|
43
|
+
jwksCache = createRemoteJWKSet(new URL(uri));
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
console.error(`Failed to initialize JWKS from ${uri}:`, err);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
// ─────────────────────────────────────────────────────────────────
|
|
37
50
|
// AUTHENTICATION CHECK
|
|
38
51
|
// ─────────────────────────────────────────────────────────────────
|
|
39
52
|
/**
|
|
@@ -47,9 +60,25 @@ export function generateToken() {
|
|
|
47
60
|
* Side effect: expired session tokens are lazily cleaned up when
|
|
48
61
|
* encountered, preventing unbounded memory growth.
|
|
49
62
|
*/
|
|
50
|
-
export function isAuthenticated(req, config) {
|
|
63
|
+
export async function isAuthenticated(req, config) {
|
|
51
64
|
if (!config.authEnabled)
|
|
52
65
|
return true;
|
|
66
|
+
// Check Bearer Token (JWKS)
|
|
67
|
+
const authHeader = req.headers.authorization || "";
|
|
68
|
+
if (authHeader.startsWith("Bearer ") && jwksCache) {
|
|
69
|
+
try {
|
|
70
|
+
const token = authHeader.slice(7);
|
|
71
|
+
const { payload } = await jwtVerify(token, jwksCache);
|
|
72
|
+
// Attach agent_id to the request for traceability if needed downstream
|
|
73
|
+
req.agent_id = payload.agent_id || payload.sub;
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
catch (err) {
|
|
77
|
+
// Verification failed — let it fall through or return false
|
|
78
|
+
// console.error("JWT verification failed:", err);
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
53
82
|
// Check session cookie first
|
|
54
83
|
const cookies = req.headers.cookie || "";
|
|
55
84
|
const match = cookies.match(/prism_session=([a-f0-9]{64})/);
|
|
@@ -63,7 +92,6 @@ export function isAuthenticated(req, config) {
|
|
|
63
92
|
config.activeSessions.delete(token);
|
|
64
93
|
}
|
|
65
94
|
// Check Basic Auth header
|
|
66
|
-
const authHeader = req.headers.authorization || "";
|
|
67
95
|
if (authHeader.startsWith("Basic ")) {
|
|
68
96
|
try {
|
|
69
97
|
const decoded = Buffer.from(authHeader.slice(6), "base64").toString("utf-8");
|