@totalreclaw/mcp-server 2.6.1 → 3.0.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.
Files changed (62) hide show
  1. package/README.md +47 -7
  2. package/dist/claims-helper.d.ts +79 -31
  3. package/dist/claims-helper.d.ts.map +1 -1
  4. package/dist/claims-helper.js +125 -45
  5. package/dist/claims-helper.js.map +1 -1
  6. package/dist/consolidation.d.ts +10 -7
  7. package/dist/consolidation.d.ts.map +1 -1
  8. package/dist/consolidation.js +105 -32
  9. package/dist/consolidation.js.map +1 -1
  10. package/dist/index.js +177 -40
  11. package/dist/index.js.map +1 -1
  12. package/dist/prompts.d.ts +13 -13
  13. package/dist/prompts.d.ts.map +1 -1
  14. package/dist/prompts.js +111 -178
  15. package/dist/prompts.js.map +1 -1
  16. package/dist/subgraph/store.d.ts +5 -2
  17. package/dist/subgraph/store.d.ts.map +1 -1
  18. package/dist/subgraph/store.js +6 -3
  19. package/dist/subgraph/store.js.map +1 -1
  20. package/dist/tools/consolidate.js +12 -12
  21. package/dist/tools/consolidate.js.map +1 -1
  22. package/dist/tools/debrief.d.ts.map +1 -1
  23. package/dist/tools/debrief.js +11 -3
  24. package/dist/tools/debrief.js.map +1 -1
  25. package/dist/tools/export.d.ts.map +1 -1
  26. package/dist/tools/export.js +61 -12
  27. package/dist/tools/export.js.map +1 -1
  28. package/dist/tools/forget.d.ts +14 -0
  29. package/dist/tools/forget.d.ts.map +1 -1
  30. package/dist/tools/forget.js +8 -2
  31. package/dist/tools/forget.js.map +1 -1
  32. package/dist/tools/import-batch.d.ts.map +1 -1
  33. package/dist/tools/import-batch.js +10 -3
  34. package/dist/tools/import-batch.js.map +1 -1
  35. package/dist/tools/index.d.ts +2 -0
  36. package/dist/tools/index.d.ts.map +1 -1
  37. package/dist/tools/index.js +15 -1
  38. package/dist/tools/index.js.map +1 -1
  39. package/dist/tools/pin.d.ts +8 -0
  40. package/dist/tools/pin.d.ts.map +1 -1
  41. package/dist/tools/pin.js +44 -12
  42. package/dist/tools/pin.js.map +1 -1
  43. package/dist/tools/recall.d.ts.map +1 -1
  44. package/dist/tools/recall.js +63 -10
  45. package/dist/tools/recall.js.map +1 -1
  46. package/dist/tools/remember.d.ts +44 -3
  47. package/dist/tools/remember.d.ts.map +1 -1
  48. package/dist/tools/remember.js +97 -10
  49. package/dist/tools/remember.js.map +1 -1
  50. package/dist/tools/retype.d.ts +119 -0
  51. package/dist/tools/retype.d.ts.map +1 -0
  52. package/dist/tools/retype.js +360 -0
  53. package/dist/tools/retype.js.map +1 -0
  54. package/dist/tools/set-scope.d.ts +57 -0
  55. package/dist/tools/set-scope.d.ts.map +1 -0
  56. package/dist/tools/set-scope.js +118 -0
  57. package/dist/tools/set-scope.js.map +1 -0
  58. package/dist/v1-types.d.ts +79 -0
  59. package/dist/v1-types.d.ts.map +1 -0
  60. package/dist/v1-types.js +104 -0
  61. package/dist/v1-types.js.map +1 -0
  62. package/package.json +2 -2
@@ -12,11 +12,13 @@
12
12
  * 3. Bulk consolidation — cluster all facts in the vault and identify
13
13
  * groups of near-duplicates for cleanup (clusterFacts).
14
14
  *
15
- * This module intentionally has minimal dependencies (only reranker for
16
- * cosineSimilarity) so it can be tested without pulling in the full
17
- * server dependency graph.
15
+ * Delegates core computation to `@totalreclaw/core` Rust WASM module where
16
+ * bindings are available. `shouldSupersede` uses the core directly.
17
+ * `findNearDuplicate` and `clusterFacts` use the core's `findBestNearDuplicate`
18
+ * and `clusterFacts` WASM functions when available, falling back to local
19
+ * implementations that use WASM-backed `cosineSimilarity`.
18
20
  *
19
- * Ported from skill/plugin/consolidation.ts — adapted for MCP server.
21
+ * Threshold helpers remain local (they read process.env).
20
22
  */
21
23
  Object.defineProperty(exports, "__esModule", { value: true });
22
24
  exports.STORE_DEDUP_MAX_CANDIDATES = void 0;
@@ -27,6 +29,18 @@ exports.shouldSupersede = shouldSupersede;
27
29
  exports.clusterFacts = clusterFacts;
28
30
  const reranker_js_1 = require("./subgraph/reranker.js");
29
31
  // ---------------------------------------------------------------------------
32
+ // Lazy-load WASM core (same pattern as claims-helper.ts)
33
+ // ---------------------------------------------------------------------------
34
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
35
+ let _wasm = null;
36
+ function getWasm() {
37
+ if (!_wasm) {
38
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
39
+ _wasm = require('@totalreclaw/core');
40
+ }
41
+ return _wasm;
42
+ }
43
+ // ---------------------------------------------------------------------------
30
44
  // Configuration
31
45
  // ---------------------------------------------------------------------------
32
46
  /**
@@ -79,6 +93,24 @@ exports.STORE_DEDUP_MAX_CANDIDATES = 200;
79
93
  * @returns - Best match above threshold, or null
80
94
  */
81
95
  function findNearDuplicate(newFactEmbedding, candidates, threshold) {
96
+ const wasm = getWasm();
97
+ // Use core's findBestNearDuplicate if available (added in core >=1.5.0).
98
+ if (typeof wasm.findBestNearDuplicate === 'function') {
99
+ const existing = candidates
100
+ .filter((c) => c.embedding && c.embedding.length > 0)
101
+ .map((c) => ({ id: c.id, embedding: c.embedding }));
102
+ if (existing.length === 0)
103
+ return null;
104
+ const resultJs = wasm.findBestNearDuplicate(JSON.stringify(newFactEmbedding), JSON.stringify(existing), threshold);
105
+ if (resultJs == null)
106
+ return null;
107
+ const result = typeof resultJs === 'string' ? JSON.parse(resultJs) : resultJs;
108
+ const matched = candidates.find((c) => c.id === result.fact_id);
109
+ if (!matched)
110
+ return null;
111
+ return { existingFact: matched, similarity: result.similarity };
112
+ }
113
+ // Fallback: local loop using WASM-backed cosineSimilarity.
82
114
  let bestMatch = null;
83
115
  for (const candidate of candidates) {
84
116
  if (!candidate.embedding || candidate.embedding.length === 0)
@@ -106,39 +138,19 @@ function findNearDuplicate(newFactEmbedding, candidates, threshold) {
106
138
  * @returns - 'supersede' if new fact should replace, 'skip' otherwise
107
139
  */
108
140
  function shouldSupersede(newImportance, existingFact) {
109
- if (newImportance >= existingFact.importance)
110
- return 'supersede';
111
- return 'skip';
141
+ const wasm = getWasm();
142
+ return wasm.shouldSupersede(newImportance, existingFact.importance) ? 'supersede' : 'skip';
112
143
  }
113
144
  // ---------------------------------------------------------------------------
114
145
  // Bulk consolidation
115
146
  // ---------------------------------------------------------------------------
116
- /**
117
- * Pick the best representative from a group of near-duplicate facts.
118
- *
119
- * Tiebreak order:
120
- * 1. Highest decayScore
121
- * 2. Most recent (highest createdAt)
122
- * 3. Longest text
123
- */
124
- function pickRepresentative(facts) {
125
- let best = facts[0];
126
- for (let i = 1; i < facts.length; i++) {
127
- const f = facts[i];
128
- if (f.decayScore > best.decayScore ||
129
- (f.decayScore === best.decayScore && f.createdAt > best.createdAt) ||
130
- (f.decayScore === best.decayScore && f.createdAt === best.createdAt && f.text.length > best.text.length)) {
131
- best = f;
132
- }
133
- }
134
- return best;
135
- }
136
147
  /**
137
148
  * Cluster facts by semantic similarity using greedy single-pass clustering.
138
149
  *
139
- * For each fact (in order), assigns it to the first existing cluster whose
140
- * representative has cosine similarity >= threshold. If no cluster matches,
141
- * a new cluster is started.
150
+ * Delegates to `@totalreclaw/core` WASM `clusterFacts` which performs the
151
+ * same greedy single-pass algorithm and representative selection. The WASM
152
+ * function returns ID-only clusters; this wrapper maps IDs back to full
153
+ * `DecryptedCandidate` objects for callers.
142
154
  *
143
155
  * Only returns clusters that have duplicates (i.e. more than one member).
144
156
  * Facts without embeddings are not clustered.
@@ -148,13 +160,52 @@ function pickRepresentative(facts) {
148
160
  * @returns - Clusters with duplicates (representative + duplicates)
149
161
  */
150
162
  function clusterFacts(facts, threshold) {
163
+ const wasm = getWasm();
164
+ // Use core's clusterFacts if available (added in core >=1.5.0).
165
+ if (typeof wasm.clusterFacts === 'function') {
166
+ // Build ConsolidationCandidate JSON for WASM (snake_case fields).
167
+ const wasmCandidates = facts
168
+ .filter((f) => f.embedding && f.embedding.length > 0)
169
+ .map((f) => ({
170
+ id: f.id,
171
+ text: f.text,
172
+ embedding: f.embedding,
173
+ importance: f.importance,
174
+ decay_score: f.decayScore,
175
+ created_at: f.createdAt,
176
+ version: f.version,
177
+ }));
178
+ if (wasmCandidates.length === 0)
179
+ return [];
180
+ const resultJs = wasm.clusterFacts(JSON.stringify(wasmCandidates), threshold);
181
+ // WASM returns a JSON string: [{ representative: string, duplicates: string[] }]
182
+ const wasmClusters = typeof resultJs === 'string' ? JSON.parse(resultJs) : resultJs;
183
+ // Build a lookup map for fast ID -> DecryptedCandidate resolution.
184
+ const byId = new Map();
185
+ for (const f of facts)
186
+ byId.set(f.id, f);
187
+ // Map ID-only clusters back to full DecryptedCandidate objects.
188
+ const result = [];
189
+ for (const wc of wasmClusters) {
190
+ const rep = byId.get(wc.representative);
191
+ if (!rep)
192
+ continue;
193
+ const dups = wc.duplicates
194
+ .map((id) => byId.get(id))
195
+ .filter((d) => d !== undefined);
196
+ if (dups.length > 0) {
197
+ result.push({ representative: rep, duplicates: dups });
198
+ }
199
+ }
200
+ return result;
201
+ }
202
+ // Fallback: local greedy single-pass clustering using WASM-backed cosineSimilarity.
151
203
  const clusters = [];
152
204
  for (const fact of facts) {
153
205
  if (!fact.embedding || fact.embedding.length === 0)
154
206
  continue;
155
207
  let assigned = false;
156
208
  for (const cluster of clusters) {
157
- // Compare against the first member's embedding (cluster seed)
158
209
  const seed = cluster.members[0];
159
210
  if (!seed.embedding)
160
211
  continue;
@@ -169,7 +220,6 @@ function clusterFacts(facts, threshold) {
169
220
  clusters.push({ members: [fact] });
170
221
  }
171
222
  }
172
- // Only return clusters with duplicates, pick representative for each
173
223
  const result = [];
174
224
  for (const cluster of clusters) {
175
225
  if (cluster.members.length < 2)
@@ -180,4 +230,27 @@ function clusterFacts(facts, threshold) {
180
230
  }
181
231
  return result;
182
232
  }
233
+ // ---------------------------------------------------------------------------
234
+ // Local helpers (used only in fallback paths)
235
+ // ---------------------------------------------------------------------------
236
+ /**
237
+ * Pick the best representative from a group of near-duplicate facts.
238
+ *
239
+ * Tiebreak order:
240
+ * 1. Highest decayScore
241
+ * 2. Most recent (highest createdAt)
242
+ * 3. Longest text
243
+ */
244
+ function pickRepresentative(facts) {
245
+ let best = facts[0];
246
+ for (let i = 1; i < facts.length; i++) {
247
+ const f = facts[i];
248
+ if (f.decayScore > best.decayScore ||
249
+ (f.decayScore === best.decayScore && f.createdAt > best.createdAt) ||
250
+ (f.decayScore === best.decayScore && f.createdAt === best.createdAt && f.text.length > best.text.length)) {
251
+ best = f;
252
+ }
253
+ }
254
+ return best;
255
+ }
183
256
  //# sourceMappingURL=consolidation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"consolidation.js","sourceRoot":"","sources":["../src/consolidation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;GAkBG;;;AAcH,wDAOC;AAQD,8DAOC;AAkDD,8CAmBC;AAgBD,0CAMC;AA2CD,oCAuCC;AA/MD,wDAA0D;AAE1D,8EAA8E;AAC9E,gBAAgB;AAChB,8EAA8E;AAE9E;;;;;GAKG;AACH,SAAgB,sBAAsB;IACpC,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC;IAC7D,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACzB,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;QAClC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,IAAI,CAAC;YAAE,OAAO,MAAM,CAAC;IAClE,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;GAKG;AACH,SAAgB,yBAAyB;IACvC,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC;IAC/D,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;QACzB,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC;QAClC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,MAAM,IAAI,CAAC,IAAI,MAAM,IAAI,CAAC;YAAE,OAAO,MAAM,CAAC;IAClE,CAAC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AE,EAAE,CAAC;QACtC,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACnB,IACE,CAAC,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU;YAC9B,CAAC,CAAC,CAAC,UAAU,KAAK,IAAI,CAAC,UAAU,IAAI,CAAC,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;YAClE,CAAC,CAAC,CAAC,UAAU,KAAK,IAAI,CAAC,UAAU,IAAI,CAAC,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS,IAAI,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,EACxG,CAAC;YACD,IAAI,GAAG,CAAC,CAAC;QACX,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC"}
package/dist/index.js CHANGED
@@ -55,8 +55,11 @@ const reranker_js_1 = require("./subgraph/reranker.js");
55
55
  const store_js_1 = require("./subgraph/store.js");
56
56
  const search_js_1 = require("./subgraph/search.js");
57
57
  const pin_js_1 = require("./tools/pin.js");
58
+ const retype_js_1 = require("./tools/retype.js");
59
+ const set_scope_js_1 = require("./tools/set-scope.js");
58
60
  const claims_helper_js_1 = require("./claims-helper.js");
59
61
  const memory_types_js_1 = require("./memory-types.js");
62
+ const remember_js_2 = require("./tools/remember.js");
60
63
  const bip39_1 = require("@scure/bip39");
61
64
  const english_js_1 = require("@scure/bip39/wordlists/english.js");
62
65
  const accounts_1 = require("viem/accounts");
@@ -71,6 +74,24 @@ const setup_js_1 = require("./cli/setup.js");
71
74
  // ── Configuration ───────────────────────────────────────────────────────────
72
75
  const SERVER_URL = process.env.TOTALRECLAW_SERVER_URL || 'https://api.totalreclaw.xyz';
73
76
  const MASTER_PASSWORD = process.env.TOTALRECLAW_RECOVERY_PHRASE;
77
+ // v1 env var cleanup — warn once if any removed env var is still set.
78
+ // See docs/guides/env-vars-reference.md for the canonical list.
79
+ (() => {
80
+ const removed = [
81
+ 'TOTALRECLAW_CHAIN_ID',
82
+ 'TOTALRECLAW_EMBEDDING_MODEL',
83
+ 'TOTALRECLAW_STORE_DEDUP',
84
+ 'TOTALRECLAW_LLM_MODEL',
85
+ 'TOTALRECLAW_SESSION_ID',
86
+ 'TOTALRECLAW_TAXONOMY_VERSION',
87
+ 'TOTALRECLAW_CLAIM_FORMAT',
88
+ 'TOTALRECLAW_DIGEST_MODE',
89
+ ].filter((name) => process.env[name] !== undefined);
90
+ if (removed.length > 0) {
91
+ console.error(`TotalReclaw MCP: ignoring removed env var(s): ${removed.join(', ')}. ` +
92
+ `See docs/guides/env-vars-reference.md for the v1 env var surface.`);
93
+ }
94
+ })();
74
95
  // ── Client identification ──────────────────────────────────────────────────
75
96
  const client_id_js_1 = require("./client-id.js");
76
97
  let clientIdentifierResolved = false;
@@ -97,8 +118,9 @@ function resolveMnemonic() {
97
118
  return undefined;
98
119
  }
99
120
  let currentMode = 'unconfigured';
100
- // Store-time near-duplicate detection (consolidation module)
101
- const STORE_DEDUP_ENABLED = process.env.TOTALRECLAW_STORE_DEDUP !== 'false';
121
+ // Store-time near-duplicate detection is always ON in v1.
122
+ // The TOTALRECLAW_STORE_DEDUP env var was removed.
123
+ const STORE_DEDUP_ENABLED = true;
102
124
  const BILLING_CACHE_TTL = 2 * 60 * 60 * 1000; // 2 hours
103
125
  let billingCache = null;
104
126
  /** Whether a background billing fetch is already in progress. */
@@ -204,14 +226,13 @@ async function initSubgraphState(mnemonic) {
204
226
  },
205
227
  });
206
228
  const smartAccountAddress = smartAccount.address.toLowerCase();
207
- // Determine chain ID: env var override > billing tier > default (Base Sepolia).
229
+ // Determine chain ID: always auto-detect from billing tier.
208
230
  // Free tier → Base Sepolia (84532, testnet — Pimlico sponsors gas for free).
209
231
  // Pro tier → Gnosis mainnet (100, permanent on-chain storage).
210
- let chainId = process.env.TOTALRECLAW_CHAIN_ID
211
- ? parseInt(process.env.TOTALRECLAW_CHAIN_ID)
212
- : 84532; // default free tier
213
- // Auto-detect Pro tier from billing endpoint (if no env override).
214
- if (!process.env.TOTALRECLAW_CHAIN_ID) {
232
+ // TOTALRECLAW_CHAIN_ID user-facing override was removed in v1.
233
+ let chainId = 84532; // default free tier
234
+ // Auto-detect Pro tier from billing endpoint.
235
+ {
215
236
  try {
216
237
  const billingUrl = `${SERVER_URL.replace(/\/+$/, '')}/v1/billing/status?wallet_address=${encodeURIComponent(smartAccountAddress)}`;
217
238
  const resp = await fetch(billingUrl, {
@@ -352,11 +373,10 @@ async function handleRememberSubgraph(state, args) {
352
373
  // Support both single fact and batch mode (single only for subgraph for now)
353
374
  const factText = input?.fact || '';
354
375
  const factsArray = input?.facts;
355
- // Phase 2.2.6: thread `type` through from input → textsToStore → canonical
356
- // Claim builder. Prior to 2.2.6, `type` was accepted in the tool schema but
357
- // silently dropped here, and line ~648 passed a hardcoded 'fact' to
358
- // buildCanonicalClaim — making `rule` and every other non-fact type
359
- // structurally unreachable via the MCP remember tool.
376
+ // Phase 2.2.6 + v1: accept both legacy 8-type and v1 6-type inputs. The
377
+ // managed-service path always writes v1 inner blobs (protobuf wrapper v4).
378
+ // The legacy `MemoryType` is still tracked for backward compat with any
379
+ // downstream reader that consults the v0 short-key value.
360
380
  const textsToStore = [];
361
381
  const resolveType = (raw) => (0, memory_types_js_1.isValidMemoryType)(raw) ? raw : 'fact';
362
382
  if (factsArray && Array.isArray(factsArray) && factsArray.length > 0) {
@@ -366,16 +386,34 @@ async function handleRememberSubgraph(state, args) {
366
386
  text: f.text.trim(),
367
387
  importance: f.importance ?? 5,
368
388
  type: resolveType(f.type),
389
+ typeV1: (0, remember_js_2.normalizeTypeToV1)(f.type),
390
+ scope: (0, remember_js_2.normalizeScope)(f.scope),
391
+ reasoning: typeof f.reasoning === 'string' && f.reasoning.trim().length > 0
392
+ ? f.reasoning.trim()
393
+ : undefined,
369
394
  });
370
395
  }
371
396
  }
372
397
  }
373
398
  else if (factText && typeof factText === 'string' && factText.trim().length > 0) {
374
399
  const singleMetadata = input?.metadata;
400
+ const topLevelScope = typeof input?.scope === 'string'
401
+ ? input.scope
402
+ : undefined;
403
+ const topLevelReasoning = typeof input?.reasoning === 'string'
404
+ ? input.reasoning
405
+ : undefined;
406
+ const resolvedScope = (0, remember_js_2.normalizeScope)(topLevelScope ?? singleMetadata?.scope);
407
+ const resolvedReasoning = topLevelReasoning ?? (typeof singleMetadata?.reasoning === 'string' ? singleMetadata.reasoning : undefined);
375
408
  textsToStore.push({
376
409
  text: factText.trim(),
377
410
  importance: input?.importance ?? 5,
378
411
  type: resolveType(singleMetadata?.type),
412
+ typeV1: (0, remember_js_2.normalizeTypeToV1)(singleMetadata?.type),
413
+ scope: resolvedScope,
414
+ reasoning: resolvedReasoning && resolvedReasoning.trim().length > 0
415
+ ? resolvedReasoning.trim()
416
+ : undefined,
379
417
  });
380
418
  }
381
419
  if (textsToStore.length === 0) {
@@ -510,22 +548,29 @@ async function handleRememberSubgraph(state, args) {
510
548
  console.error(`Store-time dedup search failed: ${dedupErr instanceof Error ? dedupErr.message : String(dedupErr)}`);
511
549
  }
512
550
  }
513
- // 4. Build the blob: canonical Claim by default, raw text if legacy flag set
551
+ // 4. Build the blob.
514
552
  //
515
- // Phase 2.2.6: `item.type` is now threaded through from the tool input.
516
- // Prior to 2.2.6 this was hardcoded to 'fact', making `rule` and every
517
- // non-fact type structurally unreachable via the MCP remember tool even
518
- // when the client passed the correct value. The MCP batch-mode debrief
519
- // handler at line ~787 was already passing item.type correctly — this
520
- // fixes the single-/batch-remember handler for parity.
521
- const claimFormat = (0, claims_helper_js_1.resolveClaimFormat)();
522
- const blobPlaintext = claimFormat === 'legacy'
523
- ? item.text
524
- : (0, claims_helper_js_1.buildCanonicalClaim)({
525
- fact: { text: item.text, type: item.type },
526
- importance: effectiveImportance,
527
- sourceAgent: 'mcp-server',
528
- });
553
+ // Memory Taxonomy v1 (MCP server v3.0.0+): the managed-service write
554
+ // path unconditionally emits v1 inner blobs. Outer protobuf wrapper is
555
+ // v4 so readers know the inner payload is v1 JSON (see
556
+ // protobuf-v4-design.md). The v0 `{t,c,i,...}` canonical and raw-text
557
+ // legacy blobs are no longer produced — `TOTALRECLAW_CLAIM_FORMAT`
558
+ // was removed in v1.
559
+ //
560
+ // `source` defaults to:
561
+ // - `'user'` when the tool was called in single-fact (explicit) mode
562
+ // - `'user-inferred'` when called via the batch path (extraction)
563
+ // Host agents typically have the best provenance signal; this is a
564
+ // conservative default the extraction pipeline can override later.
565
+ const source = isExplicitRemember ? 'user' : 'user-inferred';
566
+ const blobPlaintext = (0, claims_helper_js_1.buildV1ClaimBlob)({
567
+ text: item.text,
568
+ type: item.typeV1,
569
+ source,
570
+ scope: item.scope,
571
+ reasoning: item.reasoning,
572
+ importance: effectiveImportance,
573
+ });
529
574
  const encryptedBlob = (0, crypto_js_1.encrypt)(blobPlaintext, state.encryptionKey);
530
575
  // 5. Generate content fingerprint for dedup (over plaintext text, not blob)
531
576
  const contentFp = (0, crypto_js_1.generateContentFingerprint)(item.text, state.dedupKey);
@@ -643,14 +688,21 @@ async function handleDebriefSubgraph(state, args) {
643
688
  const embedding = await (0, embedding_js_1.generateEmbedding)(item.text);
644
689
  const lshIndices = state.lshHasher.hash(embedding);
645
690
  const allIndices = [...wordIndices, ...lshIndices];
646
- const claimFormat = (0, claims_helper_js_1.resolveClaimFormat)();
647
- const blobPlaintext = claimFormat === 'legacy'
648
- ? item.text
649
- : (0, claims_helper_js_1.buildCanonicalClaim)({
650
- fact: { text: item.text, type: item.type },
651
- importance: item.importance,
652
- sourceAgent: 'mcp-server:debrief',
653
- });
691
+ // Memory Taxonomy v1: emit v1 inner blob with `type: 'summary'` (both
692
+ // tool-level 'summary' and 'context' map here — per spec §type-semantics,
693
+ // summary absorbs session-level synthesis regardless of whether the tool
694
+ // called it "summary" or "context"). `source: 'derived'` marks this as a
695
+ // derived-from-conversation claim (spec requires summary ∈ {derived,
696
+ // assistant}; derived is the better fit here).
697
+ //
698
+ // TOTALRECLAW_CLAIM_FORMAT=legacy was removed in v1; raw-text blobs are
699
+ // no longer produced on the write path.
700
+ const blobPlaintext = (0, claims_helper_js_1.buildV1ClaimBlob)({
701
+ text: item.text,
702
+ type: 'summary',
703
+ source: 'derived',
704
+ importance: item.importance,
705
+ });
654
706
  const encryptedBlob = (0, crypto_js_1.encrypt)(blobPlaintext, state.encryptionKey);
655
707
  const contentFp = (0, crypto_js_1.generateContentFingerprint)(item.text, state.dedupKey);
656
708
  const encryptedEmb = encryptEmbedding(embedding, state.encryptionKey);
@@ -776,9 +828,14 @@ async function handleRecallSubgraph(state, args) {
776
828
  }],
777
829
  };
778
830
  }
779
- // 5. Decrypt candidates
831
+ // 5. Decrypt candidates. Surfaces v1 provenance (`source`) when the blob
832
+ // carries it so Retrieval v2 Tier 1 can apply the source-weighted
833
+ // multiplier in core's `rerankWithConfig`.
780
834
  const decryptedCandidates = [];
781
835
  const categoryMap = new Map();
836
+ const sourceMap = new Map(); // v1 source, when available
837
+ const scopeMap = new Map();
838
+ const importanceRaw = new Map();
782
839
  for (const c of candidates) {
783
840
  try {
784
841
  const blobHex = c.encryptedBlob.startsWith('0x') ? c.encryptedBlob.slice(2) : c.encryptedBlob;
@@ -786,7 +843,7 @@ async function handleRecallSubgraph(state, args) {
786
843
  const decryptedBlob = (0, crypto_js_1.decrypt)(blobBase64, state.encryptionKey);
787
844
  if ((0, claims_helper_js_1.isDigestBlob)(decryptedBlob))
788
845
  continue;
789
- const doc = (0, claims_helper_js_1.readClaimFromBlob)(decryptedBlob);
846
+ const doc = (0, claims_helper_js_1.readBlobUnified)(decryptedBlob);
790
847
  const text = doc.text;
791
848
  let embedding;
792
849
  if (c.encryptedEmbedding) {
@@ -808,12 +865,19 @@ async function handleRecallSubgraph(state, args) {
808
865
  if (doc.category) {
809
866
  categoryMap.set(c.id, doc.category);
810
867
  }
868
+ if (doc.v1) {
869
+ sourceMap.set(c.id, doc.v1.source);
870
+ if (doc.v1.scope)
871
+ scopeMap.set(c.id, doc.v1.scope);
872
+ }
873
+ importanceRaw.set(c.id, doc.importance);
811
874
  decryptedCandidates.push({
812
875
  id: c.id,
813
876
  text,
814
877
  embedding,
815
878
  importance: parseFloat(c.decayScore) || 0.5,
816
879
  createdAt: parseInt(c.timestamp) || undefined,
880
+ source: sourceMap.get(c.id),
817
881
  });
818
882
  }
819
883
  catch {
@@ -824,13 +888,34 @@ async function handleRecallSubgraph(state, args) {
824
888
  const intent = (0, reranker_js_1.detectQueryIntent)(query.trim());
825
889
  const weights = reranker_js_1.INTENT_WEIGHTS[intent];
826
890
  // 7. Rerank with BM25 + cosine + importance + recency via weighted RRF
891
+ // (+ MMR diversity). Then apply Retrieval v2 Tier 1 source weights via
892
+ // core's `rerankWithConfig` using only the bm25/cosine components (the
893
+ // MCP-side recency + MMR + intent weighting remain in TS for now).
894
+ // Strategy: run the TS reranker to produce the top-K ordering; use
895
+ // core's source-weight helper to nudge the final score so assistant-
896
+ // authored claims drop behind user-authored ones with comparable text.
827
897
  const reranked = (0, reranker_js_1.rerank)(query.trim(), queryEmbedding, decryptedCandidates, k, weights);
898
+ const core = require('@totalreclaw/core');
899
+ const weighted = reranked
900
+ .map((r) => {
901
+ const s = sourceMap.get(r.id);
902
+ const w = s
903
+ ? core.sourceWeight(s)
904
+ : core.legacyClaimFallbackWeight();
905
+ return { r, weightedScore: r.rrfScore * w, sourceWeight: w };
906
+ })
907
+ .sort((a, b) => b.weightedScore - a.weightedScore)
908
+ .slice(0, k);
828
909
  // 8. Format results
829
- const memories = reranked.map(r => ({
910
+ const memories = weighted.map(({ r, weightedScore, sourceWeight }) => ({
830
911
  fact_id: r.id,
831
912
  fact_text: r.text,
832
913
  type: categoryMap.get(r.id) ?? 'fact',
833
- score: r.rrfScore,
914
+ source: sourceMap.get(r.id),
915
+ scope: scopeMap.get(r.id),
916
+ score: weightedScore,
917
+ rrf_score: r.rrfScore,
918
+ source_weight: sourceWeight,
834
919
  cosine_similarity: r.cosineSimilarity ?? 0,
835
920
  importance: Math.round((r.importance ?? 0.5) * 10),
836
921
  age_days: r.createdAt
@@ -984,6 +1069,22 @@ function buildPinDepsFromState(state) {
984
1069
  },
985
1070
  };
986
1071
  }
1072
+ /** Build MetadataOpDeps (retype + set_scope) bound to the live subgraph state. */
1073
+ function buildMetadataOpDepsFromState(state) {
1074
+ // MetadataOpDeps is structurally compatible with PinOpDeps (minus the
1075
+ // status-flip specifics). Reuse the pin deps factory and narrow to the
1076
+ // fields `executeMetadataOp` needs.
1077
+ const pinDeps = buildPinDepsFromState(state);
1078
+ return {
1079
+ owner: pinDeps.owner,
1080
+ sourceAgent: pinDeps.sourceAgent,
1081
+ fetchFactById: pinDeps.fetchFactById,
1082
+ decryptBlob: pinDeps.decryptBlob,
1083
+ encryptBlob: pinDeps.encryptBlob,
1084
+ submitBatch: pinDeps.submitBatch,
1085
+ generateIndices: pinDeps.generateIndices,
1086
+ };
1087
+ }
987
1088
  /** Handle pin/unpin in subgraph mode. */
988
1089
  async function handlePinSubgraph(state, args) {
989
1090
  const deps = buildPinDepsFromState(state);
@@ -1445,6 +1546,8 @@ server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => ({
1445
1546
  index_js_2.accountToolDefinition,
1446
1547
  pin_js_1.pinToolDefinition,
1447
1548
  pin_js_1.unpinToolDefinition,
1549
+ retype_js_1.retypeToolDefinition,
1550
+ set_scope_js_1.setScopeToolDefinition,
1448
1551
  ],
1449
1552
  }));
1450
1553
  server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
@@ -1636,6 +1739,36 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
1636
1739
  throw error;
1637
1740
  }
1638
1741
  }
1742
+ case 'totalreclaw_retype': {
1743
+ try {
1744
+ const deps = buildMetadataOpDepsFromState(subgraphState);
1745
+ const result = await (0, retype_js_1.handleRetypeWithDeps)(args, deps);
1746
+ (0, index_js_3.invalidateMemoryContextCache)();
1747
+ server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1748
+ return result;
1749
+ }
1750
+ catch (error) {
1751
+ if (isQuotaExceededError(error)) {
1752
+ return quotaExceededResponse();
1753
+ }
1754
+ throw error;
1755
+ }
1756
+ }
1757
+ case 'totalreclaw_set_scope': {
1758
+ try {
1759
+ const deps = buildMetadataOpDepsFromState(subgraphState);
1760
+ const result = await (0, set_scope_js_1.handleSetScopeWithDeps)(args, deps);
1761
+ (0, index_js_3.invalidateMemoryContextCache)();
1762
+ server.sendResourceUpdated({ uri: index_js_3.memoryContextResource.uri }).catch((err) => console.error('Failed to send resource update:', err));
1763
+ return result;
1764
+ }
1765
+ catch (error) {
1766
+ if (isQuotaExceededError(error)) {
1767
+ return quotaExceededResponse();
1768
+ }
1769
+ throw error;
1770
+ }
1771
+ }
1639
1772
  default:
1640
1773
  return {
1641
1774
  content: [{
@@ -1701,6 +1834,10 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
1701
1834
  return await (0, pin_js_1.handlePin)(args);
1702
1835
  case 'totalreclaw_unpin':
1703
1836
  return await (0, pin_js_1.handleUnpin)(args);
1837
+ case 'totalreclaw_retype':
1838
+ return await (0, retype_js_1.handleRetype)(args);
1839
+ case 'totalreclaw_set_scope':
1840
+ return await (0, set_scope_js_1.handleSetScope)(args);
1704
1841
  default:
1705
1842
  return {
1706
1843
  content: [{