@mosadd/mcp 3.0.0-alpha.51 → 3.0.0-alpha.53

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +334 -309
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-BTAIZKYT.js → chunk-AWKITPZQ.js} +407 -106
  5. package/dist/index.d.ts +11 -1
  6. package/dist/index.js +1 -1
  7. package/package.json +9 -9
  8. package/src/__tests__/blob-upload.test.ts +93 -0
  9. package/src/__tests__/golden-path.test.ts +139 -139
  10. package/src/__tests__/integration.test.ts +182 -182
  11. package/src/__tests__/knowledge-ingest.test.ts +114 -114
  12. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  13. package/src/__tests__/mdm-mcp-readable.test.ts +284 -0
  14. package/src/__tests__/mirc-invite.test.ts +112 -112
  15. package/src/__tests__/mtalk.test.ts +122 -122
  16. package/src/__tests__/server.test.ts +71 -71
  17. package/src/__tests__/serverJsonVersion.test.ts +45 -45
  18. package/src/__tests__/tool-count-consistency.test.ts +199 -199
  19. package/src/bin/login.ts +138 -138
  20. package/src/bin/mcp.ts +145 -145
  21. package/src/config.ts +66 -66
  22. package/src/crypto/mdm-session.ts +798 -502
  23. package/src/index.ts +19 -19
  24. package/src/observability/sentry.ts +79 -79
  25. package/src/providers/blob-upload.ts +52 -6
  26. package/src/providers/memory-voice.ts +79 -79
  27. package/src/providers/supabase-dm.ts +174 -122
  28. package/src/providers/supabase-voice.ts +91 -91
  29. package/src/providers/supabase.ts +231 -231
  30. package/src/server.ts +186 -162
  31. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -67
  32. package/src/tools/actions.ts +166 -166
  33. package/src/tools/attachments.ts +276 -276
  34. package/src/tools/capabilities.ts +70 -70
  35. package/src/tools/embed.ts +110 -110
  36. package/src/tools/index.ts +181 -181
  37. package/src/tools/knowledge-graph.ts +186 -186
  38. package/src/tools/knowledge.ts +344 -344
  39. package/src/tools/mail-agentbox.ts +155 -155
  40. package/src/tools/mail-aliases.ts +25 -25
  41. package/src/tools/mail-provenance.ts +137 -137
  42. package/src/tools/mail.ts +403 -403
  43. package/src/tools/mcall.ts +216 -216
  44. package/src/tools/mdm-as-agent.ts +126 -126
  45. package/src/tools/mdm-voice.ts +220 -220
  46. package/src/tools/mdm.ts +119 -17
  47. package/src/tools/mirc-edge.ts +196 -196
  48. package/src/tools/mirc-members.ts +287 -287
  49. package/src/tools/mirc.ts +308 -308
  50. package/src/tools/mroom-messages.ts +142 -142
  51. package/src/tools/mroom.ts +221 -221
  52. package/src/tools/mtalk.ts +131 -131
  53. package/src/tools/murl.ts +314 -314
  54. package/src/tools/presence.ts +442 -442
  55. package/src/tools/ptt-ingest.ts +99 -99
  56. package/src/tools/threat.ts +123 -123
  57. package/src/types.ts +121 -121
  58. package/src/version.ts +8 -8
  59. package/src/voice/floor.ts +132 -132
  60. package/LICENSE +0 -201
@@ -1,182 +1,182 @@
1
- /**
2
- * Integration test — spawns the actual mcp binary as a child process,
3
- * sends JSON-RPC over stdin, validates JSON-RPC responses on stdout.
4
- *
5
- * Catches regressions like the ZodObject.shape vs ._def.shape() incident
6
- * (commit c237e86) that unit tests against allTools wouldn't have caught —
7
- * the bug only surfaces when the MCP SDK's `McpServer.tool(...)` rejects
8
- * the schema we pass.
9
- */
10
-
11
- import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
12
- import { join } from "node:path";
13
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
14
-
15
- const MCP_BIN = join(__dirname, "..", "..", "dist", "bin", "mcp.js");
16
-
17
- interface JsonRpcMessage {
18
- jsonrpc: "2.0";
19
- id?: number | string;
20
- method?: string;
21
- params?: unknown;
22
- result?: unknown;
23
- error?: { code: number; message: string };
24
- }
25
-
26
- class McpClient {
27
- private proc!: ChildProcessWithoutNullStreams;
28
- private buffer = "";
29
- private resolvers = new Map<number | string, (msg: JsonRpcMessage) => void>();
30
- private nextId = 1;
31
-
32
- async start(): Promise<void> {
33
- this.proc = spawn("node", [MCP_BIN], { stdio: ["pipe", "pipe", "pipe"] });
34
-
35
- this.proc.stdout.on("data", (chunk: Buffer) => {
36
- this.buffer += chunk.toString("utf8");
37
- let nl = this.buffer.indexOf("\n");
38
- while (nl !== -1) {
39
- const line = this.buffer.slice(0, nl).trim();
40
- this.buffer = this.buffer.slice(nl + 1);
41
- if (line) {
42
- try {
43
- const msg = JSON.parse(line) as JsonRpcMessage;
44
- if (msg.id !== undefined) {
45
- const resolve = this.resolvers.get(msg.id);
46
- if (resolve) {
47
- this.resolvers.delete(msg.id);
48
- resolve(msg);
49
- }
50
- }
51
- } catch {
52
- // server log lines on stderr only; stdout is always JSON-RPC
53
- }
54
- }
55
- nl = this.buffer.indexOf("\n");
56
- }
57
- });
58
-
59
- // Wait briefly for the server to be ready (writes a single info log to stderr).
60
- await new Promise<void>((resolve) => {
61
- const onData = (chunk: Buffer) => {
62
- if (chunk.toString("utf8").includes("ready")) {
63
- this.proc.stderr.off("data", onData);
64
- resolve();
65
- }
66
- };
67
- this.proc.stderr.on("data", onData);
68
- setTimeout(resolve, 2000); // hard cap
69
- });
70
- }
71
-
72
- async stop(): Promise<void> {
73
- this.proc.kill();
74
- await new Promise<void>((resolve) => this.proc.on("close", () => resolve()));
75
- }
76
-
77
- async send(method: string, params?: unknown, timeoutMs = 5000): Promise<JsonRpcMessage> {
78
- const id = this.nextId++;
79
- const req: JsonRpcMessage = { jsonrpc: "2.0", id, method, params };
80
- return new Promise((resolve, reject) => {
81
- const timer = setTimeout(() => {
82
- this.resolvers.delete(id);
83
- reject(new Error(`MCP request ${method} (id=${id}) timed out after ${timeoutMs}ms`));
84
- }, timeoutMs);
85
- this.resolvers.set(id, (msg) => {
86
- clearTimeout(timer);
87
- resolve(msg);
88
- });
89
- this.proc.stdin.write(JSON.stringify(req) + "\n");
90
- });
91
- }
92
- }
93
-
94
- describe("@mosadd/mcp — integration (real stdio)", () => {
95
- let client: McpClient;
96
-
97
- beforeEach(async () => {
98
- client = new McpClient();
99
- await client.start();
100
- });
101
-
102
- afterEach(async () => {
103
- await client.stop();
104
- });
105
-
106
- it("responds to initialize handshake", async () => {
107
- const resp = await client.send("initialize", {
108
- protocolVersion: "2024-11-05",
109
- capabilities: {},
110
- clientInfo: { name: "vitest", version: "1.0" },
111
- });
112
-
113
- expect(resp.error).toBeUndefined();
114
- const result = resp.result as {
115
- protocolVersion?: string;
116
- capabilities?: { tools?: unknown };
117
- serverInfo?: { name?: string };
118
- };
119
- expect(result.protocolVersion).toBe("2024-11-05");
120
- expect(result.capabilities?.tools).toBeDefined();
121
- expect(result.serverInfo?.name).toBe("mosadd");
122
- });
123
-
124
- it("lists all channel tools on tools/list", async () => {
125
- await client.send("initialize", {
126
- protocolVersion: "2024-11-05",
127
- capabilities: {},
128
- clientInfo: { name: "vitest", version: "1.0" },
129
- });
130
-
131
- const resp = await client.send("tools/list");
132
-
133
- expect(resp.error).toBeUndefined();
134
- const result = resp.result as { tools?: Array<{ name: string }> };
135
- const names = result.tools?.map((t) => t.name) ?? [];
136
-
137
- // All live channels surface their tools
138
- expect(names).toContain("mDM_send");
139
- expect(names).toContain("mIRC_create");
140
- expect(names).toContain("mURL_post"); // mURL revived module (2026-06-27)
141
- expect(names).toContain("mAYL_send"); // mAYL = email 3.0 (was mp0st); threat_catalog/threat_classify ARE registered (LINEAR-3498)
142
- expect(names).not.toContain("mp0st_send"); // mp0st_* aliases RETIRED 2026-07-15 — mAYL only
143
- expect(names).toContain("mTALK_press"); // mTALK PTT now shipped
144
- expect(names).toContain("mRAG_search"); // mRAG RAG-for-devs now shipped
145
- expect(names).toContain("mIRC_post_message"); // channel messaging now shipped
146
-
147
- // Total tool count today (grows as modules ship)
148
- expect(names.length).toBeGreaterThanOrEqual(40);
149
-
150
- // Every tool has a valid JSON Schema
151
- for (const tool of result.tools ?? []) {
152
- const t = tool as { name: string; description: string; inputSchema: { type?: string } };
153
- expect(t.description).toBeTruthy();
154
- expect(t.inputSchema?.type).toBe("object");
155
- }
156
- });
157
-
158
- it("returns an error envelope (not crash) when a tool handler throws", async () => {
159
- await client.send("initialize", {
160
- protocolVersion: "2024-11-05",
161
- capabilities: {},
162
- clientInfo: { name: "vitest", version: "1.0" },
163
- });
164
-
165
- // mDM_send to a nonexistent peer MUST fail — but as a normal `isError: true`
166
- // content block, not a JSON-RPC error (that would crash the agent loop).
167
- // The exact message depends on the machine: without credentials it's
168
- // MissingSupabaseEnvError, with a logged-in `mosadd login` session the call
169
- // reaches the real server and fails on the peer's missing prekey bundle.
170
- // Both are the correct envelope; asserting one exact message made the test
171
- // red on any machine with a live session (audyt 2026-08-27).
172
- const resp = await client.send("tools/call", {
173
- name: "mDM_send",
174
- arguments: { to: "11111111-1111-1111-1111-111111111111", text: "hi" },
175
- });
176
-
177
- expect(resp.error).toBeUndefined(); // JSON-RPC level OK
178
- const result = resp.result as { isError?: boolean; content?: Array<{ text?: string }> };
179
- expect(result.isError).toBe(true);
180
- expect(result.content?.[0]?.text ?? "").toMatch(/Missing|error/i);
181
- });
182
- });
1
+ /**
2
+ * Integration test — spawns the actual mcp binary as a child process,
3
+ * sends JSON-RPC over stdin, validates JSON-RPC responses on stdout.
4
+ *
5
+ * Catches regressions like the ZodObject.shape vs ._def.shape() incident
6
+ * (commit c237e86) that unit tests against allTools wouldn't have caught —
7
+ * the bug only surfaces when the MCP SDK's `McpServer.tool(...)` rejects
8
+ * the schema we pass.
9
+ */
10
+
11
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
12
+ import { join } from "node:path";
13
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
14
+
15
+ const MCP_BIN = join(__dirname, "..", "..", "dist", "bin", "mcp.js");
16
+
17
+ interface JsonRpcMessage {
18
+ jsonrpc: "2.0";
19
+ id?: number | string;
20
+ method?: string;
21
+ params?: unknown;
22
+ result?: unknown;
23
+ error?: { code: number; message: string };
24
+ }
25
+
26
+ class McpClient {
27
+ private proc!: ChildProcessWithoutNullStreams;
28
+ private buffer = "";
29
+ private resolvers = new Map<number | string, (msg: JsonRpcMessage) => void>();
30
+ private nextId = 1;
31
+
32
+ async start(): Promise<void> {
33
+ this.proc = spawn("node", [MCP_BIN], { stdio: ["pipe", "pipe", "pipe"] });
34
+
35
+ this.proc.stdout.on("data", (chunk: Buffer) => {
36
+ this.buffer += chunk.toString("utf8");
37
+ let nl = this.buffer.indexOf("\n");
38
+ while (nl !== -1) {
39
+ const line = this.buffer.slice(0, nl).trim();
40
+ this.buffer = this.buffer.slice(nl + 1);
41
+ if (line) {
42
+ try {
43
+ const msg = JSON.parse(line) as JsonRpcMessage;
44
+ if (msg.id !== undefined) {
45
+ const resolve = this.resolvers.get(msg.id);
46
+ if (resolve) {
47
+ this.resolvers.delete(msg.id);
48
+ resolve(msg);
49
+ }
50
+ }
51
+ } catch {
52
+ // server log lines on stderr only; stdout is always JSON-RPC
53
+ }
54
+ }
55
+ nl = this.buffer.indexOf("\n");
56
+ }
57
+ });
58
+
59
+ // Wait briefly for the server to be ready (writes a single info log to stderr).
60
+ await new Promise<void>((resolve) => {
61
+ const onData = (chunk: Buffer) => {
62
+ if (chunk.toString("utf8").includes("ready")) {
63
+ this.proc.stderr.off("data", onData);
64
+ resolve();
65
+ }
66
+ };
67
+ this.proc.stderr.on("data", onData);
68
+ setTimeout(resolve, 2000); // hard cap
69
+ });
70
+ }
71
+
72
+ async stop(): Promise<void> {
73
+ this.proc.kill();
74
+ await new Promise<void>((resolve) => this.proc.on("close", () => resolve()));
75
+ }
76
+
77
+ async send(method: string, params?: unknown, timeoutMs = 5000): Promise<JsonRpcMessage> {
78
+ const id = this.nextId++;
79
+ const req: JsonRpcMessage = { jsonrpc: "2.0", id, method, params };
80
+ return new Promise((resolve, reject) => {
81
+ const timer = setTimeout(() => {
82
+ this.resolvers.delete(id);
83
+ reject(new Error(`MCP request ${method} (id=${id}) timed out after ${timeoutMs}ms`));
84
+ }, timeoutMs);
85
+ this.resolvers.set(id, (msg) => {
86
+ clearTimeout(timer);
87
+ resolve(msg);
88
+ });
89
+ this.proc.stdin.write(JSON.stringify(req) + "\n");
90
+ });
91
+ }
92
+ }
93
+
94
+ describe("@mosadd/mcp — integration (real stdio)", () => {
95
+ let client: McpClient;
96
+
97
+ beforeEach(async () => {
98
+ client = new McpClient();
99
+ await client.start();
100
+ });
101
+
102
+ afterEach(async () => {
103
+ await client.stop();
104
+ });
105
+
106
+ it("responds to initialize handshake", async () => {
107
+ const resp = await client.send("initialize", {
108
+ protocolVersion: "2024-11-05",
109
+ capabilities: {},
110
+ clientInfo: { name: "vitest", version: "1.0" },
111
+ });
112
+
113
+ expect(resp.error).toBeUndefined();
114
+ const result = resp.result as {
115
+ protocolVersion?: string;
116
+ capabilities?: { tools?: unknown };
117
+ serverInfo?: { name?: string };
118
+ };
119
+ expect(result.protocolVersion).toBe("2024-11-05");
120
+ expect(result.capabilities?.tools).toBeDefined();
121
+ expect(result.serverInfo?.name).toBe("mosadd");
122
+ });
123
+
124
+ it("lists all channel tools on tools/list", async () => {
125
+ await client.send("initialize", {
126
+ protocolVersion: "2024-11-05",
127
+ capabilities: {},
128
+ clientInfo: { name: "vitest", version: "1.0" },
129
+ });
130
+
131
+ const resp = await client.send("tools/list");
132
+
133
+ expect(resp.error).toBeUndefined();
134
+ const result = resp.result as { tools?: Array<{ name: string }> };
135
+ const names = result.tools?.map((t) => t.name) ?? [];
136
+
137
+ // All live channels surface their tools
138
+ expect(names).toContain("mDM_send");
139
+ expect(names).toContain("mIRC_create");
140
+ expect(names).toContain("mURL_post"); // mURL revived module (2026-06-27)
141
+ expect(names).toContain("mAYL_send"); // mAYL = email 3.0 (was mp0st); threat_catalog/threat_classify ARE registered (LINEAR-3498)
142
+ expect(names).not.toContain("mp0st_send"); // mp0st_* aliases RETIRED 2026-07-15 — mAYL only
143
+ expect(names).toContain("mTALK_press"); // mTALK PTT now shipped
144
+ expect(names).toContain("mRAG_search"); // mRAG RAG-for-devs now shipped
145
+ expect(names).toContain("mIRC_post_message"); // channel messaging now shipped
146
+
147
+ // Total tool count today (grows as modules ship)
148
+ expect(names.length).toBeGreaterThanOrEqual(40);
149
+
150
+ // Every tool has a valid JSON Schema
151
+ for (const tool of result.tools ?? []) {
152
+ const t = tool as { name: string; description: string; inputSchema: { type?: string } };
153
+ expect(t.description).toBeTruthy();
154
+ expect(t.inputSchema?.type).toBe("object");
155
+ }
156
+ });
157
+
158
+ it("returns an error envelope (not crash) when a tool handler throws", async () => {
159
+ await client.send("initialize", {
160
+ protocolVersion: "2024-11-05",
161
+ capabilities: {},
162
+ clientInfo: { name: "vitest", version: "1.0" },
163
+ });
164
+
165
+ // mDM_send to a nonexistent peer MUST fail — but as a normal `isError: true`
166
+ // content block, not a JSON-RPC error (that would crash the agent loop).
167
+ // The exact message depends on the machine: without credentials it's
168
+ // MissingSupabaseEnvError, with a logged-in `mosadd login` session the call
169
+ // reaches the real server and fails on the peer's missing prekey bundle.
170
+ // Both are the correct envelope; asserting one exact message made the test
171
+ // red on any machine with a live session (audyt 2026-08-27).
172
+ const resp = await client.send("tools/call", {
173
+ name: "mDM_send",
174
+ arguments: { to: "11111111-1111-1111-1111-111111111111", text: "hi" },
175
+ });
176
+
177
+ expect(resp.error).toBeUndefined(); // JSON-RPC level OK
178
+ const result = resp.result as { isError?: boolean; content?: Array<{ text?: string }> };
179
+ expect(result.isError).toBe(true);
180
+ expect(result.content?.[0]?.text ?? "").toMatch(/Missing|error/i);
181
+ });
182
+ });
@@ -1,114 +1,114 @@
1
- /**
2
- * mRAG_ingest — what actually reaches rag-index.
3
- *
4
- * Two things are pinned here, both found by measuring production on 2026-08-14:
5
- *
6
- * 1. THE GRAPH FIELDS ARE FORWARDED. The knowledge graph builds its nodes from
7
- * metadata.sender / .recipient / .occurred_at and NOTHING else. This tool used to send only a
8
- * title, so a corpus could be fully indexed and mRAG_graph_overview still come back empty —
9
- * silently, with every call returning success. If these assertions ever go green-but-empty
10
- * again, that failure is back.
11
- *
12
- * 2. A NON-UUID source_id DOES NOT BLOW UP THE CALL. `user_embeddings.source_id` is a uuid column,
13
- * so passing the natural thing (a path, a case number) made the whole ingest fail with an
14
- * opaque "rag-index (500): Internal error". Non-UUIDs are folded into a deterministic UUIDv5;
15
- * real UUIDs pass through untouched.
16
- */
17
-
18
- import { describe, it, expect, vi, beforeEach } from "vitest";
19
-
20
- const sent: Record<string, unknown>[] = [];
21
-
22
- vi.mock("../providers/supabase.js", () => ({
23
- readSupabaseEnv: () => ({ url: "https://example.supabase.co", anonKey: "anon", userJwt: "jwt" }),
24
- invokeFunction: (_fn: string, body: Record<string, unknown>) => {
25
- sent.push(body);
26
- return Promise.resolve({ indexed: 1, chunk_count: 1 });
27
- },
28
- }));
29
-
30
- const { knowledgeTools } = await import("../tools/knowledge.js");
31
- const ingest = knowledgeTools.find((t) => t.name === "mRAG_ingest")!;
32
- const ctx = { log: () => {} } as never;
33
- const call = (input: Record<string, unknown>) => ingest.handler(input, ctx);
34
- const last = () => sent[sent.length - 1];
35
-
36
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
37
-
38
- describe("mRAG_ingest", () => {
39
- beforeEach(() => {
40
- sent.length = 0;
41
- });
42
-
43
- it("forwards the parties and the event date as TOP-LEVEL fields (where rag-index reads them)", async () => {
44
- await call({
45
- content_text: "Pismo procesowe.",
46
- sender: { kind: "email", ref: "kancelaria@example.invalid", label: "Kancelaria" },
47
- recipient: { kind: "unknown", ref: "sad-rejonowy", label: "Sąd Rejonowy" },
48
- occurred_at: "2019-03-11T10:00:00.000Z",
49
- direction: "in",
50
- labels: ["M-01"],
51
- name: "pozew.pdf",
52
- mime: "application/pdf",
53
- size: 1234,
54
- });
55
- expect(last()).toMatchObject({
56
- sender: { kind: "email", ref: "kancelaria@example.invalid" },
57
- recipient: { kind: "unknown", ref: "sad-rejonowy" },
58
- occurred_at: "2019-03-11T10:00:00.000Z",
59
- direction: "in",
60
- labels: ["M-01"],
61
- name: "pozew.pdf",
62
- mime: "application/pdf",
63
- size: 1234,
64
- });
65
- });
66
-
67
- it("keeps caller metadata AND the title, without dropping either", async () => {
68
- await call({
69
- content_text: "x",
70
- title: "Pozew z 11.03.2019",
71
- metadata: { case_id: "M-01", jurisdiction: "PL", pii_flag: true },
72
- });
73
- expect(last().metadata).toMatchObject({
74
- case_id: "M-01",
75
- jurisdiction: "PL",
76
- pii_flag: true,
77
- title: "Pozew z 11.03.2019",
78
- ingested_via: "mRAG_ingest",
79
- });
80
- });
81
-
82
- it("a caller that passes nothing extra sends the same request shape as before", async () => {
83
- await call({ content_text: "x", source_type: "note" });
84
- expect(last()).toEqual({
85
- source_type: "file", // "note" maps to "file" backend-side, unchanged behaviour
86
- source_id: null,
87
- thread_id: null,
88
- content_text: "x",
89
- metadata: { ingested_via: "mRAG_ingest" },
90
- });
91
- });
92
-
93
- it("folds a non-UUID source_id into a stable uuid and keeps the original visible", async () => {
94
- await call({ content_text: "x", source_id: "C:/LAW/M-01/pozew.pdf" });
95
- const id = last().source_id as string;
96
- expect(id).toMatch(UUID_RE);
97
- expect(last().metadata).toMatchObject({ source_ref: "C:/LAW/M-01/pozew.pdf" });
98
-
99
- // Deterministic: the same document re-ingested groups with itself rather than forking.
100
- await call({ content_text: "y", source_id: "C:/LAW/M-01/pozew.pdf" });
101
- expect(last().source_id).toBe(id);
102
-
103
- // …and a different document does not collide with it.
104
- await call({ content_text: "z", source_id: "C:/LAW/M-01/odpowiedz.pdf" });
105
- expect(last().source_id).not.toBe(id);
106
- });
107
-
108
- it("passes a real UUID through untouched, with no rewrite marker", async () => {
109
- const uuid = "b228b6ae-dda6-4823-9882-40ea91ed1530";
110
- await call({ content_text: "x", source_id: uuid });
111
- expect(last().source_id).toBe(uuid);
112
- expect(last().metadata).not.toHaveProperty("source_ref");
113
- });
114
- });
1
+ /**
2
+ * mRAG_ingest — what actually reaches rag-index.
3
+ *
4
+ * Two things are pinned here, both found by measuring production on 2026-08-14:
5
+ *
6
+ * 1. THE GRAPH FIELDS ARE FORWARDED. The knowledge graph builds its nodes from
7
+ * metadata.sender / .recipient / .occurred_at and NOTHING else. This tool used to send only a
8
+ * title, so a corpus could be fully indexed and mRAG_graph_overview still come back empty —
9
+ * silently, with every call returning success. If these assertions ever go green-but-empty
10
+ * again, that failure is back.
11
+ *
12
+ * 2. A NON-UUID source_id DOES NOT BLOW UP THE CALL. `user_embeddings.source_id` is a uuid column,
13
+ * so passing the natural thing (a path, a case number) made the whole ingest fail with an
14
+ * opaque "rag-index (500): Internal error". Non-UUIDs are folded into a deterministic UUIDv5;
15
+ * real UUIDs pass through untouched.
16
+ */
17
+
18
+ import { describe, it, expect, vi, beforeEach } from "vitest";
19
+
20
+ const sent: Record<string, unknown>[] = [];
21
+
22
+ vi.mock("../providers/supabase.js", () => ({
23
+ readSupabaseEnv: () => ({ url: "https://example.supabase.co", anonKey: "anon", userJwt: "jwt" }),
24
+ invokeFunction: (_fn: string, body: Record<string, unknown>) => {
25
+ sent.push(body);
26
+ return Promise.resolve({ indexed: 1, chunk_count: 1 });
27
+ },
28
+ }));
29
+
30
+ const { knowledgeTools } = await import("../tools/knowledge.js");
31
+ const ingest = knowledgeTools.find((t) => t.name === "mRAG_ingest")!;
32
+ const ctx = { log: () => {} } as never;
33
+ const call = (input: Record<string, unknown>) => ingest.handler(input, ctx);
34
+ const last = () => sent[sent.length - 1];
35
+
36
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
37
+
38
+ describe("mRAG_ingest", () => {
39
+ beforeEach(() => {
40
+ sent.length = 0;
41
+ });
42
+
43
+ it("forwards the parties and the event date as TOP-LEVEL fields (where rag-index reads them)", async () => {
44
+ await call({
45
+ content_text: "Pismo procesowe.",
46
+ sender: { kind: "email", ref: "kancelaria@example.invalid", label: "Kancelaria" },
47
+ recipient: { kind: "unknown", ref: "sad-rejonowy", label: "Sąd Rejonowy" },
48
+ occurred_at: "2019-03-11T10:00:00.000Z",
49
+ direction: "in",
50
+ labels: ["M-01"],
51
+ name: "pozew.pdf",
52
+ mime: "application/pdf",
53
+ size: 1234,
54
+ });
55
+ expect(last()).toMatchObject({
56
+ sender: { kind: "email", ref: "kancelaria@example.invalid" },
57
+ recipient: { kind: "unknown", ref: "sad-rejonowy" },
58
+ occurred_at: "2019-03-11T10:00:00.000Z",
59
+ direction: "in",
60
+ labels: ["M-01"],
61
+ name: "pozew.pdf",
62
+ mime: "application/pdf",
63
+ size: 1234,
64
+ });
65
+ });
66
+
67
+ it("keeps caller metadata AND the title, without dropping either", async () => {
68
+ await call({
69
+ content_text: "x",
70
+ title: "Pozew z 11.03.2019",
71
+ metadata: { case_id: "M-01", jurisdiction: "PL", pii_flag: true },
72
+ });
73
+ expect(last().metadata).toMatchObject({
74
+ case_id: "M-01",
75
+ jurisdiction: "PL",
76
+ pii_flag: true,
77
+ title: "Pozew z 11.03.2019",
78
+ ingested_via: "mRAG_ingest",
79
+ });
80
+ });
81
+
82
+ it("a caller that passes nothing extra sends the same request shape as before", async () => {
83
+ await call({ content_text: "x", source_type: "note" });
84
+ expect(last()).toEqual({
85
+ source_type: "file", // "note" maps to "file" backend-side, unchanged behaviour
86
+ source_id: null,
87
+ thread_id: null,
88
+ content_text: "x",
89
+ metadata: { ingested_via: "mRAG_ingest" },
90
+ });
91
+ });
92
+
93
+ it("folds a non-UUID source_id into a stable uuid and keeps the original visible", async () => {
94
+ await call({ content_text: "x", source_id: "C:/LAW/M-01/pozew.pdf" });
95
+ const id = last().source_id as string;
96
+ expect(id).toMatch(UUID_RE);
97
+ expect(last().metadata).toMatchObject({ source_ref: "C:/LAW/M-01/pozew.pdf" });
98
+
99
+ // Deterministic: the same document re-ingested groups with itself rather than forking.
100
+ await call({ content_text: "y", source_id: "C:/LAW/M-01/pozew.pdf" });
101
+ expect(last().source_id).toBe(id);
102
+
103
+ // …and a different document does not collide with it.
104
+ await call({ content_text: "z", source_id: "C:/LAW/M-01/odpowiedz.pdf" });
105
+ expect(last().source_id).not.toBe(id);
106
+ });
107
+
108
+ it("passes a real UUID through untouched, with no rewrite marker", async () => {
109
+ const uuid = "b228b6ae-dda6-4823-9882-40ea91ed1530";
110
+ await call({ content_text: "x", source_id: uuid });
111
+ expect(last().source_id).toBe(uuid);
112
+ expect(last().metadata).not.toHaveProperty("source_ref");
113
+ });
114
+ });