@maximalabs/dev-mcp-suite 0.0.0-stage → 3.6.0
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/.env.example +69 -0
- package/CHANGELOG.md +271 -0
- package/CODEX_DEV_MCP_GUIDE.md +297 -0
- package/LICENSE +21 -0
- package/README.md +193 -2
- package/armada/package.json +14 -0
- package/armada/server.js +329 -0
- package/backfill-sessions-v2.mjs +288 -0
- package/bin/_meta.mjs +73 -0
- package/bin/armada-mcp.mjs +12 -0
- package/bin/checkpoint.mjs +9 -0
- package/bin/context-pack.mjs +9 -0
- package/bin/devjournal.mjs +9 -0
- package/bin/init.mjs +25 -0
- package/bin/project-memory.mjs +10 -0
- package/bin/provider-smoke.mjs +278 -0
- package/bin/prune.mjs +158 -0
- package/bin/stats.mjs +101 -0
- package/bin/ui.mjs +5 -0
- package/checkpoint/package.json +14 -0
- package/checkpoint/server.js +318 -0
- package/context-pack/package.json +14 -0
- package/context-pack/server.js +747 -0
- package/devjournal/compress.js +75 -0
- package/devjournal/env.js +3 -0
- package/devjournal/package.json +14 -0
- package/devjournal/provider-chain.js +109 -0
- package/devjournal/rerank.js +120 -0
- package/devjournal/server.js +415 -0
- package/docs/ROADMAP.md +77 -0
- package/docs/clients/antigravity.md +52 -0
- package/docs/clients/claude-code.md +46 -0
- package/docs/clients/codex.md +39 -0
- package/docs/clients/generic-mcp.md +45 -0
- package/docs/clients/hermes.md +48 -0
- package/docs/configuration.md +123 -0
- package/docs/privacy.md +39 -0
- package/docs/providers.md +13 -0
- package/docs/superpowers/plans/2026-06-15-hardening-v1-2-implementation.md +60 -0
- package/docs/superpowers/plans/2026-06-15-provider-chain-v1-1-implementation.md +65 -0
- package/docs/superpowers/plans/2026-06-15-provider-client-agnostic-config.md +41 -0
- package/docs/superpowers/plans/2026-06-15-trust-release-implementation.md +62 -0
- package/docs/superpowers/plans/2026-06-18-v1-5-0-knowledge-graph.md +792 -0
- package/docs/superpowers/specs/2026-06-15-provider-chain-v1-1-design.md +89 -0
- package/docs/superpowers/specs/2026-06-15-trust-release-design.md +164 -0
- package/docs/superpowers/specs/2026-06-18-dev-mcp-suite-v1-5-0-knowledge-graph-design.md +386 -0
- package/docs/superpowers/specs/2026-07-22-v2-0-0-peak-intelligence.md +50 -0
- package/docs/superpowers/specs/2026-07-22-v3-0-0-god-tier.md +32 -0
- package/lib/init-wizard.js +120 -0
- package/lib/provider-smoke.js +234 -0
- package/lib/prune.js +114 -0
- package/lib/stats.js +269 -0
- package/lib/ui-server.js +151 -0
- package/lib/update-check.js +125 -0
- package/package.json +71 -4
- package/project-memory/auto-indexer.js +152 -0
- package/project-memory/dedup.js +49 -0
- package/project-memory/embedding.js +174 -0
- package/project-memory/env.js +3 -0
- package/project-memory/global-index.js +46 -0
- package/project-memory/graph.js +93 -0
- package/project-memory/local-embed.js +92 -0
- package/project-memory/package.json +14 -0
- package/project-memory/provider-chain.js +109 -0
- package/project-memory/rerank.js +120 -0
- package/project-memory/server.js +931 -0
- package/project-memory/swarm.js +56 -0
- package/run-tests.mjs +54 -0
|
@@ -0,0 +1,931 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Project Memory MCP Server for Codex
|
|
5
|
+
*
|
|
6
|
+
* Idea: Obsidian-style local Markdown vault + Context7-style on-demand recall.
|
|
7
|
+
* Persists per-directory notes/activity to .md files (with YAML frontmatter)
|
|
8
|
+
* and maintains a keyword index so a fresh session can pull back only the
|
|
9
|
+
* relevant context instead of re-pasting everything.
|
|
10
|
+
*
|
|
11
|
+
* Vault layout (default ~/.codex/memories/vault):
|
|
12
|
+
* <project-slug>/
|
|
13
|
+
* notes/<id>.md # one note per file, plain Markdown + frontmatter
|
|
14
|
+
* index.json # keyword + metadata index for fast recall
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
18
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
19
|
+
import {
|
|
20
|
+
CallToolRequestSchema,
|
|
21
|
+
ListToolsRequestSchema,
|
|
22
|
+
ListResourcesRequestSchema,
|
|
23
|
+
ListResourceTemplatesRequestSchema,
|
|
24
|
+
ReadResourceRequestSchema,
|
|
25
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
26
|
+
import fs from "fs/promises";
|
|
27
|
+
import path from "path";
|
|
28
|
+
import os from "os";
|
|
29
|
+
import crypto from "crypto";
|
|
30
|
+
import { fileURLToPath } from "url";
|
|
31
|
+
import { embed, embedOne, cosine, embeddingConfig } from "./embedding.js";
|
|
32
|
+
import { rerank, rerankConfig } from "./rerank.js";
|
|
33
|
+
import { deterministicEnabled } from "./env.js";
|
|
34
|
+
import { ensureGraphState, resolveLink, loadNoteBody } from "./graph.js";
|
|
35
|
+
import { loadGlobalNotes } from "./global-index.js";
|
|
36
|
+
import { findDuplicateCandidates } from "./dedup.js";
|
|
37
|
+
import { computeStats, formatText, formatJson } from "../lib/stats.js";
|
|
38
|
+
import { broadcastSwarmEvent, getSwarmTimeline } from "./swarm.js";
|
|
39
|
+
import { runAutoIndexer } from "./auto-indexer.js";
|
|
40
|
+
|
|
41
|
+
const VAULT_ROOT =
|
|
42
|
+
process.env.MEMORY_VAULT_DIR ||
|
|
43
|
+
path.join(os.homedir(), ".ai-shared-memory", "vault");
|
|
44
|
+
|
|
45
|
+
const MAX_CONTENT = 200_000;
|
|
46
|
+
const MAX_TITLE = 200;
|
|
47
|
+
const STOPWORDS = new Set([
|
|
48
|
+
"the", "a", "an", "and", "or", "but", "if", "then", "else", "for", "to",
|
|
49
|
+
"of", "in", "on", "at", "by", "is", "are", "was", "were", "be", "this",
|
|
50
|
+
"that", "it", "as", "with", "from", "we", "i", "you", "he", "she", "they",
|
|
51
|
+
"not", "no", "do", "did", "does", "can", "will", "so", "my", "our", "your",
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
export function projectSlug(dir) {
|
|
55
|
+
const resolved = path.resolve(dir || process.cwd());
|
|
56
|
+
const base = path.basename(resolved) || "root";
|
|
57
|
+
const hash = crypto.createHash("sha1").update(resolved).digest("hex").slice(0, 8);
|
|
58
|
+
const safeBase = base.replace(/[^a-zA-Z0-9._-]/g, "-").slice(0, 40);
|
|
59
|
+
return `${safeBase}-${hash}`;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function tokenize(text) {
|
|
63
|
+
return (String(text || "").toLowerCase().match(/[a-z0-9_./-]{2,}/g) || [])
|
|
64
|
+
.filter((w) => !STOPWORDS.has(w));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function nowIso() {
|
|
68
|
+
return new Date().toISOString();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function genId() {
|
|
72
|
+
return (
|
|
73
|
+
new Date().toISOString().replace(/[:.]/g, "").slice(0, 15) +
|
|
74
|
+
"-" +
|
|
75
|
+
crypto.randomBytes(3).toString("hex")
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function limit(value, name, max, required = true) {
|
|
80
|
+
const text = String(value ?? "");
|
|
81
|
+
if (required && !text.trim()) throw new Error(`${name} is required`);
|
|
82
|
+
if (text.length > max) throw new Error(`${name} exceeds ${max} characters`);
|
|
83
|
+
return text;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function parseFrontmatter(raw) {
|
|
87
|
+
const m = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
|
|
88
|
+
if (!m) return { meta: {}, body: raw };
|
|
89
|
+
const meta = {};
|
|
90
|
+
for (const line of m[1].split("\n")) {
|
|
91
|
+
const idx = line.indexOf(":");
|
|
92
|
+
if (idx === -1) continue;
|
|
93
|
+
const key = line.slice(0, idx).trim();
|
|
94
|
+
let val = line.slice(idx + 1).trim();
|
|
95
|
+
if (val.startsWith("[") && val.endsWith("]")) {
|
|
96
|
+
val = val.slice(1, -1).split(",").map((s) => s.trim().replace(/^["']|["']$/g, "")).filter(Boolean);
|
|
97
|
+
} else {
|
|
98
|
+
val = val.replace(/^["']|["']$/g, "");
|
|
99
|
+
}
|
|
100
|
+
meta[key] = val;
|
|
101
|
+
}
|
|
102
|
+
return { meta, body: m[2] };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function buildFrontmatter(meta) {
|
|
106
|
+
const lines = ["---"];
|
|
107
|
+
for (const [k, v] of Object.entries(meta)) {
|
|
108
|
+
if (Array.isArray(v)) lines.push(`${k}: [${v.map((x) => JSON.stringify(x)).join(", ")}]`);
|
|
109
|
+
else lines.push(`${k}: ${JSON.stringify(v)}`);
|
|
110
|
+
}
|
|
111
|
+
lines.push("---", "");
|
|
112
|
+
return lines.join("\n");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function graphBoost(note, queryTokens) {
|
|
116
|
+
let score = 0;
|
|
117
|
+
for (const link of note.links || []) {
|
|
118
|
+
for (const token of queryTokens) {
|
|
119
|
+
if (String(link.ref || "").toLowerCase().includes(token)) score += 0.05;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return Math.min(0.15, score);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
class ProjectMemoryServer {
|
|
126
|
+
constructor() {
|
|
127
|
+
this.server = new Server(
|
|
128
|
+
{ name: "project-memory", version: "1.0.0" },
|
|
129
|
+
{ capabilities: { tools: {}, resources: {} } }
|
|
130
|
+
);
|
|
131
|
+
this.setupHandlers();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
paths(dir) {
|
|
135
|
+
const slug = projectSlug(dir);
|
|
136
|
+
const projectDir = path.join(VAULT_ROOT, slug);
|
|
137
|
+
return {
|
|
138
|
+
slug,
|
|
139
|
+
projectDir,
|
|
140
|
+
notesDir: path.join(projectDir, "notes"),
|
|
141
|
+
indexFile: path.join(projectDir, "index.json"),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async loadIndex(p) {
|
|
146
|
+
try {
|
|
147
|
+
const raw = await fs.readFile(p.indexFile, "utf8");
|
|
148
|
+
return JSON.parse(raw);
|
|
149
|
+
} catch {
|
|
150
|
+
return { project: p.slug, updated: nowIso(), notes: {} };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async saveIndex(p, index) {
|
|
155
|
+
index.updated = nowIso();
|
|
156
|
+
await fs.mkdir(p.projectDir, { recursive: true });
|
|
157
|
+
await fs.writeFile(p.indexFile, JSON.stringify(index, null, 2));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Ensure an Obsidian-friendly workspace exists so the vault can be opened
|
|
161
|
+
// directly in the Obsidian app (graph view, tag pages, MOC navigation).
|
|
162
|
+
async ensureObsidianFolder(p) {
|
|
163
|
+
const obsDir = path.join(p.projectDir, ".obsidian");
|
|
164
|
+
try { await fs.access(obsDir); return; } catch {}
|
|
165
|
+
await fs.mkdir(obsDir, { recursive: true });
|
|
166
|
+
await fs.writeFile(path.join(obsDir, "app.json"), JSON.stringify({
|
|
167
|
+
alwaysUpdateLinks: true,
|
|
168
|
+
newLinkFormat: "shortest",
|
|
169
|
+
useMarkdownLinks: false,
|
|
170
|
+
showViewHeader: true,
|
|
171
|
+
}, null, 2));
|
|
172
|
+
await fs.writeFile(path.join(obsDir, "workspace.json"), JSON.stringify({
|
|
173
|
+
_comment: "Auto-managed by @maximalabs/dev-mcp-suite (project-memory).",
|
|
174
|
+
}, null, 2));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Build an Obsidian-style Map of Content (MOC) listing every note, its
|
|
178
|
+
// outgoing links, backlinks, and a #tag index. Refreshed on save/delete.
|
|
179
|
+
async writeMoc(p, index) {
|
|
180
|
+
const notes = Object.values(index.notes || {})
|
|
181
|
+
.sort((a, b) => (a.created < b.created ? 1 : -1));
|
|
182
|
+
if (notes.length === 0) return;
|
|
183
|
+
const tagMap = new Map();
|
|
184
|
+
for (const n of notes) {
|
|
185
|
+
for (const t of n.tags || []) {
|
|
186
|
+
if (!tagMap.has(t)) tagMap.set(t, []);
|
|
187
|
+
tagMap.get(t).push(n);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const lines = [
|
|
191
|
+
"# MOC — Map of Content",
|
|
192
|
+
"",
|
|
193
|
+
`> Auto-generated by project-memory for project \`${p.slug}\`. Do not edit by hand; it is regenerated on every save/delete.`,
|
|
194
|
+
"",
|
|
195
|
+
`**${notes.length} notes**`,
|
|
196
|
+
"",
|
|
197
|
+
"## Notes",
|
|
198
|
+
];
|
|
199
|
+
for (const n of notes) {
|
|
200
|
+
const link = `[[${n.title}]]`;
|
|
201
|
+
const tags = (n.tags || []).length ? ` #${(n.tags || []).join(" #")}` : "";
|
|
202
|
+
lines.push(`- ${link} — *${n.kind || "note"}*${tags}`);
|
|
203
|
+
}
|
|
204
|
+
lines.push("", "## By tag");
|
|
205
|
+
if (tagMap.size === 0) lines.push("- (no tags yet)");
|
|
206
|
+
for (const [tag, ns] of [...tagMap.entries()].sort()) {
|
|
207
|
+
lines.push(`- #${tag}: ${ns.map((n) => `[[${n.title}]]`).join(", ")}`);
|
|
208
|
+
}
|
|
209
|
+
lines.push("", "## Graph (backlinks)");
|
|
210
|
+
for (const n of notes) {
|
|
211
|
+
const bl = (n.backlinks || []).map((b) => `[[${b.title}]]`).join(", ");
|
|
212
|
+
if (bl) lines.push(`- [[${n.title}]] <- ${bl}`);
|
|
213
|
+
}
|
|
214
|
+
lines.push("");
|
|
215
|
+
await fs.writeFile(path.join(p.projectDir, "MOC.md"), lines.join("\n"));
|
|
216
|
+
// Also emit a standalone #tag index page per tag (Obsidian-style tag pages).
|
|
217
|
+
await this.writeTagPages(p, tagMap);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Emit one `tags/<tag>.md` page per tag, listing all notes carrying it.
|
|
221
|
+
async writeTagPages(p, tagMap) {
|
|
222
|
+
const tagDir = path.join(p.projectDir, "tags");
|
|
223
|
+
await fs.mkdir(tagDir, { recursive: true });
|
|
224
|
+
for (const [tag, ns] of tagMap.entries()) {
|
|
225
|
+
const body = [
|
|
226
|
+
`# Tag: ${tag}`,
|
|
227
|
+
"",
|
|
228
|
+
ns.map((n) => `- [[${n.title}]] — *${n.kind || "note"}*`).join("\n"),
|
|
229
|
+
"",
|
|
230
|
+
].join("\n");
|
|
231
|
+
await fs.writeFile(path.join(tagDir, `${String(tag).replace(/[^a-zA-Z0-9._-]/g, "-")}.md`), body);
|
|
232
|
+
}
|
|
233
|
+
// prune tag pages with no notes left
|
|
234
|
+
let files = [];
|
|
235
|
+
try { files = await fs.readdir(tagDir); } catch { return; }
|
|
236
|
+
for (const f of files) {
|
|
237
|
+
if (!f.endsWith(".md")) continue;
|
|
238
|
+
const t = f.slice(0, -3);
|
|
239
|
+
if (!tagMap.has(t)) await fs.unlink(path.join(tagDir, f)).catch(() => {});
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// Export the note graph (nodes + directed edges) for external graph views.
|
|
244
|
+
buildGraph(index) {
|
|
245
|
+
const nodes = Object.values(index.notes || {}).map((n) => ({
|
|
246
|
+
id: n.id, title: n.title, kind: n.kind || "note", tags: n.tags || [],
|
|
247
|
+
}));
|
|
248
|
+
const edges = [];
|
|
249
|
+
for (const n of Object.values(index.notes || {})) {
|
|
250
|
+
for (const link of n.links || []) {
|
|
251
|
+
edges.push({ from: n.id, raw: link.raw, ref: link.ref, kind: link.kind });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return { nodes, edges };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
setupHandlers() {
|
|
258
|
+
this.server.setRequestHandler(ListToolsRequestSchema, () => ({
|
|
259
|
+
tools: [
|
|
260
|
+
{
|
|
261
|
+
name: "memory_save",
|
|
262
|
+
description:
|
|
263
|
+
"Save a note/decision/activity to the project's Markdown vault and index it for later recall. Use after meaningful work so a fresh session can recover context.",
|
|
264
|
+
inputSchema: {
|
|
265
|
+
type: "object",
|
|
266
|
+
properties: {
|
|
267
|
+
title: { type: "string", description: "Short title/summary" },
|
|
268
|
+
content: { type: "string", description: "Markdown body: details, decisions, code refs" },
|
|
269
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
270
|
+
tags: { type: "array", items: { type: "string" }, description: "Optional tags" },
|
|
271
|
+
kind: { type: "string", description: "note | decision | task | log | snippet", default: "note" },
|
|
272
|
+
aliases: { type: "array", items: { type: "string" }, description: "Optional Obsidian-style aliases for the note (alt titles wikilinks can reference)" },
|
|
273
|
+
created: { type: "string", description: "Optional ISO timestamp to backdate the note (e.g. original session time)" },
|
|
274
|
+
},
|
|
275
|
+
required: ["title", "content"],
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
{
|
|
279
|
+
name: "memory_recall",
|
|
280
|
+
description:
|
|
281
|
+
"Retrieve the most relevant saved notes for a query. Falls back gracefully: semantic -> keyword -> LLM rerank. Set mode to control behavior: 'auto' (default), 'semantic' (require embedding), 'keyword' (skip embedding).",
|
|
282
|
+
inputSchema: {
|
|
283
|
+
type: "object",
|
|
284
|
+
properties: {
|
|
285
|
+
query: { type: "string", description: "What you need context about" },
|
|
286
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
287
|
+
limit: { type: "number", description: "Max notes to return", default: 5 },
|
|
288
|
+
full: { type: "boolean", description: "Return full bodies instead of excerpts", default: false },
|
|
289
|
+
mode: { type: "string", enum: ["auto", "semantic", "keyword"], default: "auto", description: "Retrieval mode: 'auto' (default, smart fallback), 'semantic' (require embedding), 'keyword' (skip embedding)" },
|
|
290
|
+
},
|
|
291
|
+
required: ["query"],
|
|
292
|
+
},
|
|
293
|
+
},
|
|
294
|
+
{
|
|
295
|
+
name: "memory_list",
|
|
296
|
+
description: "List saved notes for a project (newest first) with id, title, tags, timestamp.",
|
|
297
|
+
inputSchema: {
|
|
298
|
+
type: "object",
|
|
299
|
+
properties: {
|
|
300
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
301
|
+
limit: { type: "number", description: "Max notes", default: 20 },
|
|
302
|
+
},
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
{
|
|
306
|
+
name: "memory_get",
|
|
307
|
+
description: "Fetch the full Markdown content of a single note by id.",
|
|
308
|
+
inputSchema: {
|
|
309
|
+
type: "object",
|
|
310
|
+
properties: {
|
|
311
|
+
id: { type: "string", description: "Note id" },
|
|
312
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
313
|
+
},
|
|
314
|
+
required: ["id"],
|
|
315
|
+
},
|
|
316
|
+
},
|
|
317
|
+
{
|
|
318
|
+
name: "memory_delete",
|
|
319
|
+
description: "Delete a note by id from the vault and index.",
|
|
320
|
+
inputSchema: {
|
|
321
|
+
type: "object",
|
|
322
|
+
properties: {
|
|
323
|
+
id: { type: "string", description: "Note id" },
|
|
324
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
325
|
+
},
|
|
326
|
+
required: ["id"],
|
|
327
|
+
},
|
|
328
|
+
},
|
|
329
|
+
{
|
|
330
|
+
name: "memory_reindex",
|
|
331
|
+
description: "Backfill semantic embeddings for notes that don't have one yet (run after the embedding model becomes available). Safe to call repeatedly.",
|
|
332
|
+
inputSchema: {
|
|
333
|
+
type: "object",
|
|
334
|
+
properties: {
|
|
335
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
336
|
+
force: { type: "boolean", description: "Re-embed all notes, not just missing ones", default: false },
|
|
337
|
+
},
|
|
338
|
+
},
|
|
339
|
+
},
|
|
340
|
+
{
|
|
341
|
+
name: "memory_link",
|
|
342
|
+
description: "Resolve wiki-style note links and show backlinks for a note.",
|
|
343
|
+
inputSchema: {
|
|
344
|
+
type: "object",
|
|
345
|
+
properties: {
|
|
346
|
+
id: { type: "string", description: "Note id to inspect" },
|
|
347
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
348
|
+
include_unresolved: { type: "boolean", description: "Include unresolved links in output", default: true },
|
|
349
|
+
},
|
|
350
|
+
required: ["id"],
|
|
351
|
+
},
|
|
352
|
+
},
|
|
353
|
+
{
|
|
354
|
+
name: "memory_global_recall",
|
|
355
|
+
description: "Recall relevant notes across projects with same-project bias and graceful keyword fallback.",
|
|
356
|
+
inputSchema: {
|
|
357
|
+
type: "object",
|
|
358
|
+
properties: {
|
|
359
|
+
query: { type: "string", description: "What you need context about" },
|
|
360
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
361
|
+
limit: { type: "number", description: "Max notes to return", default: 5 },
|
|
362
|
+
full: { type: "boolean", description: "Return full bodies instead of excerpts", default: false },
|
|
363
|
+
},
|
|
364
|
+
required: ["query"],
|
|
365
|
+
},
|
|
366
|
+
},
|
|
367
|
+
{
|
|
368
|
+
name: "memory_dedup",
|
|
369
|
+
description: "Find likely duplicate notes and suggest non-destructive merges.",
|
|
370
|
+
inputSchema: {
|
|
371
|
+
type: "object",
|
|
372
|
+
properties: {
|
|
373
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
374
|
+
threshold: { type: "number", description: "Duplicate threshold", default: 0.9 },
|
|
375
|
+
scope: { type: "string", enum: ["project", "global"], description: "Dedup scope", default: "project" },
|
|
376
|
+
},
|
|
377
|
+
},
|
|
378
|
+
},
|
|
379
|
+
{
|
|
380
|
+
name: "memory_stats",
|
|
381
|
+
description: "Summarize local memory storage across vault / journal / checkpoints: totals, top projects, recent activity, and temp-slug cleanup candidates. Returns the same text as the `stats` CLI.",
|
|
382
|
+
inputSchema: {
|
|
383
|
+
type: "object",
|
|
384
|
+
properties: {
|
|
385
|
+
root: { type: "string", description: "Storage root (default: ~/.codex/memories or first env var of MEMORY_VAULT_DIR / JOURNAL_DIR / CHECKPOINT_DIR)" },
|
|
386
|
+
top: { type: "number", description: "How many entries in top-project / recent-activity lists (default 10)", default: 10 },
|
|
387
|
+
json: { type: "boolean", description: "Return machine-readable JSON instead of human text", default: false },
|
|
388
|
+
},
|
|
389
|
+
},
|
|
390
|
+
},
|
|
391
|
+
{
|
|
392
|
+
name: "memory_moc",
|
|
393
|
+
description: "Generate / refresh the Obsidian-style Map of Content (MOC.md) for the project: lists every note with wikilinks, a #tag index, and backlink graph. Run after saves, or on demand to open the vault in Obsidian.",
|
|
394
|
+
inputSchema: {
|
|
395
|
+
type: "object",
|
|
396
|
+
properties: {
|
|
397
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
398
|
+
},
|
|
399
|
+
},
|
|
400
|
+
},
|
|
401
|
+
{
|
|
402
|
+
name: "memory_graph",
|
|
403
|
+
description: "Export the note graph (nodes + directed edges from [[wikilinks]]) as JSON, for external graph views or analysis. Backlinks are resolved via graph state.",
|
|
404
|
+
inputSchema: {
|
|
405
|
+
type: "object",
|
|
406
|
+
properties: {
|
|
407
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
408
|
+
},
|
|
409
|
+
},
|
|
410
|
+
},
|
|
411
|
+
{
|
|
412
|
+
name: "memory_broadcast",
|
|
413
|
+
description: "Broadcast an event/finding to the real-time multi-agent swarm stream for peer subagents in the workspace.",
|
|
414
|
+
inputSchema: {
|
|
415
|
+
type: "object",
|
|
416
|
+
properties: {
|
|
417
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
418
|
+
eventType: { type: "string", description: "Event type: 'finding' | 'bug' | 'decision' | 'status'", default: "finding" },
|
|
419
|
+
topic: { type: "string", description: "Topic/category" },
|
|
420
|
+
payload: { type: "object", description: "Structured event payload" },
|
|
421
|
+
agentName: { type: "string", description: "Name/role of emitting agent", default: "agent" },
|
|
422
|
+
},
|
|
423
|
+
required: ["topic"],
|
|
424
|
+
},
|
|
425
|
+
},
|
|
426
|
+
{
|
|
427
|
+
name: "memory_swarm_timeline",
|
|
428
|
+
description: "Query real-time multi-agent swarm event stream in the shared workspace.",
|
|
429
|
+
inputSchema: {
|
|
430
|
+
type: "object",
|
|
431
|
+
properties: {
|
|
432
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
433
|
+
limit: { type: "number", description: "Max events to return", default: 20 },
|
|
434
|
+
eventType: { type: "string", description: "Filter by eventType" },
|
|
435
|
+
},
|
|
436
|
+
},
|
|
437
|
+
},
|
|
438
|
+
{
|
|
439
|
+
name: "memory_import_session",
|
|
440
|
+
description: "Ingest and extract key decisions, bugs solved, and architecture notes from a conversation or session digest into permanent Markdown memory notes.",
|
|
441
|
+
inputSchema: {
|
|
442
|
+
type: "object",
|
|
443
|
+
properties: {
|
|
444
|
+
title: { type: "string", description: "Title for the imported memory snapshot" },
|
|
445
|
+
sessionText: { type: "string", description: "Raw transcript or summary text of the session" },
|
|
446
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
447
|
+
tags: { type: "array", items: { type: "string" }, description: "Tags for the notes" },
|
|
448
|
+
},
|
|
449
|
+
required: ["title", "sessionText"],
|
|
450
|
+
},
|
|
451
|
+
},
|
|
452
|
+
{
|
|
453
|
+
name: "memory_auto_index",
|
|
454
|
+
description: "Run autonomous background observer to inspect git commits, branch switches, file modifications, and chat session transcripts to auto-derive project notes and architectural decisions.",
|
|
455
|
+
inputSchema: {
|
|
456
|
+
type: "object",
|
|
457
|
+
properties: {
|
|
458
|
+
dir: { type: "string", description: "Project directory (defaults to CWD)" },
|
|
459
|
+
dryRun: { type: "boolean", description: "Preview derived knowledge without saving", default: false },
|
|
460
|
+
scanSessions: { type: "boolean", description: "Scan recent chat session logs/transcripts to auto-extract architectural decisions and key discussions", default: true },
|
|
461
|
+
sessionDir: { type: "string", description: "Optional custom directory containing session JSONL logs" },
|
|
462
|
+
},
|
|
463
|
+
},
|
|
464
|
+
},
|
|
465
|
+
],
|
|
466
|
+
}));
|
|
467
|
+
|
|
468
|
+
this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
469
|
+
const { name, arguments: args } = request.params;
|
|
470
|
+
try {
|
|
471
|
+
switch (name) {
|
|
472
|
+
case "memory_save": return await this.save(args || {});
|
|
473
|
+
case "memory_recall": return await this.recall(args || {});
|
|
474
|
+
case "memory_list": return await this.list(args || {});
|
|
475
|
+
case "memory_get": return await this.get(args || {});
|
|
476
|
+
case "memory_delete": return await this.del(args || {});
|
|
477
|
+
case "memory_reindex": return await this.reindex(args || {});
|
|
478
|
+
case "memory_link": return await this.link(args || {});
|
|
479
|
+
case "memory_global_recall": return await this.globalRecall(args || {});
|
|
480
|
+
case "memory_dedup": return await this.dedup(args || {});
|
|
481
|
+
case "memory_stats": return await this.stats(args || {});
|
|
482
|
+
case "memory_moc": return await this.moc(args || {});
|
|
483
|
+
case "memory_graph": return await this.graph(args || {});
|
|
484
|
+
case "memory_broadcast": return await this.broadcast(args || {});
|
|
485
|
+
case "memory_swarm_timeline": return await this.swarmTimeline(args || {});
|
|
486
|
+
case "memory_auto_index": return await this.autoIndex(args || {});
|
|
487
|
+
default: throw new Error(`Unknown tool: ${name}`);
|
|
488
|
+
}
|
|
489
|
+
} catch (error) {
|
|
490
|
+
return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true };
|
|
491
|
+
}
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
// Resources: expose every saved note as a read-only resource across all
|
|
495
|
+
// projects in the vault. URI form: memory://<project-slug>/<noteId>
|
|
496
|
+
this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
|
|
497
|
+
const resources = [];
|
|
498
|
+
let slugs = [];
|
|
499
|
+
try { slugs = await fs.readdir(VAULT_ROOT); } catch { slugs = []; }
|
|
500
|
+
for (const slug of slugs) {
|
|
501
|
+
const indexFile = path.join(VAULT_ROOT, slug, "index.json");
|
|
502
|
+
let index; try { index = JSON.parse(await fs.readFile(indexFile, "utf8")); } catch { continue; }
|
|
503
|
+
for (const n of Object.values(index.notes || {})) {
|
|
504
|
+
resources.push({
|
|
505
|
+
uri: `memory://${slug}/${n.id}`,
|
|
506
|
+
name: n.title || n.id,
|
|
507
|
+
description: `[${n.kind || "note"}] ${(n.tags || []).join(", ")} — ${n.created || ""}`.trim(),
|
|
508
|
+
mimeType: "text/markdown",
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return { resources };
|
|
513
|
+
});
|
|
514
|
+
|
|
515
|
+
this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({ resourceTemplates: [] }));
|
|
516
|
+
|
|
517
|
+
this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
518
|
+
const uri = request.params.uri || "";
|
|
519
|
+
const m = uri.match(/^memory:\/\/([^/]+)\/(.+)$/);
|
|
520
|
+
if (!m) throw new Error(`Unknown resource URI: ${uri}`);
|
|
521
|
+
const [, slug, noteId] = m;
|
|
522
|
+
const indexFile = path.join(VAULT_ROOT, slug, "index.json");
|
|
523
|
+
let index; try { index = JSON.parse(await fs.readFile(indexFile, "utf8")); } catch { throw new Error(`Project not found: ${slug}`); }
|
|
524
|
+
const note = index.notes?.[noteId];
|
|
525
|
+
if (!note) throw new Error(`Note not found: ${noteId}`);
|
|
526
|
+
const raw = await fs.readFile(path.join(VAULT_ROOT, slug, note.file), "utf8");
|
|
527
|
+
return { contents: [{ uri, mimeType: "text/markdown", text: raw }] };
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
async save({ title, content, dir, tags, kind = "note", aliases, created: createdArg }) {
|
|
532
|
+
title = limit(title, "title", MAX_TITLE);
|
|
533
|
+
content = limit(content, "content", MAX_CONTENT);
|
|
534
|
+
const tagList = Array.isArray(tags) ? tags.map((t) => String(t).trim()).filter(Boolean) : [];
|
|
535
|
+
const aliasList = Array.isArray(aliases) ? aliases.map((t) => String(t).trim()).filter(Boolean) : [];
|
|
536
|
+
const p = this.paths(dir);
|
|
537
|
+
await fs.mkdir(p.notesDir, { recursive: true });
|
|
538
|
+
|
|
539
|
+
const id = genId();
|
|
540
|
+
const created = (createdArg && /^\d{4}-\d{2}-\d{2}/.test(String(createdArg))) ? String(createdArg) : nowIso();
|
|
541
|
+
const meta = { id, title, kind, tags: tagList, aliases: aliasList, created, dir: path.resolve(dir || process.cwd()) };
|
|
542
|
+
const file = path.join(p.notesDir, `${id}.md`);
|
|
543
|
+
await fs.writeFile(file, buildFrontmatter(meta) + `# ${title}\n\n${content}\n`);
|
|
544
|
+
|
|
545
|
+
const index = await this.loadIndex(p);
|
|
546
|
+
const keywords = [...new Set([...tokenize(title), ...tokenize(content), ...tagList.map((t) => t.toLowerCase())])];
|
|
547
|
+
const note = { id, title, kind, tags: tagList, aliases: aliasList, created, keywords, file: path.relative(p.projectDir, file) };
|
|
548
|
+
|
|
549
|
+
const vec = await embedOne(`${title}\n\n${content}`);
|
|
550
|
+
let embedded = false;
|
|
551
|
+
if (vec) { note.embedding = vec; note.embModel = embeddingConfig().model; embedded = true; }
|
|
552
|
+
|
|
553
|
+
index.notes[id] = note;
|
|
554
|
+
await this.saveIndex(p, index);
|
|
555
|
+
await this.ensureObsidianFolder(p);
|
|
556
|
+
// Resolve [[wikilinks]] + backlinks immediately so the graph is fresh on save.
|
|
557
|
+
const ensured = await ensureGraphState({
|
|
558
|
+
vaultRoot: VAULT_ROOT,
|
|
559
|
+
projectDir: p.projectDir,
|
|
560
|
+
slug: p.slug,
|
|
561
|
+
index,
|
|
562
|
+
noteLoader: loadNoteBody,
|
|
563
|
+
});
|
|
564
|
+
if (ensured.changed) await this.saveIndex(p, ensured.index);
|
|
565
|
+
await this.writeMoc(p, ensured.index);
|
|
566
|
+
|
|
567
|
+
return { content: [{ type: "text", text: `Saved note ${id} → ${p.slug}\nFile: ${file}\nKeywords indexed: ${keywords.length}${embedded ? " (semantic embedding stored)" : " (keyword-only; embeddings unavailable)"}\nMOC refreshed: ${path.join(p.projectDir, "MOC.md")}` }] };
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
async recall({ query, dir, limit: lim = 5, full = false, mode: requestedMode = "auto" }) {
|
|
571
|
+
query = limit(query, "query", 2000);
|
|
572
|
+
const p = this.paths(dir);
|
|
573
|
+
const index = await this.loadIndex(p);
|
|
574
|
+
const ensured = await ensureGraphState({
|
|
575
|
+
vaultRoot: VAULT_ROOT,
|
|
576
|
+
projectDir: p.projectDir,
|
|
577
|
+
slug: p.slug,
|
|
578
|
+
index,
|
|
579
|
+
noteLoader: loadNoteBody,
|
|
580
|
+
});
|
|
581
|
+
if (ensured.changed) await this.saveIndex(p, ensured.index);
|
|
582
|
+
const notes = Object.values(ensured.index.notes || {});
|
|
583
|
+
if (notes.length === 0) {
|
|
584
|
+
return { content: [{ type: "text", text: `No memories for ${p.slug} yet. Use memory_save first.` }] };
|
|
585
|
+
}
|
|
586
|
+
const qTokens = new Set(tokenize(query));
|
|
587
|
+
const kw = (n) => {
|
|
588
|
+
let score = 0;
|
|
589
|
+
for (const k of n.keywords || []) if (qTokens.has(k)) score += 1;
|
|
590
|
+
for (const t of n.tags || []) if (qTokens.has(t.toLowerCase())) score += 2;
|
|
591
|
+
for (const w of tokenize(n.title)) if (qTokens.has(w)) score += 2;
|
|
592
|
+
return score;
|
|
593
|
+
};
|
|
594
|
+
|
|
595
|
+
// Tier 2.1: respect requested mode. "auto" = smart fallback.
|
|
596
|
+
let mode = deterministicEnabled() ? "deterministic" : "keyword";
|
|
597
|
+
const useEmbed = requestedMode !== "keyword" && !deterministicEnabled();
|
|
598
|
+
const qVec = useEmbed ? await embedOne(query) : null;
|
|
599
|
+
const haveEmb = qVec && notes.some((n) => Array.isArray(n.embedding));
|
|
600
|
+
|
|
601
|
+
// Tier 2.1: "semantic" requested but unavailable -> error
|
|
602
|
+
if (requestedMode === "semantic" && !haveEmb) {
|
|
603
|
+
return { content: [{ type: "text", text: `memory_recall(mode=semantic) requested but no embeddings available. Set MCP_EMBED_API_KEY + MCP_EMBED_MODEL, or omit mode for keyword fallback.` }], isError: true };
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
let scored;
|
|
607
|
+
if (haveEmb) {
|
|
608
|
+
mode = "semantic";
|
|
609
|
+
const maxKw = Math.max(1, ...notes.map(kw));
|
|
610
|
+
scored = notes.map((n) => {
|
|
611
|
+
const sim = Array.isArray(n.embedding) ? cosine(qVec, n.embedding) : 0;
|
|
612
|
+
const kwNorm = kw(n) / maxKw;
|
|
613
|
+
const score = 0.8 * sim + 0.2 * kwNorm + graphBoost(n, [...qTokens]);
|
|
614
|
+
return { n, score, sim };
|
|
615
|
+
}).filter((x) => x.score > 0.05)
|
|
616
|
+
.sort((a, b) => b.score - a.score || (a.n.created < b.n.created ? 1 : -1))
|
|
617
|
+
.slice(0, Math.max(1, Math.min(20, lim)));
|
|
618
|
+
} else {
|
|
619
|
+
const want = Math.max(1, Math.min(20, lim));
|
|
620
|
+
const kwRanked = notes.map((n) => ({ n, score: kw(n) + graphBoost(n, [...qTokens]) }))
|
|
621
|
+
.filter((x) => x.score > 0)
|
|
622
|
+
.sort((a, b) => b.score - a.score || (a.n.created < b.n.created ? 1 : -1));
|
|
623
|
+
|
|
624
|
+
// Build a candidate pool for the LLM reranker. If keyword found nothing,
|
|
625
|
+
// fall back to most-recent notes so semantic-style queries still work.
|
|
626
|
+
let pool = kwRanked.slice(0, 20);
|
|
627
|
+
if (pool.length === 0 && rerankConfig().enabled) {
|
|
628
|
+
pool = notes.slice().sort((a, b) => (a.created < b.created ? 1 : -1)).slice(0, 20).map((n) => ({ n, score: 0 }));
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
let reranked = null;
|
|
632
|
+
if (rerankConfig().enabled && pool.length > 1) {
|
|
633
|
+
const cands = [];
|
|
634
|
+
for (const { n } of pool) {
|
|
635
|
+
const raw = await fs.readFile(path.join(p.projectDir, n.file), "utf8").catch(() => "");
|
|
636
|
+
const { body } = parseFrontmatter(raw);
|
|
637
|
+
cands.push({ id: n.id, title: n.title, snippet: body });
|
|
638
|
+
}
|
|
639
|
+
const order = await rerank(query, cands, want);
|
|
640
|
+
if (order) {
|
|
641
|
+
mode = "rerank";
|
|
642
|
+
const byId = new Map(pool.map((x) => [x.n.id, x.n]));
|
|
643
|
+
reranked = order.map((id) => byId.get(id)).filter(Boolean).slice(0, want).map((n) => ({ n, score: 0 }));
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
scored = (reranked && reranked.length)
|
|
648
|
+
? reranked
|
|
649
|
+
: kwRanked.slice(0, want);
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
if (scored.length === 0) {
|
|
653
|
+
return { content: [{ type: "text", text: `No relevant memories for "${query}" in ${p.slug}. Try memory_list.` }] };
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const blocks = [];
|
|
657
|
+
for (const { n, score, sim } of scored) {
|
|
658
|
+
const raw = await fs.readFile(path.join(p.projectDir, n.file), "utf8").catch(() => "");
|
|
659
|
+
const { body } = parseFrontmatter(raw);
|
|
660
|
+
const text = full ? body.trim() : body.trim().split("\n").slice(0, 12).join("\n");
|
|
661
|
+
const tag = mode === "semantic" ? `sim:${(sim ?? 0).toFixed(3)}` : (mode === "rerank" ? "llm-ranked" : `score:${score}`);
|
|
662
|
+
blocks.push(`### ${n.title} (id:${n.id}, ${tag}, ${n.created})\n${text}`);
|
|
663
|
+
}
|
|
664
|
+
// Tier 2.2: annotate mode with rerank indicator
|
|
665
|
+
const isReranked = rerankConfig().enabled && blocks.length > 1;
|
|
666
|
+
const displayMode = mode === "semantic" && isReranked ? "semantic+rerank"
|
|
667
|
+
: mode === "keyword" && isReranked ? "keyword+rerank"
|
|
668
|
+
: mode;
|
|
669
|
+
return { content: [{ type: "text", text: `Recall for "${query}" in ${p.slug} [${displayMode}]:\n\n${blocks.join("\n\n---\n\n")}` }] };
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
async dedup({ dir, threshold = 0.9, scope = "project" }) {
|
|
673
|
+
const p = this.paths(dir);
|
|
674
|
+
const rows = await loadGlobalNotes(VAULT_ROOT);
|
|
675
|
+
const filtered = scope === "project" ? rows.filter((row) => row.slug === p.slug) : rows;
|
|
676
|
+
const withBodies = await Promise.all(filtered.map(async ({ slug, note }) => {
|
|
677
|
+
const raw = await fs.readFile(path.join(VAULT_ROOT, slug, note.file), "utf8").catch(() => "");
|
|
678
|
+
const { body } = parseFrontmatter(raw);
|
|
679
|
+
return { slug, note, body };
|
|
680
|
+
}));
|
|
681
|
+
const pairs = findDuplicateCandidates({ rows: withBodies, threshold });
|
|
682
|
+
if (!pairs.length) {
|
|
683
|
+
return { content: [{ type: "text", text: `No duplicate suggestions above ${threshold} in ${scope} scope.` }] };
|
|
684
|
+
}
|
|
685
|
+
const lines = [`Duplicate suggestions [threshold=${threshold}, scope=${scope}]:`, ""];
|
|
686
|
+
for (const pair of pairs) {
|
|
687
|
+
lines.push(`- suggested merge: [${pair.left.slug}] ${pair.left.note.title} <-> [${pair.right.slug}] ${pair.right.note.title} (score=${pair.score.toFixed(3)})`);
|
|
688
|
+
lines.push(` reasons: ${pair.reasons.join(", ")}`);
|
|
689
|
+
}
|
|
690
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
async globalRecall({ query, dir, limit: lim = 5, full = false }) {
|
|
694
|
+
query = limit(query, "query", 2000);
|
|
695
|
+
const p = this.paths(dir);
|
|
696
|
+
const currentIndex = await this.loadIndex(p);
|
|
697
|
+
const ensured = await ensureGraphState({
|
|
698
|
+
vaultRoot: VAULT_ROOT,
|
|
699
|
+
projectDir: p.projectDir,
|
|
700
|
+
slug: p.slug,
|
|
701
|
+
index: currentIndex,
|
|
702
|
+
noteLoader: loadNoteBody,
|
|
703
|
+
});
|
|
704
|
+
if (ensured.changed) await this.saveIndex(p, ensured.index);
|
|
705
|
+
const rows = await loadGlobalNotes(VAULT_ROOT);
|
|
706
|
+
const qTokens = new Set(tokenize(query));
|
|
707
|
+
const qVec = deterministicEnabled() ? null : await embedOne(query);
|
|
708
|
+
const haveEmbeddings = !!(qVec && rows.some((row) => Array.isArray(row.note.embedding)));
|
|
709
|
+
|
|
710
|
+
const scored = rows.map(({ slug, note }) => {
|
|
711
|
+
let kwScore = 0;
|
|
712
|
+
for (const keyword of note.keywords || []) if (qTokens.has(keyword)) kwScore += 1;
|
|
713
|
+
for (const word of tokenize(note.title)) if (qTokens.has(word)) kwScore += 2;
|
|
714
|
+
const sameProjectBoost = slug === p.slug ? 0.25 : 0;
|
|
715
|
+
const sim = haveEmbeddings && Array.isArray(note.embedding) ? cosine(qVec, note.embedding) : 0;
|
|
716
|
+
const score = (haveEmbeddings ? (0.8 * sim) : 0) + (0.2 * kwScore) + sameProjectBoost + graphBoost(note, [...qTokens]);
|
|
717
|
+
return { slug, note, sim, score };
|
|
718
|
+
}).filter((entry) => entry.score > 0)
|
|
719
|
+
.sort((a, b) => b.score - a.score || (a.note.created < b.note.created ? 1 : -1))
|
|
720
|
+
.slice(0, Math.max(1, Math.min(20, lim)));
|
|
721
|
+
|
|
722
|
+
if (scored.length === 0) {
|
|
723
|
+
return { content: [{ type: "text", text: `No relevant global memories for "${query}". Try memory_list or memory_recall.` }] };
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const mode = haveEmbeddings ? "semantic+graph" : "keyword+graph";
|
|
727
|
+
const blocks = await Promise.all(scored.map(async ({ slug, note, sim, score }) => {
|
|
728
|
+
const raw = await fs.readFile(path.join(VAULT_ROOT, slug, note.file), "utf8").catch(() => "");
|
|
729
|
+
const { body } = parseFrontmatter(raw);
|
|
730
|
+
const text = full ? body.trim() : body.trim().split("\n").slice(0, 12).join("\n");
|
|
731
|
+
return `### ${note.title} ([${slug}], ${haveEmbeddings ? `sim:${sim.toFixed(3)}` : `score:${score.toFixed(2)}`})\n${text}`;
|
|
732
|
+
}));
|
|
733
|
+
return { content: [{ type: "text", text: `Global recall for "${query}" [${mode}]:\n\n${blocks.join("\n\n---\n\n")}` }] };
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
async list({ dir, limit: lim = 20 }) {
|
|
737
|
+
const p = this.paths(dir);
|
|
738
|
+
const index = await this.loadIndex(p);
|
|
739
|
+
const notes = Object.values(index.notes || {})
|
|
740
|
+
.sort((a, b) => (a.created < b.created ? 1 : -1))
|
|
741
|
+
.slice(0, Math.max(1, Math.min(200, lim)));
|
|
742
|
+
if (notes.length === 0) return { content: [{ type: "text", text: `No memories for ${p.slug} yet.` }] };
|
|
743
|
+
const lines = notes.map((n) => `- ${n.id} [${n.kind}] ${n.title}${n.tags?.length ? ` (#${n.tags.join(" #")})` : ""} — ${n.created}`);
|
|
744
|
+
return { content: [{ type: "text", text: `Memories in ${p.slug} (${notes.length}):\n${lines.join("\n")}` }] };
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
async get({ id, dir }) {
|
|
748
|
+
id = limit(id, "id", 100);
|
|
749
|
+
const p = this.paths(dir);
|
|
750
|
+
const index = await this.loadIndex(p);
|
|
751
|
+
const meta = index.notes?.[id];
|
|
752
|
+
if (!meta) throw new Error(`Note ${id} not found in ${p.slug}`);
|
|
753
|
+
const raw = await fs.readFile(path.join(p.projectDir, meta.file), "utf8");
|
|
754
|
+
return { content: [{ type: "text", text: raw }] };
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
async del({ id, dir }) {
|
|
758
|
+
id = limit(id, "id", 100);
|
|
759
|
+
const p = this.paths(dir);
|
|
760
|
+
const index = await this.loadIndex(p);
|
|
761
|
+
const meta = index.notes?.[id];
|
|
762
|
+
if (!meta) throw new Error(`Note ${id} not found in ${p.slug}`);
|
|
763
|
+
await fs.unlink(path.join(p.projectDir, meta.file)).catch(() => {});
|
|
764
|
+
delete index.notes[id];
|
|
765
|
+
await this.saveIndex(p, index);
|
|
766
|
+
await this.writeMoc(p, index);
|
|
767
|
+
return { content: [{ type: "text", text: `Deleted note ${id} from ${p.slug}` }] };
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
async link({ id, dir, include_unresolved = true }) {
|
|
771
|
+
id = limit(id, "id", 100);
|
|
772
|
+
const p = this.paths(dir);
|
|
773
|
+
const index = await this.loadIndex(p);
|
|
774
|
+
const note = index.notes?.[id];
|
|
775
|
+
if (!note) throw new Error(`Note ${id} not found in ${p.slug}`);
|
|
776
|
+
|
|
777
|
+
const ensured = await ensureGraphState({
|
|
778
|
+
vaultRoot: VAULT_ROOT,
|
|
779
|
+
projectDir: p.projectDir,
|
|
780
|
+
slug: p.slug,
|
|
781
|
+
index,
|
|
782
|
+
noteLoader: loadNoteBody,
|
|
783
|
+
});
|
|
784
|
+
if (ensured.changed) await this.saveIndex(p, ensured.index);
|
|
785
|
+
|
|
786
|
+
const current = ensured.index.notes[id];
|
|
787
|
+
const links = [];
|
|
788
|
+
for (const link of current.links || []) {
|
|
789
|
+
const resolved = await resolveLink({
|
|
790
|
+
vaultRoot: VAULT_ROOT,
|
|
791
|
+
currentSlug: p.slug,
|
|
792
|
+
ref: link.ref,
|
|
793
|
+
project: link.project,
|
|
794
|
+
kind: link.kind,
|
|
795
|
+
});
|
|
796
|
+
if (resolved.status !== "missing" || include_unresolved) links.push({ link, resolved });
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
const lines = [
|
|
800
|
+
`Links for ${current.title} (${current.id})`,
|
|
801
|
+
"",
|
|
802
|
+
"Outgoing:",
|
|
803
|
+
...links.map(({ link, resolved }) => `- ${link.raw} -> ${resolved.status}${resolved.match ? ` (${resolved.match.title})` : ""}`),
|
|
804
|
+
"",
|
|
805
|
+
"Backlinks:",
|
|
806
|
+
...((current.backlinks || []).length ? current.backlinks.map((b) => `- ${b.title} (${b.id})`) : ["- none"]),
|
|
807
|
+
];
|
|
808
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
async reindex({ dir, force = false }) {
|
|
812
|
+
const p = this.paths(dir);
|
|
813
|
+
if (deterministicEnabled()) return { content: [{ type: "text", text: `Reindex ${p.slug}: skipped (deterministic no-network mode; embeddings disabled).` }] };
|
|
814
|
+
const index = await this.loadIndex(p);
|
|
815
|
+
const notes = Object.values(index.notes || {});
|
|
816
|
+
if (notes.length === 0) return { content: [{ type: "text", text: `No memories for ${p.slug} yet.` }] };
|
|
817
|
+
|
|
818
|
+
const targets = notes.filter((n) => force || !Array.isArray(n.embedding));
|
|
819
|
+
if (targets.length === 0) return { content: [{ type: "text", text: `All ${notes.length} notes already embedded in ${p.slug}.` }] };
|
|
820
|
+
|
|
821
|
+
let done = 0, failed = 0;
|
|
822
|
+
for (const n of targets) {
|
|
823
|
+
const raw = await fs.readFile(path.join(p.projectDir, n.file), "utf8").catch(() => "");
|
|
824
|
+
const { body } = parseFrontmatter(raw);
|
|
825
|
+
const vec = await embedOne(`${n.title}\n\n${body}`);
|
|
826
|
+
if (vec) { n.embedding = vec; n.embModel = embeddingConfig().model; done++; }
|
|
827
|
+
else { failed++; }
|
|
828
|
+
}
|
|
829
|
+
await this.saveIndex(p, index);
|
|
830
|
+
return { content: [{ type: "text", text: `Reindex ${p.slug}: embedded ${done}, failed ${failed} (embeddings ${embeddingConfig().enabled ? "configured" : "not configured"}). ${failed ? "Failures usually mean the embedding model is unavailable right now." : ""}` }] };
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
async stats({ root: explicitRoot, top = 10, json = false } = {}) {
|
|
834
|
+
const root = explicitRoot
|
|
835
|
+
? path.resolve(explicitRoot)
|
|
836
|
+
: (process.env.MEMORY_VAULT_DIR
|
|
837
|
+
? path.dirname(process.env.MEMORY_VAULT_DIR)
|
|
838
|
+
: process.env.JOURNAL_DIR
|
|
839
|
+
? path.dirname(process.env.JOURNAL_DIR)
|
|
840
|
+
: process.env.CHECKPOINT_DIR
|
|
841
|
+
? path.dirname(process.env.CHECKPOINT_DIR)
|
|
842
|
+
: path.join(os.homedir(), ".ai-shared-memory"));
|
|
843
|
+
const stats = computeStats({ root, topLimit: top });
|
|
844
|
+
const text = json ? formatJson(stats) : formatText(stats);
|
|
845
|
+
return { content: [{ type: "text", text }] };
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
async moc({ dir } = {}) {
|
|
849
|
+
const p = this.paths(dir);
|
|
850
|
+
await this.ensureObsidianFolder(p);
|
|
851
|
+
const index = await this.loadIndex(p);
|
|
852
|
+
await this.writeMoc(p, index);
|
|
853
|
+
const mocFile = path.join(p.projectDir, "MOC.md");
|
|
854
|
+
const count = Object.keys(index.notes || {}).length;
|
|
855
|
+
return { content: [{ type: "text", text: `MOC refreshed for ${p.slug}: ${count} notes → ${mocFile}\nOpen the project folder in Obsidian to see the graph + tag pages.` }] };
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
async graph({ dir } = {}) {
|
|
859
|
+
const p = this.paths(dir);
|
|
860
|
+
const index = await this.loadIndex(p);
|
|
861
|
+
const ensured = await ensureGraphState({
|
|
862
|
+
vaultRoot: VAULT_ROOT,
|
|
863
|
+
projectDir: p.projectDir,
|
|
864
|
+
slug: p.slug,
|
|
865
|
+
index,
|
|
866
|
+
noteLoader: loadNoteBody,
|
|
867
|
+
});
|
|
868
|
+
if (ensured.changed) await this.saveIndex(p, ensured.index);
|
|
869
|
+
const g = this.buildGraph(ensured.index);
|
|
870
|
+
return { content: [{ type: "text", text: JSON.stringify(g, null, 2) }] };
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
async broadcast({ dir, eventType = "finding", topic, payload, agentName = "agent" } = {}) {
|
|
874
|
+
const p = this.paths(dir);
|
|
875
|
+
const event = await broadcastSwarmEvent(p.projectDir, { eventType, topic, payload, agentName });
|
|
876
|
+
return { content: [{ type: "text", text: `Broadcasted swarm event ${event.id} [${event.eventType}] topic: "${topic}" by ${agentName}` }] };
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
async swarmTimeline({ dir, limit = 20, eventType = null } = {}) {
|
|
880
|
+
const p = this.paths(dir);
|
|
881
|
+
const events = await getSwarmTimeline(p.projectDir, { limit, eventType });
|
|
882
|
+
if (!events.length) {
|
|
883
|
+
return { content: [{ type: "text", text: `No swarm events recorded yet for project ${p.slug}.` }] };
|
|
884
|
+
}
|
|
885
|
+
const lines = [`# Swarm Stream: ${p.slug}`, `Total Events: ${events.length}`, ``];
|
|
886
|
+
for (const e of events) {
|
|
887
|
+
lines.push(`- **[${e.timestamp}] (${e.agentName})** \`${e.eventType}\` — **${e.topic}**`);
|
|
888
|
+
if (e.payload && Object.keys(e.payload).length > 0) {
|
|
889
|
+
lines.push(` \`\`\`json\n ${JSON.stringify(e.payload)}\n \`\`\``);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
async autoIndex({ dir, dryRun = false, scanSessions = true, sessionDir = null } = {}) {
|
|
896
|
+
const p = this.paths(dir);
|
|
897
|
+
const res = await runAutoIndexer(dir, { dryRun, scanSessions, sessionDir });
|
|
898
|
+
if (!dryRun && res.summaryText) {
|
|
899
|
+
await this.save({
|
|
900
|
+
title: `Auto-Index ${new Date().toISOString().substring(0, 10)} (${res.branch})`,
|
|
901
|
+
content: res.summaryText,
|
|
902
|
+
dir,
|
|
903
|
+
tags: ["auto-index", "git", "session-digest"],
|
|
904
|
+
kind: "auto-derived"
|
|
905
|
+
});
|
|
906
|
+
for (const note of (res.notesCreated || [])) {
|
|
907
|
+
await this.save({
|
|
908
|
+
title: note.title,
|
|
909
|
+
content: note.content,
|
|
910
|
+
dir,
|
|
911
|
+
tags: note.tags || ["session-digest", "auto-derived"],
|
|
912
|
+
kind: "session-digest"
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
return { content: [{ type: "text", text: res.summaryText + (dryRun ? "\n\n(Dry Run — note not saved)" : "\n\n(Saved to project memory vault)") }] };
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
async run() {
|
|
920
|
+
const transport = new StdioServerTransport();
|
|
921
|
+
await this.server.connect(transport);
|
|
922
|
+
console.error(`Project Memory MCP server running on stdio (vault: ${VAULT_ROOT})`);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
927
|
+
const server = new ProjectMemoryServer();
|
|
928
|
+
server.run().catch(console.error);
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
export { ProjectMemoryServer };
|