dsh-mnemon-source-memory-spaces 0.5.2 → 0.5.4

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/lib/index.js CHANGED
@@ -1,21 +1,22 @@
1
+ import { findMnemonCommand, isMnemonExecutable, mnemonNpmLauncher } from "./native-cli.js";
1
2
  import { CATEGORIES as CATEGORIES$1, EDGE_TYPES, INTENTS as INTENTS$1, MNEMON_EMBEDDING_PROTOCOLS, SOURCES as SOURCES$1 } from "./contracts.js";
2
3
  import { a as MemoryProviderCatalog, i as EMPTY_MEMORY_PROVIDER_CATALOG, n as PrivateMemorySpaceProviderHost, r as MemoryProviderAdapterRegistry, t as createMemorySpaceProviderPlugin } from "./plugin-DlsNeZbQ.js";
3
4
  import { t as runProcess } from "./process-B-t3UflO.js";
4
5
  import { r as defineMemorySpaceProvider } from "./definitions-DfmOqJjR.js";
6
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import { homedir, tmpdir } from "node:os";
8
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
5
9
  import z from "schemastery";
6
10
  import { createMemoryMutationReceipt, defineMemoryPlugin, defineMemorySource, installMemory, memoryConfigurationDigest, memoryInputInteger, memoryInputRecord, memoryInputStringArray, memoryInputText, truncateMemoryText, withMemoryStorageLock } from "dsh-mnemon/extension-sdk";
7
11
  import { createHash, randomUUID } from "node:crypto";
8
12
  import { COMPOSABLE_MEMORY_API_VERSION } from "dsh-mnemon/contracts";
9
- import { accessSync, constants, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
10
- import { homedir, tmpdir } from "node:os";
11
- import { basename, dirname, isAbsolute, join, posix, resolve, win32 } from "node:path";
12
13
  //#region src/view-model.ts
13
14
  const MODEL_MEMORY_BODY_LIMIT = 16;
14
15
  function boundedToolText(value, maximum) {
15
16
  return value.length <= maximum ? value : `${value.slice(0, maximum - 1)}…`;
16
17
  }
17
18
  /** Strip control-plane paths, provider settings, and statistics from model output. */
18
- function modelBodyCatalog(catalog) {
19
+ function modelSpaceCatalog(catalog) {
19
20
  const items = catalog.items.slice(0, MODEL_MEMORY_BODY_LIMIT);
20
21
  return {
21
22
  items: items.map((body) => ({
@@ -94,7 +95,7 @@ function modelJson(value, maximum) {
94
95
  return result;
95
96
  }
96
97
  //#endregion
97
- //#region src/memory-bodies.ts
98
+ //#region src/memory-spaces.ts
98
99
  const NATIVE_REGISTRY_VERSION = 1;
99
100
  const PROVIDER_REGISTRY_VERSION = 4;
100
101
  const ID_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
@@ -192,7 +193,7 @@ function normalizePlacementDecision(value, providerId, providerCatalog = EMPTY_M
192
193
  ...placement.subagentProvider === void 0 ? {} : { subagentProvider: placement.subagentProvider }
193
194
  };
194
195
  }
195
- function validateMemoryBodyId(value) {
196
+ function validateMemorySpaceId(value) {
196
197
  const normalized = value.trim();
197
198
  if (!ID_PATTERN.test(normalized)) throw new Error("memoryBodyId must match [a-zA-Z0-9][a-zA-Z0-9_-]*");
198
199
  return normalized;
@@ -204,7 +205,7 @@ function validateMemoryBodyId(value) {
204
205
  * compatible. External connection metadata lives under state and is never
205
206
  * included in Memory Space Packs.
206
207
  */
207
- var MemoryBodyRegistry = class MemoryBodyRegistry {
208
+ var MemorySpaceRegistry = class MemorySpaceRegistry {
208
209
  runner;
209
210
  persistent;
210
211
  now;
@@ -220,7 +221,7 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
220
221
  this.now = now;
221
222
  this.providerCatalog = providerCatalog;
222
223
  this.state = sharedState ?? {
223
- bodies: [],
224
+ spaces: [],
224
225
  services: {},
225
226
  serviceEnabled: {}
226
227
  };
@@ -229,11 +230,11 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
229
230
  this.providerRegistryPath = join(runner.effectiveDataDir(), "state", "memory-providers.json");
230
231
  if (sharedState === void 0) this.reload();
231
232
  }
232
- get bodies() {
233
- return this.state.bodies;
233
+ get spaces() {
234
+ return this.state.spaces;
234
235
  }
235
- set bodies(value) {
236
- this.state.bodies = value;
236
+ set spaces(value) {
237
+ this.state.spaces = value;
237
238
  }
238
239
  get services() {
239
240
  return this.state.services;
@@ -249,7 +250,7 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
249
250
  }
250
251
  /** One generation-local descriptor view over the same persistent authority. */
251
252
  withProviderCatalog(providerCatalog) {
252
- return new MemoryBodyRegistry(this.runner, this.persistent, this.now, providerCatalog, this.state);
253
+ return new MemorySpaceRegistry(this.runner, this.persistent, this.now, providerCatalog, this.state);
253
254
  }
254
255
  isNative(providerId) {
255
256
  return this.providerTypeId(providerId) === "mnemon-native";
@@ -261,15 +262,15 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
261
262
  list() {
262
263
  this.refreshIfChanged();
263
264
  this.reconcileDiscoveredStores();
264
- return this.bodies.filter((body) => this.providerCatalog.has(body.providerId)).map((body) => this.view(body));
265
+ return this.spaces.filter((body) => this.providerCatalog.has(body.providerId)).map((body) => this.view(body));
265
266
  }
266
267
  active() {
267
268
  return this.list().filter((body) => body.active && (this.isNative(body.provider.id) || Object.hasOwn(this.services, body.provider.id) && this.serviceEnabled[body.provider.id] === true));
268
269
  }
269
270
  get(id) {
270
- const normalized = validateMemoryBodyId(id);
271
+ const normalized = validateMemorySpaceId(id);
271
272
  const body = this.list().find((entry) => entry.id === normalized);
272
- if (body === void 0) throw new Error(`unknown memory body: ${normalized}`);
273
+ if (body === void 0) throw new Error(`unknown memory space: ${normalized}`);
273
274
  return body;
274
275
  }
275
276
  openVikingConnection(id) {
@@ -285,10 +286,10 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
285
286
  }
286
287
  providerConnection(id, expectedProviderId) {
287
288
  this.refreshIfChanged();
288
- const normalized = validateMemoryBodyId(id);
289
- const body = this.bodies.find((entry) => entry.id === normalized);
290
- if (body === void 0 || this.isNative(body.providerId)) throw new Error(`memory body has no external provider connection: ${normalized}`);
291
- if (expectedProviderId !== void 0 && body.providerId !== expectedProviderId) throw new Error(`memory body ${normalized} uses ${body.providerId}, not ${expectedProviderId}`);
289
+ const normalized = validateMemorySpaceId(id);
290
+ const body = this.spaces.find((entry) => entry.id === normalized);
291
+ if (body === void 0 || this.isNative(body.providerId)) throw new Error(`memory space has no external provider connection: ${normalized}`);
292
+ if (expectedProviderId !== void 0 && body.providerId !== expectedProviderId) throw new Error(`memory space ${normalized} uses ${body.providerId}, not ${expectedProviderId}`);
292
293
  return this.connectionFor(body);
293
294
  }
294
295
  /** Used only after a public operation has refreshed the registry authority. */
@@ -333,7 +334,7 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
333
334
  const previous = this.services[providerId] ?? {};
334
335
  this.services[providerId] = this.providerCatalog.normalizeService(providerId, settings, previous, clearSecrets);
335
336
  this.serviceEnabled[providerId] = enabled;
336
- if (!enabled) this.bodies = this.bodies.filter((body) => body.providerId !== providerId);
337
+ if (!enabled) this.spaces = this.spaces.filter((body) => body.providerId !== providerId);
337
338
  this.save();
338
339
  return this.providerServices().items.find((item) => item.providerId === providerId);
339
340
  }
@@ -348,8 +349,8 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
348
349
  if (this.isNative(providerId)) throw new Error("Mnemon Native Stores are discovered from disk");
349
350
  let normalizedService = this.providerCatalog.normalizeService(providerId, service);
350
351
  const seen = /* @__PURE__ */ new Set();
351
- const existing = this.bodies.filter((body) => body.providerId === providerId);
352
- const reservedIds = new Set(this.bodies.filter((body) => body.providerId !== providerId).map((body) => body.id));
352
+ const existing = this.spaces.filter((body) => body.providerId === providerId);
353
+ const reservedIds = new Set(this.spaces.filter((body) => body.providerId !== providerId).map((body) => body.id));
353
354
  const timestamp = this.now().toISOString();
354
355
  const projections = discovered.map((candidate) => {
355
356
  const externalId = requiredText(candidate.externalId, "provider externalId", 2e3);
@@ -361,10 +362,10 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
361
362
  ...connection
362
363
  });
363
364
  const previous = existing.find((body) => body.externalId === externalId);
364
- let id = previous?.id ?? validateMemoryBodyId(`${providerId}-${createHash("sha256").update(externalId).digest("hex").slice(0, 24)}`);
365
+ let id = previous?.id ?? validateMemorySpaceId(`${providerId}-${createHash("sha256").update(externalId).digest("hex").slice(0, 24)}`);
365
366
  let suffix = 1;
366
367
  while (reservedIds.has(id)) {
367
- id = validateMemoryBodyId(`${providerId}-${createHash("sha256").update(`${externalId}:${suffix}`).digest("hex").slice(0, 24)}`);
368
+ id = validateMemorySpaceId(`${providerId}-${createHash("sha256").update(`${externalId}:${suffix}`).digest("hex").slice(0, 24)}`);
368
369
  suffix += 1;
369
370
  }
370
371
  reservedIds.add(id);
@@ -394,7 +395,7 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
394
395
  }
395
396
  this.services[providerId] = normalizedService;
396
397
  this.serviceEnabled[providerId] = true;
397
- this.bodies = [...this.bodies.filter((body) => body.providerId !== providerId), ...projections];
398
+ this.spaces = [...this.spaces.filter((body) => body.providerId !== providerId), ...projections];
398
399
  this.save();
399
400
  return this.providerServices().items.find((item) => item.providerId === providerId);
400
401
  }
@@ -436,8 +437,8 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
436
437
  const reservedIds = new Set(this.list().map((body) => body.id));
437
438
  const nativeStoreIds = this.nativeStoreIds();
438
439
  const nativeProvider = this.isNative(providerId);
439
- let id = nativeProvider && nativeStoreIds.length === 0 && !reservedIds.has("default") ? "default" : validateMemoryBodyId(nativeProvider ? randomUUID() : `${providerId}-${randomUUID()}`);
440
- while (reservedIds.has(id) || nativeStoreIds.includes(id)) id = validateMemoryBodyId(randomUUID());
440
+ let id = nativeProvider && nativeStoreIds.length === 0 && !reservedIds.has("default") ? "default" : validateMemorySpaceId(nativeProvider ? randomUUID() : `${providerId}-${randomUUID()}`);
441
+ while (reservedIds.has(id) || nativeStoreIds.includes(id)) id = validateMemorySpaceId(randomUUID());
441
442
  const connectionInput = request.providerConnections?.[providerId] ?? (this.providerTypeId(providerId) === "openviking" && request.connection === void 0 && request.openViking !== void 0 ? request.openViking : request.connection);
442
443
  let connection;
443
444
  if (!nativeProvider) {
@@ -474,19 +475,19 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
474
475
  createdAt: timestamp,
475
476
  updatedAt: timestamp
476
477
  };
477
- this.bodies.push(body);
478
+ this.spaces.push(body);
478
479
  this.save();
479
480
  return this.view(body);
480
481
  }
481
482
  update(id, request) {
482
483
  this.refreshIfChanged();
483
- const normalized = validateMemoryBodyId(id);
484
- const index = this.bodies.findIndex((body) => body.id === normalized);
485
- if (index < 0) throw new Error(`unknown memory body: ${normalized}`);
486
- const current = this.bodies[index];
487
- if (request.openViking !== void 0 && this.providerTypeId(current.providerId) !== "openviking") throw new Error("OpenViking connection settings only apply to OpenViking memory bodies");
484
+ const normalized = validateMemorySpaceId(id);
485
+ const index = this.spaces.findIndex((body) => body.id === normalized);
486
+ if (index < 0) throw new Error(`unknown memory space: ${normalized}`);
487
+ const current = this.spaces[index];
488
+ if (request.openViking !== void 0 && this.providerTypeId(current.providerId) !== "openviking") throw new Error("OpenViking connection settings only apply to OpenViking memory spaces");
488
489
  const nativeProvider = this.isNative(current.providerId);
489
- if ((request.connection !== void 0 || request.clearSecrets !== void 0) && nativeProvider) throw new Error("Mnemon Native memory bodies do not have provider connection settings");
490
+ if ((request.connection !== void 0 || request.clearSecrets !== void 0) && nativeProvider) throw new Error("Mnemon Native memory spaces do not have provider connection settings");
490
491
  const legacyPatch = request.openViking === void 0 ? void 0 : {
491
492
  ...request.openViking,
492
493
  ...request.openViking.clearApiKey === true ? { apiKey: "" } : {}
@@ -518,7 +519,7 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
518
519
  ...connection === void 0 ? {} : { connection },
519
520
  updatedAt: this.nextTimestamp(current.updatedAt)
520
521
  };
521
- this.bodies[index] = body;
522
+ this.spaces[index] = body;
522
523
  this.save();
523
524
  return this.view(body);
524
525
  }
@@ -528,30 +529,30 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
528
529
  if (updates.length === 0 || updates.length > 20) throw new Error("metadata maintenance requires 1 through 20 Memory Spaces");
529
530
  const seen = /* @__PURE__ */ new Set();
530
531
  const replacements = updates.map((update) => {
531
- const id = validateMemoryBodyId(update.memoryBodyId);
532
+ const id = validateMemorySpaceId(update.memoryBodyId);
532
533
  if (seen.has(id)) throw new Error(`duplicate metadata update: ${id}`);
533
534
  seen.add(id);
534
- const index = this.bodies.findIndex((body) => body.id === id);
535
- if (index < 0) throw new Error(`unknown memory body: ${id}`);
535
+ const index = this.spaces.findIndex((body) => body.id === id);
536
+ if (index < 0) throw new Error(`unknown memory space: ${id}`);
536
537
  return {
537
538
  index,
538
539
  body: {
539
- ...this.bodies[index],
540
+ ...this.spaces[index],
540
541
  name: requiredText(update.title, "title", 48),
541
542
  description: requiredText(update.description, "description", 200),
542
543
  metadataSource: "ai",
543
- updatedAt: this.nextTimestamp(this.bodies[index].updatedAt)
544
+ updatedAt: this.nextTimestamp(this.spaces[index].updatedAt)
544
545
  }
545
546
  };
546
547
  });
547
- for (const replacement of replacements) this.bodies[replacement.index] = replacement.body;
548
+ for (const replacement of replacements) this.spaces[replacement.index] = replacement.body;
548
549
  this.save();
549
550
  return replacements.map((replacement) => this.view(replacement.body));
550
551
  }
551
552
  async remove(id, signal) {
552
553
  const body = this.get(id);
553
554
  if (!this.isNative(body.provider.id)) {
554
- this.bodies = this.bodies.filter((entry) => entry.id !== body.id);
555
+ this.spaces = this.spaces.filter((entry) => entry.id !== body.id);
555
556
  this.save();
556
557
  return body;
557
558
  }
@@ -589,7 +590,7 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
589
590
  }
590
591
  });
591
592
  await this.runner.runTextBatch(commands);
592
- this.bodies = this.bodies.filter((entry) => entry.id !== body.id);
593
+ this.spaces = this.spaces.filter((entry) => entry.id !== body.id);
593
594
  this.save();
594
595
  return body;
595
596
  }
@@ -598,14 +599,14 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
598
599
  }
599
600
  /** Advance the safe catalog checkpoint after provider-backed content changes. */
600
601
  touch(id) {
601
- const normalized = validateMemoryBodyId(id);
602
- const index = this.bodies.findIndex((body) => body.id === normalized);
603
- if (index < 0) throw new Error(`unknown memory body: ${normalized}`);
602
+ const normalized = validateMemorySpaceId(id);
603
+ const index = this.spaces.findIndex((body) => body.id === normalized);
604
+ if (index < 0) throw new Error(`unknown memory space: ${normalized}`);
604
605
  const body = {
605
- ...this.bodies[index],
606
- updatedAt: this.nextTimestamp(this.bodies[index].updatedAt)
606
+ ...this.spaces[index],
607
+ updatedAt: this.nextTimestamp(this.spaces[index].updatedAt)
607
608
  };
608
- this.bodies[index] = body;
609
+ this.spaces[index] = body;
609
610
  this.save();
610
611
  return this.view(body);
611
612
  }
@@ -613,7 +614,7 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
613
614
  reload() {
614
615
  this.refreshing = true;
615
616
  try {
616
- this.bodies = [];
617
+ this.spaces = [];
617
618
  this.services = {};
618
619
  this.serviceEnabled = {};
619
620
  this.loadAndReconcile();
@@ -645,7 +646,7 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
645
646
  const parsed = JSON.parse(readFileSync(this.registryPath, "utf8"));
646
647
  if ((parsed.version === NATIVE_REGISTRY_VERSION || parsed.version === 2) && Array.isArray(parsed.bodies)) {
647
648
  migratedProviderRegistry = parsed.version === 2;
648
- this.bodies = parsed.bodies.filter((body) => ID_PATTERN.test(body.id)).map((body) => {
649
+ this.spaces = parsed.bodies.filter((body) => ID_PATTERN.test(body.id)).map((body) => {
649
650
  const syntheticDefault = body.id === "default" && body.name === "默认记忆体" && body.description === "从现有 Mnemon Store 自动接入。";
650
651
  migratedSyntheticDefault ||= syntheticDefault;
651
652
  const providerId = "providerId" in body && storedProviderId(body.providerId) ? body.providerId : "mnemon-native";
@@ -685,7 +686,7 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
685
686
  });
686
687
  }
687
688
  } catch {
688
- this.bodies = [];
689
+ this.spaces = [];
689
690
  }
690
691
  if (this.persistent && existsSync(this.providerRegistryPath)) try {
691
692
  const parsed = JSON.parse(readFileSync(this.providerRegistryPath, "utf8"));
@@ -697,8 +698,8 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
697
698
  }
698
699
  if ((parsed.version === 1 || parsed.version === 2 || parsed.version === 3 || parsed.version === PROVIDER_REGISTRY_VERSION) && Array.isArray(parsed.bodies)) {
699
700
  migratedProviderRegistry ||= parsed.version !== PROVIDER_REGISTRY_VERSION;
700
- const existingIds = new Set(this.bodies.map((body) => body.id));
701
- this.bodies.push(...parsed.bodies.filter((body) => storedProviderId(body.providerId) && (!this.providerCatalog.has(body.providerId) || !this.isNative(body.providerId)) && ID_PATTERN.test(body.id) && !existingIds.has(body.id)).map((body) => {
701
+ const existingIds = new Set(this.spaces.map((body) => body.id));
702
+ this.spaces.push(...parsed.bodies.filter((body) => storedProviderId(body.providerId) && (!this.providerCatalog.has(body.providerId) || !this.isNative(body.providerId)) && ID_PATTERN.test(body.id) && !existingIds.has(body.id)).map((body) => {
702
703
  const providerId = body.providerId;
703
704
  if (!this.providerCatalog.has(providerId)) return {
704
705
  id: body.id,
@@ -743,9 +744,9 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
743
744
  }));
744
745
  }
745
746
  } catch {}
746
- const retainedBodies = this.bodies.filter((body) => !this.providerCatalog.has(body.providerId) || this.isNative(body.providerId) || this.providerServiceEnabled(body.providerId));
747
- if (retainedBodies.length !== this.bodies.length) {
748
- this.bodies = retainedBodies;
747
+ const retainedBodies = this.spaces.filter((body) => !this.providerCatalog.has(body.providerId) || this.isNative(body.providerId) || this.providerServiceEnabled(body.providerId));
748
+ if (retainedBodies.length !== this.spaces.length) {
749
+ this.spaces = retainedBodies;
749
750
  migratedProviderRegistry = true;
750
751
  }
751
752
  this.reconcileDiscoveredStores();
@@ -758,12 +759,12 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
758
759
  let changed = false;
759
760
  for (const entry of readdirSync(this.directory, { withFileTypes: true })) {
760
761
  if (!entry.isDirectory() || !ID_PATTERN.test(entry.name) || !existsSync(join(this.directory, entry.name, "mnemon.db"))) continue;
761
- if (this.bodies.some((body) => body.id === entry.name)) continue;
762
- this.bodies.push({
762
+ if (this.spaces.some((body) => body.id === entry.name)) continue;
763
+ this.spaces.push({
763
764
  id: entry.name,
764
765
  name: entry.name,
765
766
  description: "Existing Mnemon Store discovered on disk.",
766
- active: this.bodies.length === 0 || entry.name === legacyActive,
767
+ active: this.spaces.length === 0 || entry.name === legacyActive,
767
768
  providerId: "mnemon-native",
768
769
  createdAt: timestamp,
769
770
  updatedAt: timestamp
@@ -819,12 +820,12 @@ var MemoryBodyRegistry = class MemoryBodyRegistry {
819
820
  recursive: true,
820
821
  mode: 448
821
822
  });
822
- const nativeBodies = this.bodies.filter((body) => body.providerId === "mnemon-native" || this.providerCatalog.has(body.providerId) && this.isNative(body.providerId)).map(({ providerId: _providerId, connection: _connection, openViking: _openViking, ...body }) => body);
823
+ const nativeBodies = this.spaces.filter((body) => body.providerId === "mnemon-native" || this.providerCatalog.has(body.providerId) && this.isNative(body.providerId)).map(({ providerId: _providerId, connection: _connection, openViking: _openViking, ...body }) => body);
823
824
  this.writeRegistry(this.registryPath, {
824
825
  version: NATIVE_REGISTRY_VERSION,
825
826
  bodies: nativeBodies
826
827
  });
827
- const providerBodies = this.bodies.filter((body) => body.providerId !== "mnemon-native" && (!this.providerCatalog.has(body.providerId) || !this.isNative(body.providerId)));
828
+ const providerBodies = this.spaces.filter((body) => body.providerId !== "mnemon-native" && (!this.providerCatalog.has(body.providerId) || !this.isNative(body.providerId)));
828
829
  if (providerBodies.length === 0 && Object.keys(this.services).length === 0) {
829
830
  rmSync(this.providerRegistryPath, { force: true });
830
831
  this.state.diskRevision = this.diskRevision();
@@ -1374,10 +1375,12 @@ var MemorySpacesService = class {
1374
1375
  config;
1375
1376
  recallQualityPolicyRegistry;
1376
1377
  providerCatalog;
1378
+ memorySpaces;
1379
+ /** @deprecated Use memorySpaces. Both names share the same registry authority. */
1377
1380
  memoryBodies;
1378
1381
  providers;
1379
1382
  recallQualityPolicy;
1380
- bodiesInFlight;
1383
+ spacesInFlight;
1381
1384
  providersDisposed = false;
1382
1385
  providerTypeId(providerId) {
1383
1386
  const catalog = this.providerCatalog;
@@ -1388,18 +1391,20 @@ var MemorySpacesService = class {
1388
1391
  isNativeProvider(providerId) {
1389
1392
  return this.providerTypeId(providerId) === "mnemon-native";
1390
1393
  }
1391
- isNativeBody(body) {
1394
+ isNativeSpace(body) {
1392
1395
  return (body.provider.typeId ?? body.provider.id) === "mnemon-native";
1393
1396
  }
1394
- constructor(runner, config, memoryBodies, recallQualityPolicyRegistry = recallQualityPolicies, providerAdapterRegistry = new MemoryProviderAdapterRegistry(), providerCatalog = EMPTY_MEMORY_PROVIDER_CATALOG) {
1397
+ constructor(runner, config, memorySpaces, recallQualityPolicyRegistry = recallQualityPolicies, providerAdapterRegistry = new MemoryProviderAdapterRegistry(), providerCatalog = EMPTY_MEMORY_PROVIDER_CATALOG) {
1395
1398
  this.runner = runner;
1396
1399
  this.config = config;
1397
1400
  this.recallQualityPolicyRegistry = recallQualityPolicyRegistry;
1398
1401
  this.providerCatalog = providerCatalog;
1399
- this.memoryBodies = memoryBodies === void 0 ? new MemoryBodyRegistry(runner, true, () => /* @__PURE__ */ new Date(), providerCatalog) : providerCatalog === EMPTY_MEMORY_PROVIDER_CATALOG ? memoryBodies : memoryBodies.withProviderCatalog(providerCatalog);
1402
+ this.memorySpaces = memorySpaces === void 0 ? new MemorySpaceRegistry(runner, true, () => /* @__PURE__ */ new Date(), providerCatalog) : providerCatalog === EMPTY_MEMORY_PROVIDER_CATALOG ? memorySpaces : memorySpaces.withProviderCatalog(providerCatalog);
1403
+ this.memoryBodies = this.memorySpaces;
1400
1404
  this.recallQualityPolicy = recallQualityPolicyRegistry.resolve(config.recallQuality.policy);
1401
1405
  this.providers = providerAdapterRegistry.create({
1402
- memoryBodies: this.memoryBodies,
1406
+ memorySpaces: this.memorySpaces,
1407
+ memoryBodies: this.memorySpaces,
1403
1408
  config: this.config,
1404
1409
  nativeRunner: this.runner
1405
1410
  });
@@ -1417,20 +1422,20 @@ var MemorySpacesService = class {
1417
1422
  this.providers.clear();
1418
1423
  if (failures.length > 0) throw new AggregateError(failures, "Memory Space Provider disposal failed");
1419
1424
  }
1420
- async bodies(signal) {
1421
- if (signal !== void 0) return this.collectBodies(signal);
1422
- if (this.bodiesInFlight !== void 0) return this.bodiesInFlight;
1423
- const pending = this.collectBodies();
1424
- this.bodiesInFlight = pending;
1425
+ async spaces(signal) {
1426
+ if (signal !== void 0) return this.collectSpaces(signal);
1427
+ if (this.spacesInFlight !== void 0) return this.spacesInFlight;
1428
+ const pending = this.collectSpaces();
1429
+ this.spacesInFlight = pending;
1425
1430
  try {
1426
1431
  return await pending;
1427
1432
  } finally {
1428
- if (this.bodiesInFlight === pending) this.bodiesInFlight = void 0;
1433
+ if (this.spacesInFlight === pending) this.spacesInFlight = void 0;
1429
1434
  }
1430
1435
  }
1431
1436
  /** Coalesce simultaneous Status/Memory-page probes without caching mutations. */
1432
- async collectBodies(signal) {
1433
- const directory = this.bodyDirectory();
1437
+ async collectSpaces(signal) {
1438
+ const directory = this.spaceDirectory();
1434
1439
  const items = await Promise.all(directory.items.map(async (body) => {
1435
1440
  let status;
1436
1441
  if (!(body.providerEnabled !== false)) status = {
@@ -1459,12 +1464,12 @@ var MemorySpacesService = class {
1459
1464
  };
1460
1465
  }
1461
1466
  /** Return the control-plane directory without waiting for provider I/O. */
1462
- bodyDirectory() {
1467
+ spaceDirectory() {
1463
1468
  const mnemonDefaultStore = this.runner.persistedStore();
1464
- const all = this.memoryBodies.list();
1465
- const enabled = new Set(this.memoryBodies.providerServices().items.filter((service) => service.enabled).map((service) => service.providerId));
1469
+ const all = this.memorySpaces.list();
1470
+ const enabled = new Set(this.memorySpaces.providerServices().items.filter((service) => service.enabled).map((service) => service.providerId));
1466
1471
  const items = all.map((body) => {
1467
- const nativeProvider = this.isNativeBody(body);
1472
+ const nativeProvider = this.isNativeSpace(body);
1468
1473
  const providerEnabled = nativeProvider || enabled.has(body.provider.id);
1469
1474
  return {
1470
1475
  ...body,
@@ -1488,7 +1493,7 @@ var MemorySpacesService = class {
1488
1493
  },
1489
1494
  total: items.length,
1490
1495
  activeCount: items.filter((body) => body.active && body.providerEnabled !== false).length,
1491
- directory: this.memoryBodies.directory,
1496
+ directory: this.memorySpaces.directory,
1492
1497
  generatedAt: (/* @__PURE__ */ new Date()).toISOString()
1493
1498
  };
1494
1499
  }
@@ -1498,11 +1503,11 @@ var MemorySpacesService = class {
1498
1503
  }
1499
1504
  /** One local metadata observation supplies membership and its revision. */
1500
1505
  memoryState() {
1501
- const all = this.memoryBodies.list();
1502
- const serviceItems = this.memoryBodies.providerServices().items;
1506
+ const all = this.memorySpaces.list();
1507
+ const serviceItems = this.memorySpaces.providerServices().items;
1503
1508
  const enabled = new Set(serviceItems.filter((service) => service.enabled).map((service) => service.providerId));
1504
- const active = all.filter((body) => body.active && (this.isNativeBody(body) || enabled.has(body.provider.id))).sort((left, right) => left.id.localeCompare(right.id));
1505
- const bodies = [...all].sort((left, right) => left.id.localeCompare(right.id)).map((body) => ({
1509
+ const active = all.filter((body) => body.active && (this.isNativeSpace(body) || enabled.has(body.provider.id))).sort((left, right) => left.id.localeCompare(right.id));
1510
+ const spaces = [...all].sort((left, right) => left.id.localeCompare(right.id)).map((body) => ({
1506
1511
  id: body.id,
1507
1512
  name: body.name,
1508
1513
  description: body.description,
@@ -1520,19 +1525,19 @@ var MemorySpacesService = class {
1520
1525
  all,
1521
1526
  active,
1522
1527
  revision: createHash("sha256").update(JSON.stringify({
1523
- bodies,
1528
+ bodies: spaces,
1524
1529
  services
1525
1530
  })).digest("hex")
1526
1531
  };
1527
1532
  }
1528
1533
  /** Return a usable system snapshot without waiting for any Provider I/O. */
1529
1534
  statusSummary() {
1530
- const catalog = this.bodyDirectory();
1535
+ const catalog = this.spaceDirectory();
1531
1536
  const dshActiveStores = catalog.items.filter((body) => body.active && body.providerEnabled !== false).map((body) => body.id);
1532
- const providerServices = this.memoryBodies.providerServices().items.map((service) => {
1537
+ const providerServices = this.memorySpaces.providerServices().items.map((service) => {
1533
1538
  const descriptor = this.providerCatalog.descriptor(service.providerId);
1534
- const bodies = catalog.items.filter((body) => body.provider.id === service.providerId);
1535
- const activeBodies = bodies.filter((body) => body.active && body.providerEnabled !== false);
1539
+ const spaces = catalog.items.filter((body) => body.provider.id === service.providerId);
1540
+ const activeSpaces = spaces.filter((body) => body.active && body.providerEnabled !== false);
1536
1541
  return {
1537
1542
  providerId: service.providerId,
1538
1543
  label: descriptor.label,
@@ -1540,8 +1545,8 @@ var MemorySpacesService = class {
1540
1545
  enabled: service.enabled,
1541
1546
  configured: service.configured,
1542
1547
  status: !service.enabled ? "disabled" : "idle",
1543
- memoryBodyCount: bodies.length,
1544
- activeMemoryBodyCount: activeBodies.length
1548
+ memoryBodyCount: spaces.length,
1549
+ activeMemoryBodyCount: activeSpaces.length
1545
1550
  };
1546
1551
  });
1547
1552
  return {
@@ -1581,9 +1586,9 @@ var MemorySpacesService = class {
1581
1586
  };
1582
1587
  }
1583
1588
  async status(signal) {
1584
- const hasNativeBody = this.memoryBodies.list().some((body) => this.isNativeBody(body));
1589
+ const hasNativeSpace = this.memorySpaces.list().some((body) => this.isNativeSpace(body));
1585
1590
  let versionError;
1586
- const [catalog, rawVersion] = await Promise.all([this.bodies(signal), hasNativeBody ? this.runner.runText(["--version"], signal === void 0 ? { globalFlags: false } : {
1591
+ const [catalog, rawVersion] = await Promise.all([this.spaces(signal), hasNativeSpace ? this.runner.runText(["--version"], signal === void 0 ? { globalFlags: false } : {
1587
1592
  signal,
1588
1593
  globalFlags: false
1589
1594
  }).catch((error) => {
@@ -1591,12 +1596,12 @@ var MemorySpacesService = class {
1591
1596
  }) : Promise.resolve(void 0)]);
1592
1597
  const active = catalog.items.filter((body) => body.active && body.providerEnabled !== false);
1593
1598
  const dshActiveStores = active.map((body) => body.id);
1594
- const providerServices = this.memoryBodies.providerServices().items.map((service) => {
1599
+ const providerServices = this.memorySpaces.providerServices().items.map((service) => {
1595
1600
  const descriptor = this.providerCatalog.descriptor(service.providerId);
1596
- const bodies = catalog.items.filter((body) => body.provider.id === service.providerId);
1597
- const activeBodies = bodies.filter((body) => body.active && body.providerEnabled !== false);
1598
- const failed = activeBodies.filter((body) => !body.healthy);
1599
- const status = !service.enabled ? "disabled" : activeBodies.length === 0 ? "idle" : failed.length === 0 ? "healthy" : "unhealthy";
1601
+ const spaces = catalog.items.filter((body) => body.provider.id === service.providerId);
1602
+ const activeSpaces = spaces.filter((body) => body.active && body.providerEnabled !== false);
1603
+ const failed = activeSpaces.filter((body) => !body.healthy);
1604
+ const status = !service.enabled ? "disabled" : activeSpaces.length === 0 ? "idle" : failed.length === 0 ? "healthy" : "unhealthy";
1600
1605
  return {
1601
1606
  providerId: service.providerId,
1602
1607
  label: descriptor.label,
@@ -1604,8 +1609,8 @@ var MemorySpacesService = class {
1604
1609
  enabled: service.enabled,
1605
1610
  configured: service.configured,
1606
1611
  status,
1607
- memoryBodyCount: bodies.length,
1608
- activeMemoryBodyCount: activeBodies.length,
1612
+ memoryBodyCount: spaces.length,
1613
+ activeMemoryBodyCount: activeSpaces.length,
1609
1614
  ...failed.length === 0 ? {} : { error: failed.map((body) => `${body.name}: ${body.error ?? "unavailable"}`).join("; ") }
1610
1615
  };
1611
1616
  });
@@ -1626,19 +1631,19 @@ var MemorySpacesService = class {
1626
1631
  };
1627
1632
  try {
1628
1633
  if (versionError !== void 0) throw versionError;
1629
- const healthyBodies = active.filter((body) => body.healthy && body.stats !== void 0);
1634
+ const healthySpaces = active.filter((body) => body.healthy && body.stats !== void 0);
1630
1635
  const topEntities = /* @__PURE__ */ new Map();
1631
1636
  const byCategory = {};
1632
- for (const body of healthyBodies) {
1637
+ for (const body of healthySpaces) {
1633
1638
  for (const [category, count] of Object.entries(body.stats.byCategory)) byCategory[category] = (byCategory[category] ?? 0) + count;
1634
1639
  for (const entity of body.stats.topEntities) topEntities.set(entity.entity, (topEntities.get(entity.entity) ?? 0) + entity.count);
1635
1640
  }
1636
1641
  const stats = {
1637
- totalInsights: healthyBodies.reduce((total, body) => total + body.stats.totalInsights, 0),
1638
- deletedInsights: healthyBodies.reduce((total, body) => total + body.stats.deletedInsights, 0),
1639
- edgeCount: healthyBodies.reduce((total, body) => total + body.stats.edgeCount, 0),
1640
- oplogCount: healthyBodies.reduce((total, body) => total + body.stats.oplogCount, 0),
1641
- dbSizeBytes: healthyBodies.reduce((total, body) => total + body.stats.dbSizeBytes, 0),
1642
+ totalInsights: healthySpaces.reduce((total, body) => total + body.stats.totalInsights, 0),
1643
+ deletedInsights: healthySpaces.reduce((total, body) => total + body.stats.deletedInsights, 0),
1644
+ edgeCount: healthySpaces.reduce((total, body) => total + body.stats.edgeCount, 0),
1645
+ oplogCount: healthySpaces.reduce((total, body) => total + body.stats.oplogCount, 0),
1646
+ dbSizeBytes: healthySpaces.reduce((total, body) => total + body.stats.dbSizeBytes, 0),
1642
1647
  byCategory,
1643
1648
  topEntities: [...topEntities].map(([entity, count]) => ({
1644
1649
  entity,
@@ -1662,11 +1667,11 @@ var MemorySpacesService = class {
1662
1667
  };
1663
1668
  }
1664
1669
  }
1665
- async reconnectBody(id, signal) {
1666
- const body = this.memoryBodies.list().find((candidate) => candidate.id === id);
1667
- if (body === void 0) throw new Error(`unknown memory body: ${id}`);
1668
- if (!this.isNativeBody(body)) {
1669
- if (!this.memoryBodies.providerServiceEnabled(body.provider.id)) throw new Error(`${body.provider.label} is disabled in Settings`);
1670
+ async reconnectSpace(id, signal) {
1671
+ const body = this.memorySpaces.list().find((candidate) => candidate.id === id);
1672
+ if (body === void 0) throw new Error(`unknown memory space: ${id}`);
1673
+ if (!this.isNativeSpace(body)) {
1674
+ if (!this.memorySpaces.providerServiceEnabled(body.provider.id)) throw new Error(`${body.provider.label} is disabled in Settings`);
1670
1675
  }
1671
1676
  const provider = this.providerFor(body);
1672
1677
  provider.invalidateStatus?.(body.id);
@@ -1674,7 +1679,7 @@ var MemorySpacesService = class {
1674
1679
  return {
1675
1680
  ...body,
1676
1681
  providerEnabled: true,
1677
- mnemonDefault: this.isNativeBody(body) && body.id === this.runner.persistedStore(),
1682
+ mnemonDefault: this.isNativeSpace(body) && body.id === this.runner.persistedStore(),
1678
1683
  ...status
1679
1684
  };
1680
1685
  }
@@ -1694,7 +1699,7 @@ var MemorySpacesService = class {
1694
1699
  const category = allowed(request.category, CATEGORIES$1, "category");
1695
1700
  const source = allowed(request.source, SOURCES$1, "source");
1696
1701
  const intent = allowed(request.intent, INTENTS$1, "intent");
1697
- const bodies = this.readBodies(request.memoryBodyIds);
1702
+ const spaces = this.readSpaces(request.memoryBodyIds);
1698
1703
  const normalizedRequest = {
1699
1704
  query,
1700
1705
  mode,
@@ -1703,7 +1708,7 @@ var MemorySpacesService = class {
1703
1708
  ...source === void 0 ? {} : { source },
1704
1709
  ...intent === void 0 ? {} : { intent }
1705
1710
  };
1706
- let batches = await Promise.all(bodies.map(async (body) => {
1711
+ let batches = await Promise.all(spaces.map(async (body) => {
1707
1712
  if (!body.provider.capabilities.search) return {
1708
1713
  body,
1709
1714
  result: {
@@ -1747,7 +1752,7 @@ var MemorySpacesService = class {
1747
1752
  })));
1748
1753
  if (result.hint !== void 0) hints.push(`${body.name}: ${result.hint}`);
1749
1754
  }
1750
- const heterogeneous = new Set(bodies.map((body) => body.provider.id)).size > 1;
1755
+ const heterogeneous = new Set(spaces.map((body) => body.provider.id)).size > 1;
1751
1756
  if (heterogeneous) for (const candidate of candidates) candidate.insight.federatedScore = 1 / (60 + candidate.providerRank);
1752
1757
  candidates.sort((left, right) => heterogeneous ? (right.insight.federatedScore ?? 0) - (left.insight.federatedScore ?? 0) || left.bodyOrder - right.bodyOrder : (right.insight.score ?? 0) - (left.insight.score ?? 0));
1753
1758
  return {
@@ -1759,7 +1764,7 @@ var MemorySpacesService = class {
1759
1764
  const hasRecoveryEvidence = recoveryPlan !== void 0 && evaluation.quality.selected.some((candidate) => recoveryMatchCount(candidate.candidate.insight.content, recoveryPlan) >= recoveryPlan.requiredMatches);
1760
1765
  if (recoveryPlan !== void 0 && !hasRecoveryEvidence) {
1761
1766
  batches = await Promise.all(batches.map(async (batch) => {
1762
- if (!this.isNativeBody(batch.body) || batch.source.status === "unsupported" || batch.source.status === "unavailable") return batch;
1767
+ if (!this.isNativeSpace(batch.body) || batch.source.status === "unsupported" || batch.source.status === "unavailable") return batch;
1763
1768
  try {
1764
1769
  const recovered = await this.providerFor(batch.body).search(batch.body, {
1765
1770
  query: recoveryPlan.query,
@@ -1829,12 +1834,12 @@ var MemorySpacesService = class {
1829
1834
  * expansion, and large browse projections before an LLM metadata pass.
1830
1835
  */
1831
1836
  async metadataSample(memoryBodyId, signal) {
1832
- const body = this.readBodies([memoryBodyId])[0];
1837
+ const body = this.readSpaces([memoryBodyId])[0];
1833
1838
  const provider = this.providerFor(body);
1834
1839
  const limit = 6;
1835
1840
  let method;
1836
1841
  let items;
1837
- if (this.isNativeBody(body)) {
1842
+ if (this.isNativeSpace(body)) {
1838
1843
  method = "native-basic";
1839
1844
  items = provider.metadataSample === void 0 ? await provider.list(body, { limit }, signal) : await provider.metadataSample(body, limit, signal);
1840
1845
  } else if (METADATA_SEARCH_FIRST_PROVIDERS.has(body.provider.typeId ?? body.provider.id) || !body.provider.capabilities.browse) {
@@ -1864,11 +1869,11 @@ var MemorySpacesService = class {
1864
1869
  };
1865
1870
  }
1866
1871
  async graph(signal, memoryBodyIds) {
1867
- const bodies = this.readBodies(memoryBodyIds);
1872
+ const spaces = this.readSpaces(memoryBodyIds);
1868
1873
  const nodes = [];
1869
1874
  const edges = [];
1870
1875
  const sources = [];
1871
- const snapshots = await Promise.all(bodies.map(async (body) => {
1876
+ const snapshots = await Promise.all(spaces.map(async (body) => {
1872
1877
  const mode = body.provider.capabilities.graph ? "graph" : body.provider.capabilities.browse ? "projection" : body.provider.capabilities.search ? "query-only" : "unsupported";
1873
1878
  if (mode === "query-only") return {
1874
1879
  body,
@@ -1921,7 +1926,7 @@ var MemorySpacesService = class {
1921
1926
  nodes,
1922
1927
  edges,
1923
1928
  generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1924
- memoryBodies: bodies.map(({ id, name, active }) => ({
1929
+ memoryBodies: spaces.map(({ id, name, active }) => ({
1925
1930
  id,
1926
1931
  name,
1927
1932
  active
@@ -1935,8 +1940,8 @@ var MemorySpacesService = class {
1935
1940
  if (rawQuery.length > 500) throw new Error("query is too long (max 500 characters)");
1936
1941
  const category = allowed(request.category, CATEGORIES$1, "category");
1937
1942
  const limit = boundedInteger(request.limit, 200, 1, 1e3);
1938
- const bodies = this.readBodies(request.memoryBodyIds);
1939
- const batches = await Promise.all(bodies.map(async (body) => {
1943
+ const spaces = this.readSpaces(request.memoryBodyIds);
1944
+ const batches = await Promise.all(spaces.map(async (body) => {
1940
1945
  const mode = body.provider.capabilities.browse ? "enumerable" : body.provider.capabilities.search ? "query-only" : "unsupported";
1941
1946
  if (mode === "query-only" && rawQuery === "") return {
1942
1947
  body,
@@ -1982,7 +1987,7 @@ var MemorySpacesService = class {
1982
1987
  };
1983
1988
  }
1984
1989
  async entities(entity, limit, signal) {
1985
- const active = (await this.bodies(signal)).items.filter((body) => body.active);
1990
+ const active = (await this.spaces(signal)).items.filter((body) => body.active);
1986
1991
  const capable = active.filter((body) => body.provider.capabilities.entities);
1987
1992
  const entityCounts = /* @__PURE__ */ new Map();
1988
1993
  for (const body of capable) for (const item of body.stats?.topEntities ?? []) entityCounts.set(item.entity, (entityCounts.get(item.entity) ?? 0) + item.count);
@@ -2042,7 +2047,7 @@ var MemorySpacesService = class {
2042
2047
  const provider = this.providerFor(body);
2043
2048
  let providerChanged = false;
2044
2049
  const batchWriter = provider.rememberMany;
2045
- const batch = batchWriter === void 0 ? [] : group.filter((entry) => !this.isNativeBody(body) || entry.request.content.length <= 8e3);
2050
+ const batch = batchWriter === void 0 ? [] : group.filter((entry) => !this.isNativeSpace(body) || entry.request.content.length <= 8e3);
2046
2051
  if (batchWriter !== void 0 && batch.length > 0) {
2047
2052
  const written = await batchWriter.call(provider, body, batch.map((entry) => entry.request), signal);
2048
2053
  if (written.length !== batch.length) throw new Error(`batch remember did not return one receipt per request for Memory Space ${body.id}`);
@@ -2063,7 +2068,7 @@ var MemorySpacesService = class {
2063
2068
  return results;
2064
2069
  }
2065
2070
  async related(id, depth = 2, edge, signal, memoryBodyId) {
2066
- const body = this.readBody(memoryBodyId);
2071
+ const body = this.readSpace(memoryBodyId);
2067
2072
  const selectedEdge = allowed(edge, EDGE_TYPES, "edge");
2068
2073
  const provider = this.providerFor(body);
2069
2074
  if (provider.related === void 0 || !body.provider.capabilities.related) throw new Error(`${body.provider.label} does not support related-memory traversal`);
@@ -2071,7 +2076,7 @@ var MemorySpacesService = class {
2071
2076
  }
2072
2077
  async link(sourceId, targetId, type = "semantic", weight = .5, reason, signal, memoryBodyId) {
2073
2078
  this.assertWritable();
2074
- const body = this.writeBody(memoryBodyId);
2079
+ const body = this.writeSpace(memoryBodyId);
2075
2080
  if (!Number.isFinite(weight) || weight < 0 || weight > 1) throw new Error("weight must be within 0..1");
2076
2081
  const selectedType = allowed(type, EDGE_TYPES, "type") ?? "semantic";
2077
2082
  const provider = this.providerFor(body);
@@ -2082,35 +2087,35 @@ var MemorySpacesService = class {
2082
2087
  }
2083
2088
  async forget(id, signal, memoryBodyId) {
2084
2089
  this.assertWritable();
2085
- const body = this.writeBody(memoryBodyId);
2090
+ const body = this.writeSpace(memoryBodyId);
2086
2091
  const provider = this.providerFor(body);
2087
2092
  if (provider.forget === void 0 || !body.provider.capabilities.forget) throw new Error(`${body.provider.label} does not expose safe forget semantics in this integration`);
2088
2093
  const result = await provider.forget(body, required(id, "id", 2e3), signal);
2089
2094
  this.activateAfterWrite(body, mutationResultCommitted(result));
2090
2095
  return this.annotateResult(result, body);
2091
2096
  }
2092
- prepareBodyPlacement(request) {
2097
+ prepareSpacePlacement(request) {
2093
2098
  if (request.placement === void 0) throw new Error("automatic provider placement request is required");
2094
2099
  if (request.providerId !== void 0) throw new Error("automatic provider placement cannot include a fixed providerId");
2095
- return prepareMemoryPlacement(request.placement, this.memoryBodies.placementCandidates(request));
2100
+ return prepareMemoryPlacement(request.placement, this.memorySpaces.placementCandidates(request));
2096
2101
  }
2097
- async createBody(request, signal, placement) {
2102
+ async createSpace(request, signal, placement) {
2098
2103
  this.assertWritable();
2099
- return await this.memoryBodies.create(request, signal, placement);
2104
+ return await this.memorySpaces.create(request, signal, placement);
2100
2105
  }
2101
2106
  /**
2102
2107
  * Create a Memory Space from the configured distillation policy. The model
2103
2108
  * may choose only among candidates already filtered by the host; manual mode
2104
2109
  * ignores model preference and always uses the configured fixed provider.
2105
2110
  */
2106
- async createBodyForPersistence(body, selection, signal, delegation = {
2111
+ async createSpaceForPersistence(body, selection, signal, delegation = {
2107
2112
  runId: "memory-write",
2108
2113
  provider: "task-agent"
2109
2114
  }) {
2110
2115
  const strategy = this.config.persistenceStrategy;
2111
2116
  if (strategy.mode === "manual") {
2112
2117
  const connection = strategy.providerConnections[strategy.providerId];
2113
- return this.createBody({
2118
+ return this.createSpace({
2114
2119
  ...body,
2115
2120
  providerId: strategy.providerId,
2116
2121
  ...this.isNativeProvider(strategy.providerId) || connection === void 0 ? {} : { connection }
@@ -2125,45 +2130,45 @@ var MemorySpacesService = class {
2125
2130
  },
2126
2131
  ...Object.keys(strategy.providerConnections).length === 0 ? {} : { providerConnections: strategy.providerConnections }
2127
2132
  };
2128
- const prepared = this.prepareBodyPlacement(request);
2133
+ const prepared = this.prepareSpacePlacement(request);
2129
2134
  const decision = rulesOnlyPlacement(prepared) ?? finalizeLlmPlacement(prepared, selection ?? {
2130
2135
  providerId: "",
2131
2136
  reason: "",
2132
2137
  confidence: ""
2133
2138
  }, delegation);
2134
- return this.createBody(request, signal, decision);
2139
+ return this.createSpace(request, signal, decision);
2135
2140
  }
2136
2141
  async updateProviderService(providerId, settings, clearSecrets = [], enabled = true, signal) {
2137
2142
  this.assertWritable();
2138
2143
  if (this.isNativeProvider(providerId)) throw new Error("Mnemon Native service settings are managed by the native configuration");
2139
- if (!enabled) return this.memoryBodies.updateProviderService(providerId, settings, clearSecrets, false);
2140
- const connection = this.memoryBodies.resolveProviderService(providerId, settings, clearSecrets);
2144
+ if (!enabled) return this.memorySpaces.updateProviderService(providerId, settings, clearSecrets, false);
2145
+ const connection = this.memorySpaces.resolveProviderService(providerId, settings, clearSecrets);
2141
2146
  const provider = this.providers.get(providerId);
2142
2147
  if (provider?.discover === void 0) throw new Error(`${this.providerCatalog.descriptor(providerId).label} does not support Memory Space discovery`);
2143
2148
  const discovered = await provider.discover(connection, signal);
2144
- return this.memoryBodies.syncProviderService(providerId, connection, discovered);
2149
+ return this.memorySpaces.syncProviderService(providerId, connection, discovered);
2145
2150
  }
2146
- updateBody(id, request) {
2151
+ updateSpace(id, request) {
2147
2152
  this.assertWritable();
2148
- return this.memoryBodies.update(id, request);
2153
+ return this.memorySpaces.update(id, request);
2149
2154
  }
2150
- updateBodyMetadata(updates) {
2155
+ updateSpaceMetadata(updates) {
2151
2156
  this.assertWritable();
2152
- return this.memoryBodies.updateMetadata(updates);
2157
+ return this.memorySpaces.updateMetadata(updates);
2153
2158
  }
2154
- async deleteBody(id, signal) {
2159
+ async deleteSpace(id, signal) {
2155
2160
  this.assertWritable();
2156
- return await this.memoryBodies.remove(id, signal);
2161
+ return await this.memorySpaces.remove(id, signal);
2157
2162
  }
2158
- async mergeBodies(targetBodyId, sourceBodyIds, deactivateSources = true, signal) {
2163
+ async mergeSpaces(targetSpaceId, sourceSpaceIds, deactivateSources = true, signal) {
2159
2164
  this.assertWritable();
2160
- const target = this.memoryBodies.get(targetBodyId);
2161
- if (!this.isNativeBody(target)) throw new Error("memory-body merge currently requires a Mnemon Native target");
2162
- const sourceIds = [...new Set(sourceBodyIds.map((id) => id.trim()).filter((id) => id !== ""))];
2163
- if (sourceIds.length === 0) throw new Error("sourceMemoryBodyIds requires at least one memory body");
2164
- if (sourceIds.includes(target.id)) throw new Error("target memory body cannot also be a merge source");
2165
- const sources = sourceIds.map((id) => this.memoryBodies.get(id));
2166
- if (sources.some((source) => !this.isNativeBody(source))) throw new Error("memory-body merge currently supports Mnemon Native sources only");
2165
+ const target = this.memorySpaces.get(targetSpaceId);
2166
+ if (!this.isNativeSpace(target)) throw new Error("memory-space merge currently requires a Mnemon Native target");
2167
+ const sourceIds = [...new Set(sourceSpaceIds.map((id) => id.trim()).filter((id) => id !== ""))];
2168
+ if (sourceIds.length === 0) throw new Error("sourceMemoryBodyIds requires at least one memory space");
2169
+ if (sourceIds.includes(target.id)) throw new Error("target memory space cannot also be a merge source");
2170
+ const sources = sourceIds.map((id) => this.memorySpaces.get(id));
2171
+ if (sources.some((source) => !this.isNativeSpace(source))) throw new Error("memory-space merge currently supports Mnemon Native sources only");
2167
2172
  const insights = [];
2168
2173
  const edges = [];
2169
2174
  for (const source of sources) {
@@ -2196,7 +2201,7 @@ var MemorySpacesService = class {
2196
2201
  if (insights.length === 0) {
2197
2202
  if (deactivateSources) for (const source of sources) {
2198
2203
  if (!source.active) continue;
2199
- this.memoryBodies.setActive(source.id, false);
2204
+ this.memorySpaces.setActive(source.id, false);
2200
2205
  }
2201
2206
  return {
2202
2207
  action: "merged",
@@ -2233,7 +2238,7 @@ var MemorySpacesService = class {
2233
2238
  this.activateAfterWrite(target, complete);
2234
2239
  if (deactivateSources && complete) for (const source of sources) {
2235
2240
  if (!source.active) continue;
2236
- this.memoryBodies.setActive(source.id, false);
2241
+ this.memorySpaces.setActive(source.id, false);
2237
2242
  }
2238
2243
  const completion = mutationResultCompletion(result);
2239
2244
  return this.annotateResult({
@@ -2252,39 +2257,39 @@ var MemorySpacesService = class {
2252
2257
  if (provider === void 0) throw new Error(`unsupported memory provider: ${body.provider.id}`);
2253
2258
  return provider;
2254
2259
  }
2255
- readBodies(ids) {
2256
- const active = this.memoryBodies.active();
2260
+ readSpaces(ids) {
2261
+ const active = this.memorySpaces.active();
2257
2262
  if (ids === void 0 || ids.length === 0) return active;
2258
2263
  return [...new Set(ids.map((id) => id.trim()).filter((id) => id !== ""))].map((id) => {
2259
- const body = this.memoryBodies.get(id);
2260
- if (!body.active) throw new Error(`memory body is not active for reading: ${id}`);
2261
- if (!this.isNativeBody(body) && !this.memoryBodies.providerServiceEnabled(body.provider.id)) throw new Error(`${body.provider.label} is disabled in Settings`);
2264
+ const body = this.memorySpaces.get(id);
2265
+ if (!body.active) throw new Error(`memory space is not active for reading: ${id}`);
2266
+ if (!this.isNativeSpace(body) && !this.memorySpaces.providerServiceEnabled(body.provider.id)) throw new Error(`${body.provider.label} is disabled in Settings`);
2262
2267
  return body;
2263
2268
  });
2264
2269
  }
2265
- readBody(id) {
2270
+ readSpace(id) {
2266
2271
  if (id !== void 0 && id.trim() !== "") {
2267
- const body = this.memoryBodies.get(id);
2268
- if (!body.active) throw new Error(`memory body is not active for reading: ${body.id}`);
2269
- if (!this.isNativeBody(body) && !this.memoryBodies.providerServiceEnabled(body.provider.id)) throw new Error(`${body.provider.label} is disabled in Settings`);
2272
+ const body = this.memorySpaces.get(id);
2273
+ if (!body.active) throw new Error(`memory space is not active for reading: ${body.id}`);
2274
+ if (!this.isNativeSpace(body) && !this.memorySpaces.providerServiceEnabled(body.provider.id)) throw new Error(`${body.provider.label} is disabled in Settings`);
2270
2275
  return body;
2271
2276
  }
2272
- const active = this.memoryBodies.active();
2273
- if (active.length !== 1) throw new Error("memoryBodyId is required when the number of active memory bodies is not exactly one");
2277
+ const active = this.memorySpaces.active();
2278
+ if (active.length !== 1) throw new Error("memoryBodyId is required when the number of active memory spaces is not exactly one");
2274
2279
  return active[0];
2275
2280
  }
2276
- writeBody(id) {
2281
+ writeSpace(id) {
2277
2282
  if (id !== void 0 && id.trim() !== "") {
2278
- const body = this.memoryBodies.get(id);
2279
- if (!this.isNativeBody(body) && !this.memoryBodies.providerServiceEnabled(body.provider.id)) throw new Error(`${body.provider.label} is disabled in Settings`);
2283
+ const body = this.memorySpaces.get(id);
2284
+ if (!this.isNativeSpace(body) && !this.memorySpaces.providerServiceEnabled(body.provider.id)) throw new Error(`${body.provider.label} is disabled in Settings`);
2280
2285
  return body;
2281
2286
  }
2282
- const active = this.memoryBodies.active();
2283
- if (active.length !== 1) throw new Error("memoryBodyId is required when the number of active memory bodies is not exactly one");
2287
+ const active = this.memorySpaces.active();
2288
+ if (active.length !== 1) throw new Error("memoryBodyId is required when the number of active memory spaces is not exactly one");
2284
2289
  return active[0];
2285
2290
  }
2286
2291
  prepareRemember(request) {
2287
- const body = this.writeBody(request.memoryBodyId);
2292
+ const body = this.writeSpace(request.memoryBodyId);
2288
2293
  const content = required(request.content, "content", 8192);
2289
2294
  const importance = boundedInteger(request.importance, 3, 1, 5);
2290
2295
  const category = allowed(request.category, CATEGORIES$1, "category") ?? "general";
@@ -2326,84 +2331,57 @@ var MemorySpacesService = class {
2326
2331
  }
2327
2332
  activateAfterWrite(body, providerChanged) {
2328
2333
  if (!providerChanged) return;
2329
- if (!body.active) this.memoryBodies.setActive(body.id, true);
2330
- else this.memoryBodies.touch(body.id);
2334
+ if (!body.active) this.memorySpaces.setActive(body.id, true);
2335
+ else this.memorySpaces.touch(body.id);
2331
2336
  }
2332
2337
  assertWritable() {
2333
2338
  if (!this.config.writeEnabled) throw new Error("dsh-mnemon is configured read-only (writeEnabled: false)");
2334
2339
  }
2340
+ /** @deprecated Use spaces. */
2341
+ bodies(...args) {
2342
+ return this.spaces(...args);
2343
+ }
2344
+ /** @deprecated Use spaceDirectory. */
2345
+ bodyDirectory(...args) {
2346
+ return this.spaceDirectory(...args);
2347
+ }
2348
+ /** @deprecated Use reconnectSpace. */
2349
+ reconnectBody(...args) {
2350
+ return this.reconnectSpace(...args);
2351
+ }
2352
+ /** @deprecated Use prepareSpacePlacement. */
2353
+ prepareBodyPlacement(...args) {
2354
+ return this.prepareSpacePlacement(...args);
2355
+ }
2356
+ /** @deprecated Use createSpace. */
2357
+ createBody(...args) {
2358
+ return this.createSpace(...args);
2359
+ }
2360
+ /** @deprecated Use createSpaceForPersistence. */
2361
+ createBodyForPersistence(...args) {
2362
+ return this.createSpaceForPersistence(...args);
2363
+ }
2364
+ /** @deprecated Use updateSpace. */
2365
+ updateBody(...args) {
2366
+ return this.updateSpace(...args);
2367
+ }
2368
+ /** @deprecated Use updateSpaceMetadata. */
2369
+ updateBodyMetadata(...args) {
2370
+ return this.updateSpaceMetadata(...args);
2371
+ }
2372
+ /** @deprecated Use deleteSpace. */
2373
+ deleteBody(...args) {
2374
+ return this.deleteSpace(...args);
2375
+ }
2376
+ /** @deprecated Use mergeSpaces. */
2377
+ mergeBodies(...args) {
2378
+ return this.mergeSpaces(...args);
2379
+ }
2335
2380
  };
2336
2381
  //#endregion
2337
2382
  //#region src/runner.ts
2338
- const UNIX_COMMON_CLI_PATHS = [
2339
- "~/.local/bin/mnemon",
2340
- "/opt/homebrew/bin/mnemon",
2341
- "/usr/local/bin/mnemon",
2342
- "/usr/bin/mnemon"
2343
- ];
2344
- function pathApi(platform) {
2345
- return platform === "win32" ? win32 : posix;
2346
- }
2347
- function expandHome(path, home = homedir(), platform = process.platform) {
2348
- if (path === "~") return home;
2349
- return path.startsWith("~/") || path.startsWith("~\\") ? pathApi(platform).join(home, path.slice(2)) : path;
2350
- }
2351
- function envValue(env, name, platform) {
2352
- if (platform !== "win32") return env[name];
2353
- const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
2354
- return key === void 0 ? void 0 : env[key];
2355
- }
2356
- function executable(path, platform = process.platform) {
2357
- if (platform === "win32" && win32.extname(path).toLowerCase() !== ".exe") return false;
2358
- try {
2359
- accessSync(path, platform === "win32" ? constants.F_OK : constants.X_OK);
2360
- return statSync(path).isFile();
2361
- } catch {
2362
- return false;
2363
- }
2364
- }
2365
- function windowsCommonCliPaths(env, home) {
2366
- const candidates = [];
2367
- const goBin = envValue(env, "GOBIN", "win32")?.trim();
2368
- if (goBin !== void 0 && win32.isAbsolute(goBin)) candidates.push(win32.join(goBin, "mnemon.exe"));
2369
- const goInstallRoot = (envValue(env, "GOPATH", "win32")?.trim())?.split(win32.delimiter).map((candidate) => candidate.trim()).find((candidate) => candidate !== "" && win32.isAbsolute(candidate)) ?? win32.join(home, "go");
2370
- candidates.push(win32.join(goInstallRoot, "bin", "mnemon.exe"));
2371
- const localAppData = envValue(env, "LOCALAPPDATA", "win32")?.trim();
2372
- if (localAppData !== void 0 && win32.isAbsolute(localAppData)) candidates.push(win32.join(localAppData, "Programs", "mnemon", "mnemon.exe"));
2373
- const programFiles = envValue(env, "ProgramFiles", "win32")?.trim();
2374
- if (programFiles !== void 0 && win32.isAbsolute(programFiles)) candidates.push(win32.join(programFiles, "mnemon", "mnemon.exe"));
2375
- return [...new Set(candidates)];
2376
- }
2377
- function commonCliPaths(platform, env, home) {
2378
- if (platform === "win32") return windowsCommonCliPaths(env, home);
2379
- return UNIX_COMMON_CLI_PATHS.map((candidate) => expandHome(candidate, home, platform));
2380
- }
2381
- /** Locate the local Mnemon binary without invoking a shell. */
2382
- function findMnemonCommand(config, options = {}) {
2383
- const platform = options.platform ?? process.platform;
2384
- const env = options.env ?? process.env;
2385
- const home = options.home ?? homedir();
2386
- const isExecutable = options.isExecutable ?? ((path) => executable(path, platform));
2387
- const paths = pathApi(platform);
2388
- const resolveCommand = (command) => {
2389
- const expanded = expandHome(command, home, platform);
2390
- if (expanded.includes("/") || expanded.includes("\\")) return expanded;
2391
- const name = platform === "win32" && paths.extname(expanded) === "" ? `${expanded}.exe` : expanded;
2392
- for (const directory of (envValue(env, "PATH", platform) ?? "").split(paths.delimiter)) {
2393
- if (directory === "") continue;
2394
- const path = paths.join(directory, name);
2395
- if (isExecutable(path)) return path;
2396
- }
2397
- };
2398
- if (config.cliPath !== void 0) return resolveCommand(config.cliPath);
2399
- const envPath = envValue(env, "MNEMON_CLI_PATH", platform)?.trim();
2400
- if (envPath !== void 0 && envPath !== "") {
2401
- const path = resolveCommand(envPath);
2402
- if (path !== void 0 && isExecutable(path)) return path;
2403
- }
2404
- const fromPath = resolveCommand("mnemon");
2405
- if (fromPath !== void 0) return fromPath;
2406
- for (const path of commonCliPaths(platform, env, home)) if (isExecutable(path)) return path;
2383
+ function expandHome(path) {
2384
+ return path === "~" ? homedir() : path.startsWith("~/") || path.startsWith("~\\") ? join(homedir(), path.slice(2)) : path;
2407
2385
  }
2408
2386
  var MnemonCliError = class extends Error {
2409
2387
  exitCode;
@@ -2465,7 +2443,9 @@ function createRunner(config, processRunner = runProcess, workspaceRoot) {
2465
2443
  };
2466
2444
  let result;
2467
2445
  try {
2468
- result = await processRunner(currentCommand(), argv, processOptions);
2446
+ const command = currentCommand();
2447
+ const launcher = mnemonNpmLauncher(command);
2448
+ result = await processRunner(launcher === void 0 ? command : process.execPath, launcher === void 0 ? argv : [launcher, ...argv], processOptions);
2469
2449
  } catch (error) {
2470
2450
  throw new MnemonCliError(`${error instanceof Error ? error.message : String(error)}. ${process.platform === "win32" ? "Install the official Mnemon Windows release, ensure mnemon.exe is on PATH or under %LOCALAPPDATA%\\Programs\\mnemon, or set MNEMON_CLI_PATH or mnemon.cliPath to its absolute path." : "Install Mnemon and ensure \"mnemon\" is on PATH, or set MNEMON_CLI_PATH or mnemon.cliPath."}`);
2471
2451
  }
@@ -2484,7 +2464,7 @@ function createRunner(config, processRunner = runProcess, workspaceRoot) {
2484
2464
  },
2485
2465
  get commandFound() {
2486
2466
  const found = findMnemonCommand(config);
2487
- return found !== void 0 && executable(found);
2467
+ return found !== void 0 && isMnemonExecutable(found);
2488
2468
  },
2489
2469
  config,
2490
2470
  async runJson(args, options) {
@@ -2704,7 +2684,7 @@ function providerConnections(value) {
2704
2684
  const input = memoryInputRecord(value, "providerConnections");
2705
2685
  return Object.fromEntries(Object.entries(input).map(([providerId, connection]) => [memoryInputText(providerId, "providerId", 128), scalarRecord(connection, `providerConnections.${providerId}`)]));
2706
2686
  }
2707
- function createBodyRequest(value) {
2687
+ function createSpaceRequest(value) {
2708
2688
  const input = memoryInputRecord(value, "Memory Space body-create request");
2709
2689
  const providerId = memoryInputText(input.providerId, "providerId", 128, false);
2710
2690
  const connection = scalarRecord(input.connection, "connection");
@@ -2733,7 +2713,7 @@ function createBodyRequest(value) {
2733
2713
  ...placement === void 0 ? {} : { placement }
2734
2714
  };
2735
2715
  }
2736
- function updateBodyRequest(value) {
2716
+ function updateSpaceRequest(value) {
2737
2717
  const input = memoryInputRecord(value, "Memory Space body-update request");
2738
2718
  const connection = scalarRecord(input.connection, "connection");
2739
2719
  return {
@@ -2775,9 +2755,9 @@ async function manageMemorySpaces(service, request) {
2775
2755
  case "embedding-status": return managementResult(service, await service.embeddingStatus(request.signal));
2776
2756
  case "status-summary": return managementResult(service, service.statusSummary());
2777
2757
  case "status": return managementResult(service, await service.status(request.signal));
2778
- case "body-directory": return managementResult(service, service.bodyDirectory());
2779
- case "bodies": return managementResult(service, await service.bodies(request.signal));
2780
- case "provider-services": return managementResult(service, service.memoryBodies.providerServices());
2758
+ case "body-directory": return managementResult(service, service.spaceDirectory());
2759
+ case "bodies": return managementResult(service, await service.spaces(request.signal));
2760
+ case "provider-services": return managementResult(service, service.memorySpaces.providerServices());
2781
2761
  case "graph": return managementResult(service, await service.graph(request.signal, memoryInputStringArray(input.memoryBodyIds, "memoryBodyIds", 1e4)));
2782
2762
  case "list": return managementResult(service, await service.list({
2783
2763
  ...memoryInputText(input.query, "query", 2e3, false) === void 0 ? {} : { query: memoryInputText(input.query, "query", 2e3, false) },
@@ -2796,8 +2776,8 @@ async function manageMemorySpaces(service, request) {
2796
2776
  ...memoryInputStringArray(input.memoryBodyIds, "memoryBodyIds", 1e4) === void 0 ? {} : { memoryBodyIds: memoryInputStringArray(input.memoryBodyIds, "memoryBodyIds", 1e4) }
2797
2777
  }, request.signal));
2798
2778
  case "related": return managementResult(service, await service.related(memoryInputText(input.id, "id", 2e3), memoryInputInteger(input.depth, 2, 1, 5), memoryInputText(input.edge, "edge", 30, false), request.signal, memoryInputText(input.memoryBodyId, "memoryBodyId", 300, false)));
2799
- case "body-reconnect": return managementResult(service, await service.reconnectBody(memoryInputText(input.memoryBodyId, "memoryBodyId", 300), request.signal));
2800
- case "prepare-body-placement": return managementResult(service, service.prepareBodyPlacement(createBodyRequest(request.input)));
2779
+ case "body-reconnect": return managementResult(service, await service.reconnectSpace(memoryInputText(input.memoryBodyId, "memoryBodyId", 300), request.signal));
2780
+ case "prepare-body-placement": return managementResult(service, service.prepareSpacePlacement(createSpaceRequest(request.input)));
2801
2781
  case "finalize-placement": {
2802
2782
  const prepared = memoryInputRecord(input.prepared, "prepared placement");
2803
2783
  if (!Array.isArray(prepared.candidates) || prepared.candidates.length === 0) throw new Error("placement candidates are required");
@@ -2819,7 +2799,7 @@ async function manageMemorySpaces(service, request) {
2819
2799
  case "provider-service-update": {
2820
2800
  const providerId = memoryInputText(input.providerId, "providerId", 128);
2821
2801
  await service.updateProviderService(providerId, scalarRecord(input.settings, "settings") ?? {}, memoryInputStringArray(input.clearSecrets, "clearSecrets", 100) ?? [], input.enabled === void 0 ? true : input.enabled === true, request.signal);
2822
- return managementResult(service, service.memoryBodies.providerServices().items.find((item) => item.providerId === providerId));
2802
+ return managementResult(service, service.memorySpaces.providerServices().items.find((item) => item.providerId === providerId));
2823
2803
  }
2824
2804
  case "remember": return managementResult(service, await service.remember({
2825
2805
  content: memoryInputText(input.content, "content", 1e5),
@@ -2834,18 +2814,18 @@ async function manageMemorySpaces(service, request) {
2834
2814
  case "forget": return managementResult(service, await service.forget(memoryInputText(input.id, "id", 2e3), request.signal, memoryInputText(input.memoryBodyId, "memoryBodyId", 300, false)));
2835
2815
  case "body-create": {
2836
2816
  const bodyInput = input.request ?? request.input;
2837
- return managementResult(service, await service.createBody(createBodyRequest(bodyInput), request.signal, placementDecision(input.placementDecision)));
2817
+ return managementResult(service, await service.createSpace(createSpaceRequest(bodyInput), request.signal, placementDecision(input.placementDecision)));
2838
2818
  }
2839
2819
  case "body-update": {
2840
- const parsed = updateBodyRequest(request.input);
2841
- return managementResult(service, service.updateBody(parsed.memoryBodyId, parsed.request));
2820
+ const parsed = updateSpaceRequest(request.input);
2821
+ return managementResult(service, service.updateSpace(parsed.memoryBodyId, parsed.request));
2842
2822
  }
2843
2823
  case "remember-many":
2844
2824
  if (!Array.isArray(input.requests) || input.requests.length > 1e3) throw new Error("remember-many requires at most 1000 requests");
2845
2825
  return managementResult(service, await service.rememberMany(input.requests.map((value) => memoryInputRecord(value, "remember request")), request.signal));
2846
2826
  case "body-create-for-persistence": {
2847
2827
  const selection = input.selection === void 0 ? void 0 : memoryInputRecord(input.selection, "placement selection");
2848
- return managementResult(service, await service.createBodyForPersistence(createBodyRequest(input.request ?? request.input), selection === void 0 ? void 0 : {
2828
+ return managementResult(service, await service.createSpaceForPersistence(createSpaceRequest(input.request ?? request.input), selection === void 0 ? void 0 : {
2849
2829
  providerId: memoryInputText(selection.providerId, "providerId", 128),
2850
2830
  reason: memoryInputText(selection.reason, "reason", 4e3),
2851
2831
  confidence: memoryInputText(selection.confidence, "confidence", 40)
@@ -2861,13 +2841,13 @@ async function manageMemorySpaces(service, request) {
2861
2841
  description: memoryInputText(update.description, "description", 200)
2862
2842
  };
2863
2843
  });
2864
- return managementResult(service, service.updateBodyMetadata(updates));
2844
+ return managementResult(service, service.updateSpaceMetadata(updates));
2865
2845
  }
2866
- case "body-merge": return managementResult(service, await service.mergeBodies(memoryInputText(input.targetMemoryBodyId, "targetMemoryBodyId", 300), memoryInputStringArray(input.sourceMemoryBodyIds, "sourceMemoryBodyIds", 1e3) ?? [], input.deactivateSources !== false, request.signal));
2846
+ case "body-merge": return managementResult(service, await service.mergeSpaces(memoryInputText(input.targetMemoryBodyId, "targetMemoryBodyId", 300), memoryInputStringArray(input.sourceMemoryBodyIds, "sourceMemoryBodyIds", 1e3) ?? [], input.deactivateSources !== false, request.signal));
2867
2847
  case "reload":
2868
- service.memoryBodies.reload();
2848
+ service.memorySpaces.reload();
2869
2849
  return managementResult(service, { reloaded: true });
2870
- case "body-delete": return managementResult(service, await service.deleteBody(memoryInputText(input.memoryBodyId, "memoryBodyId", 300), request.signal));
2850
+ case "body-delete": return managementResult(service, await service.deleteSpace(memoryInputText(input.memoryBodyId, "memoryBodyId", 300), request.signal));
2871
2851
  default: throw new Error(`unsupported Memory Spaces management mutation operation: ${request.operation}`);
2872
2852
  }
2873
2853
  }
@@ -3199,9 +3179,9 @@ function createMemorySpacesSource(providerSnapshot, config = {}) {
3199
3179
  const known = memoryInputStringArray(memoryInputRecord(request.grant.value, "Memory Spaces scope").knownMemoryBodyIds, "knownMemoryBodyIds", 1e4) ?? allowedBodies;
3200
3180
  let value;
3201
3181
  if (input.section === "directory") {
3202
- const catalog = service.bodyDirectory();
3182
+ const catalog = service.spaceDirectory();
3203
3183
  const owned = createdByView.get(request.view.id);
3204
- value = modelBodyCatalog({
3184
+ value = modelSpaceCatalog({
3205
3185
  ...catalog,
3206
3186
  items: catalog.items.filter((body) => known.includes(body.id) || owned?.has(body.id))
3207
3187
  });
@@ -3219,14 +3199,14 @@ function createMemorySpacesSource(providerSnapshot, config = {}) {
3219
3199
  if (category !== void 0 && !CATEGORIES.has(category)) throw new Error(`unsupported category: ${category}`);
3220
3200
  if (source !== void 0 && !SOURCES.has(source)) throw new Error(`unsupported source: ${source}`);
3221
3201
  if (intent !== void 0 && !INTENTS.has(intent)) throw new Error(`unsupported intent: ${intent}`);
3222
- const requestedBodies = memoryInputStringArray(input.memoryBodyIds, "memoryBodyIds", 1e4) ?? allowedBodies;
3223
- if (requestedBodies.some((id) => !allowedBodies.includes(id))) throw new Error("Recall requested a Memory Space outside this View ReadGrant");
3202
+ const requestedSpaces = memoryInputStringArray(input.memoryBodyIds, "memoryBodyIds", 1e4) ?? allowedBodies;
3203
+ if (requestedSpaces.some((id) => !allowedBodies.includes(id))) throw new Error("Recall requested a Memory Space outside this View ReadGrant");
3224
3204
  const mode = memoryInputText(input.mode, "mode", 20, false);
3225
3205
  const result = await service.search({
3226
3206
  query: memoryInputText(input.query, "query", 2e3),
3227
3207
  ...mode === void 0 ? {} : { mode },
3228
3208
  limit: Math.min(request.route.maxResults ?? 20, memoryInputInteger(input.limit, 10, 1, 20)),
3229
- memoryBodyIds: requestedBodies,
3209
+ memoryBodyIds: requestedSpaces,
3230
3210
  ...category === void 0 ? {} : { category },
3231
3211
  ...source === void 0 ? {} : { source },
3232
3212
  ...intent === void 0 ? {} : { intent }
@@ -3235,10 +3215,10 @@ function createMemorySpacesSource(providerSnapshot, config = {}) {
3235
3215
  }
3236
3216
  if (request.route.sourceRouteId === "related") {
3237
3217
  const id = memoryInputText(input.id, "id", 2e3);
3238
- const requestedBody = memoryInputText(input.memoryBodyId, "memoryBodyId", 300, false);
3218
+ const requestedSpace = memoryInputText(input.memoryBodyId, "memoryBodyId", 300, false);
3239
3219
  const admitted = admittedByView.get(request.view.id);
3240
3220
  const owners = [...admitted?.entries() ?? []].filter(([reference]) => reference.endsWith("/" + id)).map(([, bodyId]) => bodyId);
3241
- const owner = requestedBody === void 0 ? owners.length === 1 ? owners[0] : void 0 : admitted?.get(requestedBody + "/" + id);
3221
+ const owner = requestedSpace === void 0 ? owners.length === 1 ? owners[0] : void 0 : admitted?.get(requestedSpace + "/" + id);
3242
3222
  if (owner === void 0) throw new Error("related-memory traversal requires evidence already admitted by this View");
3243
3223
  if (!allowedBodies.includes(owner)) throw new Error("related-memory owner is outside this View ReadGrant");
3244
3224
  const edge = memoryInputText(input.edge, "edge", 30, false);
@@ -3258,9 +3238,9 @@ function createMemorySpacesSource(providerSnapshot, config = {}) {
3258
3238
  const created = createdByView.get(request.view.id) ?? /* @__PURE__ */ new Set();
3259
3239
  const writeBodies = [.../* @__PURE__ */ new Set([...knownBodies, ...created])];
3260
3240
  const admittedOwner = (id) => {
3261
- const requestedBody = memoryInputText(input.memoryBodyId, "memoryBodyId", 300, false);
3241
+ const requestedSpace = memoryInputText(input.memoryBodyId, "memoryBodyId", 300, false);
3262
3242
  const entries = admittedByView.get(request.view.id);
3263
- if (requestedBody !== void 0) return entries?.get(requestedBody + "/" + id);
3243
+ if (requestedSpace !== void 0) return entries?.get(requestedSpace + "/" + id);
3264
3244
  const owners = [...entries?.entries() ?? []].filter(([reference]) => reference.endsWith("/" + id)).map(([, owner]) => owner);
3265
3245
  return owners.length === 1 ? owners[0] : void 0;
3266
3246
  };
@@ -3269,7 +3249,7 @@ function createMemorySpacesSource(providerSnapshot, config = {}) {
3269
3249
  if (request.offer.sourceActionId === "manage-spaces") {
3270
3250
  if (input.operation === "create") {
3271
3251
  const selection = input.selection === void 0 ? void 0 : memoryInputRecord(input.selection, "placement selection");
3272
- const body = await service.createBodyForPersistence(createBodyRequest(input.request), selection === void 0 ? void 0 : {
3252
+ const body = await service.createSpaceForPersistence(createSpaceRequest(input.request), selection === void 0 ? void 0 : {
3273
3253
  providerId: memoryInputText(selection.providerId, "providerId", 128),
3274
3254
  reason: memoryInputText(selection.reason, "reason", 4e3),
3275
3255
  confidence: memoryInputText(selection.confidence, "confidence", 40)
@@ -3287,7 +3267,7 @@ function createMemorySpacesSource(providerSnapshot, config = {}) {
3287
3267
  } else if (input.operation === "update") {
3288
3268
  bodyId = memoryInputText(input.memoryBodyId, "memoryBodyId", 300);
3289
3269
  if (!writeBodies.includes(bodyId)) throw new Error("Memory Space update is outside this View scope");
3290
- const body = service.updateBody(bodyId, {
3270
+ const body = service.updateSpace(bodyId, {
3291
3271
  ...input.name === void 0 ? {} : { name: memoryInputText(input.name, "name", 100) },
3292
3272
  ...input.description === void 0 ? {} : { description: memoryInputText(input.description, "description", 1e3) },
3293
3273
  ...typeof input.active === "boolean" ? { active: input.active } : {}
@@ -3304,7 +3284,7 @@ function createMemorySpacesSource(providerSnapshot, config = {}) {
3304
3284
  const sources = memoryInputStringArray(input.sourceMemoryBodyIds, "sourceMemoryBodyIds", 20) ?? [];
3305
3285
  if ([target, ...sources].some((id) => !writeBodies.includes(id))) throw new Error("Memory Space merge is outside this View scope");
3306
3286
  bodyId = target;
3307
- result = await service.mergeBodies(target, sources, input.deactivateSources !== false, request.signal);
3287
+ result = await service.mergeSpaces(target, sources, input.deactivateSources !== false, request.signal);
3308
3288
  } else throw new Error("unsupported Memory Space management action");
3309
3289
  } else if (request.offer.sourceActionId === "remember") {
3310
3290
  bodyId = memoryInputText(input.memoryBodyId, "memoryBodyId", 300, false);
@@ -3330,10 +3310,10 @@ function createMemorySpacesSource(providerSnapshot, config = {}) {
3330
3310
  } else if (request.offer.sourceActionId === "link") {
3331
3311
  const sourceId = memoryInputText(input.sourceId, "sourceId", 2e3);
3332
3312
  const targetId = memoryInputText(input.targetId, "targetId", 2e3);
3333
- const sourceBody = admittedOwner(sourceId);
3334
- const targetBody = admittedOwner(targetId);
3335
- if (sourceBody === void 0 || targetBody === void 0 || sourceBody !== targetBody || !allowedBodies.includes(sourceBody)) throw new Error("link requires two evidence items admitted by this View from the same Memory Space");
3336
- bodyId = sourceBody;
3313
+ const sourceSpace = admittedOwner(sourceId);
3314
+ const targetSpace = admittedOwner(targetId);
3315
+ if (sourceSpace === void 0 || targetSpace === void 0 || sourceSpace !== targetSpace || !allowedBodies.includes(sourceSpace)) throw new Error("link requires two evidence items admitted by this View from the same Memory Space");
3316
+ bodyId = sourceSpace;
3337
3317
  const edge = memoryInputText(input.type, "type", 30, false);
3338
3318
  if (edge !== void 0 && !EDGES.has(edge)) throw new Error(`unsupported edge: ${edge}`);
3339
3319
  const weight = typeof input.weight === "number" ? input.weight : .5;
@@ -3453,4 +3433,4 @@ async function apply(ctx, config = { providers: [] }) {
3453
3433
  await installMemorySpaces(ctx, await resolveMemorySpaceProviderEntries(ctx, providers), { config: sourceConfig });
3454
3434
  }
3455
3435
  //#endregion
3456
- export { Config, MemorySpaceProviderDeclarationSchema, apply, inject, installMemorySpaces, memoryPlugin, name, resolveMemorySpaceProviderEntries };
3436
+ export { Config, MemorySpaceProviderDeclarationSchema, apply, inject, installMemorySpaces, memoryPlugin, name, resolveEmbedding, resolveMemorySpaceProviderEntries, resolvePersistenceStrategy, resolveRecallQuality };