@mosadd/mcp 3.0.0-alpha.46 → 3.0.0-alpha.48

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/dist/bin/mcp.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  createMosaddServer
4
- } from "../chunk-STWB7DEK.js";
4
+ } from "../chunk-MGF7BV3M.js";
5
5
  import {
6
6
  isSessionExpired,
7
7
  loadSession,
@@ -93,13 +93,30 @@ async function invokeFunction(fn, body) {
93
93
  const raw = await res.text();
94
94
  if (raw) {
95
95
  let detail = raw;
96
+ let recipe = "";
96
97
  try {
97
98
  const parsed = JSON.parse(raw);
98
99
  detail = typeof parsed.error === "string" && parsed.error || typeof parsed.message === "string" && parsed.message || raw;
100
+ const steps = Array.isArray(parsed.next_steps) ? parsed.next_steps : [];
101
+ const lines = [];
102
+ if (typeof parsed.code === "string" && parsed.code) lines.push(`code: ${parsed.code}`);
103
+ if (typeof parsed.message_en === "string" && parsed.message_en && parsed.message_en !== detail) {
104
+ lines.push(parsed.message_en);
105
+ }
106
+ for (const raw_step of steps) {
107
+ const step = raw_step;
108
+ const who = typeof step.actor === "string" ? step.actor : "?";
109
+ const what = typeof step.tool === "string" && step.tool || typeof step.ui === "string" && step.ui || "";
110
+ if (!what) continue;
111
+ const why = typeof step.why === "string" ? ` \u2014 ${step.why}` : "";
112
+ const args = step.args && typeof step.args === "object" ? ` ${JSON.stringify(step.args)}` : "";
113
+ lines.push(`next (${who}): ${what}${args}${why}`);
114
+ }
115
+ if (lines.length) recipe = "\n" + lines.join("\n");
99
116
  } catch {
100
117
  }
101
118
  const status = typeof res.status === "number" ? res.status : void 0;
102
- msg = status ? `${fn} (${status}): ${detail}` : `${fn}: ${detail}`;
119
+ msg = (status ? `${fn} (${status}): ${detail}` : `${fn}: ${detail}`) + recipe;
103
120
  }
104
121
  } catch {
105
122
  }
@@ -115,6 +132,19 @@ async function invokeFunction(fn, body) {
115
132
  // src/tools/mdm.ts
116
133
  import { z } from "zod";
117
134
 
135
+ // src/tools/voice-format.ts
136
+ function formatVoiceIfAny(text) {
137
+ try {
138
+ const obj = JSON.parse(text);
139
+ if (obj && typeof obj === "object" && typeof obj.audio === "string" && obj.audio.length > 1e3 && typeof obj.dur === "number") {
140
+ const s = Math.max(1, Math.round(obj.dur / 1e3));
141
+ return `[voice note \u2014 ${s}s]`;
142
+ }
143
+ } catch {
144
+ }
145
+ return text;
146
+ }
147
+
118
148
  // src/crypto/mdm-session.ts
119
149
  import {
120
150
  decryptBytes,
@@ -531,18 +561,18 @@ async function mDM_list(input, ctx) {
531
561
  thread_id: m.threadId
532
562
  };
533
563
  if (!isE2eeEnvelope(m.payload)) {
534
- return { ...base, text: unpackPayload(m.payload).text, encrypted: false };
564
+ return { ...base, text: formatVoiceIfAny(unpackPayload(m.payload).text), encrypted: false };
535
565
  }
536
566
  if (m.senderId === selfId) {
537
567
  const cached = await ctx.providers.keys.getSentMessage?.(m.id);
538
568
  if (cached) {
539
- return { ...base, text: unpackPayload(cached).text, encrypted: true };
569
+ return { ...base, text: formatVoiceIfAny(unpackPayload(cached).text), encrypted: true };
540
570
  }
541
571
  return { ...base, text: "<encrypted \xB7 sent by you>", encrypted: true };
542
572
  }
543
573
  try {
544
574
  const inner = await decryptFromPeer(ctx.providers.keys, m.senderId, m.payload);
545
- return { ...base, text: unpackPayload(inner).text, encrypted: true };
575
+ return { ...base, text: formatVoiceIfAny(unpackPayload(inner).text), encrypted: true };
546
576
  } catch (err) {
547
577
  ctx.log("warn", "mDM_list failed to decrypt a message", { id: m.id, error: String(err) });
548
578
  return { ...base, text: "<undecryptable>", encrypted: true };
@@ -1369,7 +1399,7 @@ async function mIRC_list_messages(input, ctx) {
1369
1399
  messages: (data?.messages ?? []).map((m) => ({
1370
1400
  id: m.id,
1371
1401
  sender_identity_id: m.sender_identity_id,
1372
- text: unpackPayload2(m.encrypted_payload).text,
1402
+ text: formatVoiceIfAny(unpackPayload2(m.encrypted_payload).text),
1373
1403
  timestamp: m.created_at
1374
1404
  })),
1375
1405
  next_cursor: data?.next_before ?? data?.cursor ?? null
@@ -2715,7 +2745,14 @@ async function comms_session_attach(input, ctx) {
2715
2745
  const { error } = await sb.from("agent_bridge_heartbeat").delete().eq("identity_id", id);
2716
2746
  if (error) throw new Error(`Could not release the line: ${error.message}`);
2717
2747
  }
2718
- await sb.from("mosadd_gateway_agent_binding").delete().eq("user_id", self.user_id).eq("session_id", sessionId());
2748
+ const { error: relError } = await sb.rpc("mosadd_gateway_binding_release", {
2749
+ p_session_id: sessionId()
2750
+ });
2751
+ if (relError) {
2752
+ ctx.log("warn", "comms_session_attach: release RPC failed, line will lapse on its own", {
2753
+ error: relError.message
2754
+ });
2755
+ }
2719
2756
  processBindings.delete(self.user_id);
2720
2757
  ctx.log("info", "comms_session_attach: released", { identity_ids: [...toRelease] });
2721
2758
  return {
@@ -2729,6 +2766,7 @@ async function comms_session_attach(input, ctx) {
2729
2766
  const mode = "mcp-session";
2730
2767
  let lineId = self.id;
2731
2768
  let speakingAs;
2769
+ let przejeteOd;
2732
2770
  if (input.as_agent) {
2733
2771
  const agent = await resolveOwnedAgentLine(env, self.user_id, input.as_agent);
2734
2772
  if (!agent) {
@@ -2738,24 +2776,20 @@ async function comms_session_attach(input, ctx) {
2738
2776
  }
2739
2777
  lineId = agent.id;
2740
2778
  speakingAs = { identity_id: agent.id, address: agent.m0ssad_email, display_name: agent.display_name };
2741
- const { error: bindError } = await sb.from("mosadd_gateway_agent_binding").upsert(
2742
- {
2743
- user_id: self.user_id,
2744
- // ⛔ CZYJA TO DEKLARACJA (2026-08-27). Wiersz jest nadal JEDEN na konto — pełna izolacja
2745
- // wymaga, by żaden żywy klient nie zapisywał już przez ON CONFLICT (user_id), a takie
2746
- // klienty jeszcze chodzą (próba zdjęcia tej unikalności zablokowała im wpinanie
2747
- // całkowicie, więc została natychmiast cofnięta). Zapisany `session_id` pozwala jednak
2748
- // bramie ROZPOZNAĆ, że deklarację przejęła inna sesja, i powiedzieć to wprost zamiast po
2749
- // cichu podpisywać posty cudzą linią.
2750
- session_id: sessionId(),
2751
- agent_identity_id: agent.id,
2752
- agent_address: agent.m0ssad_email,
2753
- bound_at: (/* @__PURE__ */ new Date()).toISOString(),
2754
- bound_by_host: host
2755
- },
2756
- { onConflict: "user_id" }
2757
- );
2779
+ const { data: claim, error: bindError } = await sb.rpc("mosadd_gateway_binding_claim", {
2780
+ p_session_id: sessionId(),
2781
+ p_agent_identity_id: agent.id,
2782
+ p_agent_address: agent.m0ssad_email,
2783
+ p_host: host
2784
+ });
2758
2785
  if (bindError) throw new Error(`Could not declare the agent line: ${bindError.message}`);
2786
+ const wynik = claim ?? {};
2787
+ przejeteOd = wynik.took_over ? wynik.previous_session_id ?? null : void 0;
2788
+ if (wynik.took_over) {
2789
+ ctx.log("warn", "comms_session_attach: TOOK OVER the line from another session", {
2790
+ previous_session_id: wynik.previous_session_id ?? null
2791
+ });
2792
+ }
2759
2793
  processBindings.set(self.user_id, agent.id);
2760
2794
  }
2761
2795
  stopAttachment(lineId);
@@ -2773,6 +2807,7 @@ async function comms_session_attach(input, ctx) {
2773
2807
  ...speakingAs ? { speaking_as: speakingAs } : {},
2774
2808
  host,
2775
2809
  holds_for_seconds: HOLD_SECONDS,
2810
+ ...przejeteOd !== void 0 ? { took_over: true, previous_session_id: przejeteOd } : {},
2776
2811
  note: speakingAs ? `This session now speaks for ${speakingAs.address ?? speakingAs.identity_id}: channel posts sent through this gateway are signed as that agent automatically (an explicit \`agent\` field still wins), and the agent's cloud stand-in defers to you while the session runs. Call again with release:true to hand it back.` : "This session now owns the account's reply lane; the cloud stand-in will not answer while it is held. The hold renews itself for as long as this process runs and lapses on its own if the session dies. Call again with release:true to hand it back immediately."
2777
2812
  };
2778
2813
  }
@@ -3280,7 +3315,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3280
3315
  // package.json
3281
3316
  var package_default = {
3282
3317
  name: "@mosadd/mcp",
3283
- version: "3.0.0-alpha.45",
3318
+ version: "3.0.0-alpha.48",
3284
3319
  mcpName: "io.github.hei33enberg/mosadd-mcp",
3285
3320
  description: "Model Context Protocol server for mosadd. Exposes 4 modules (mDM, mIRC, mURL, mAYL) and capabilities (mTALK, mRAG) plus comms agent-actions \u2014 85 tools \u2014 to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
3286
3321
  homepage: "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  createMosaddServer,
5
5
  defaultProviders,
6
6
  runWithSupabaseEnv
7
- } from "./chunk-STWB7DEK.js";
7
+ } from "./chunk-MGF7BV3M.js";
8
8
  import "./chunk-Z7WR52GE.js";
9
9
  export {
10
10
  TOOL_COUNT,
package/package.json CHANGED
@@ -1,73 +1,73 @@
1
- {
2
- "name": "@mosadd/mcp",
3
- "version": "3.0.0-alpha.46",
4
- "mcpName": "io.github.hei33enberg/mosadd-mcp",
5
- "description": "Model Context Protocol server for mosadd. Exposes 4 modules (mDM, mIRC, mURL, mAYL) and capabilities (mTALK, mRAG) plus comms agent-actions — 85 tools — to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
6
- "homepage": "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
7
- "repository": {
8
- "type": "git",
9
- "url": "https://github.com/Hei33enberg/mosADD-OS.git",
10
- "directory": "packages/mcp"
11
- },
12
- "license": "Apache-2.0",
13
- "type": "module",
14
- "main": "./dist/index.js",
15
- "module": "./dist/index.js",
16
- "types": "./dist/index.d.ts",
17
- "exports": {
18
- ".": {
19
- "types": "./dist/index.d.ts",
20
- "import": "./dist/index.js"
21
- }
22
- },
23
- "bin": {
24
- "mosadd-mcp": "./dist/bin/mcp.js",
25
- "mosadd": "./dist/bin/mcp.js"
26
- },
27
- "files": [
28
- "dist",
29
- "src",
30
- "README.md",
31
- "CHANGELOG.md",
32
- "LICENSE"
33
- ],
34
- "publishConfig": {
35
- "access": "public"
36
- },
37
- "dependencies": {
38
- "@modelcontextprotocol/sdk": "^1.0.4",
39
- "@supabase/supabase-js": "^2.48.0",
40
- "zod": "^4.3.6",
41
- "@mosadd/threat-engine": "3.0.0-alpha.28",
42
- "@mosadd/crypto": "3.0.0-alpha.27",
43
- "@mosadd/providers": "3.0.0-alpha.27",
44
- "@mosadd/protocol": "3.0.0-alpha.28"
45
- },
46
- "devDependencies": {
47
- "tsup": "^8.3.5",
48
- "tsx": "^4.19.2",
49
- "typescript": "^5.7.2",
50
- "vitest": "^2.1.8"
51
- },
52
- "keywords": [
53
- "mosadd",
54
- "mcp",
55
- "model-context-protocol",
56
- "agent",
57
- "claude",
58
- "cursor",
59
- "anthropic",
60
- "communication",
61
- "messaging"
62
- ],
63
- "engines": {
64
- "node": ">=18"
65
- },
66
- "scripts": {
67
- "build": "tsup src/index.ts src/bin/mcp.ts src/bin/login.ts --format esm --dts --clean --shims",
68
- "dev": "tsx src/bin/mcp.ts",
69
- "test": "vitest run",
70
- "typecheck": "tsc -p tsconfig.json --noEmit",
71
- "clean": "rm -rf dist .turbo"
72
- }
73
- }
1
+ {
2
+ "name": "@mosadd/mcp",
3
+ "version": "3.0.0-alpha.48",
4
+ "mcpName": "io.github.hei33enberg/mosadd-mcp",
5
+ "description": "Model Context Protocol server for mosadd. Exposes 4 modules (mDM, mIRC, mURL, mAYL) and capabilities (mTALK, mRAG) plus comms agent-actions — 85 tools — to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
6
+ "homepage": "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/Hei33enberg/mosADD-OS.git",
10
+ "directory": "packages/mcp"
11
+ },
12
+ "license": "Apache-2.0",
13
+ "type": "module",
14
+ "main": "./dist/index.js",
15
+ "module": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ }
22
+ },
23
+ "bin": {
24
+ "mosadd-mcp": "./dist/bin/mcp.js",
25
+ "mosadd": "./dist/bin/mcp.js"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "src",
30
+ "README.md",
31
+ "CHANGELOG.md",
32
+ "LICENSE"
33
+ ],
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "scripts": {
38
+ "build": "tsup src/index.ts src/bin/mcp.ts src/bin/login.ts --format esm --dts --clean --shims",
39
+ "dev": "tsx src/bin/mcp.ts",
40
+ "test": "vitest run",
41
+ "typecheck": "tsc -p tsconfig.json --noEmit",
42
+ "clean": "rm -rf dist .turbo"
43
+ },
44
+ "dependencies": {
45
+ "@modelcontextprotocol/sdk": "^1.0.4",
46
+ "@mosadd/crypto": "workspace:*",
47
+ "@mosadd/protocol": "workspace:*",
48
+ "@mosadd/providers": "workspace:*",
49
+ "@mosadd/threat-engine": "workspace:*",
50
+ "@supabase/supabase-js": "^2.48.0",
51
+ "zod": "^4.3.6"
52
+ },
53
+ "devDependencies": {
54
+ "tsup": "^8.3.5",
55
+ "tsx": "^4.19.2",
56
+ "typescript": "^5.7.2",
57
+ "vitest": "^2.1.8"
58
+ },
59
+ "keywords": [
60
+ "mosadd",
61
+ "mcp",
62
+ "model-context-protocol",
63
+ "agent",
64
+ "claude",
65
+ "cursor",
66
+ "anthropic",
67
+ "communication",
68
+ "messaging"
69
+ ],
70
+ "engines": {
71
+ "node": ">=18"
72
+ }
73
+ }
@@ -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
+ });