@mastra/mongodb 1.25.0 → 1.26.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -5,12 +5,13 @@ let _mastra_core_storage = require("@mastra/core/storage");
5
5
  let _mastra_core_vector = require("@mastra/core/vector");
6
6
  let mongodb = require("mongodb");
7
7
  let _mastra_core_vector_filter = require("@mastra/core/vector/filter");
8
+ let _mastra_core_features = require("@mastra/core/features");
8
9
  let crypto$1 = require("crypto");
9
10
  let _mastra_core_agent = require("@mastra/core/agent");
10
11
  let _mastra_core_evals = require("@mastra/core/evals");
11
12
  let _mastra_core_storage_domains_skills = require("@mastra/core/storage/domains/skills");
12
13
  // package.json
13
- var version = "1.25.0";
14
+ var version = "1.26.0-alpha.1";
14
15
  // src/vector/filter.ts
15
16
  /**
16
17
  * Translator for MongoDB filter queries.
@@ -1729,6 +1730,7 @@ const SNAPSHOT_FIELDS$6 = [
1729
1730
  "description",
1730
1731
  "instructions",
1731
1732
  "model",
1733
+ "modelList",
1732
1734
  "tools",
1733
1735
  "defaultOptions",
1734
1736
  "workflows",
@@ -4769,845 +4771,2026 @@ var MongoDBExperimentsStorage = class MongoDBExperimentsStorage extends _mastra_
4769
4771
  } catch {}
4770
4772
  }
4771
4773
  };
4772
- // src/storage/domains/knowledge/index.ts
4773
- let assertDescriptionWithinBound;
4774
- async function assertKnowledgeDescriptionWithinBoundCompat(description) {
4775
- let assertWithinBound = assertDescriptionWithinBound;
4776
- if (!assertWithinBound) {
4777
- const resolvedAssert = (await import("@mastra/core/storage")).assertKnowledgeDescriptionWithinBound ?? ((value) => {
4778
- if (value !== void 0 && value.length > 400) throw new Error("Knowledge node description exceeds the 400 UTF-16 code unit limit");
4774
+ const KNOWLEDGE_TABLE_NAMES = [
4775
+ "mastra_knowledge_nodes",
4776
+ "mastra_knowledge_records",
4777
+ "mastra_knowledge_mentions",
4778
+ "mastra_knowledge_activity",
4779
+ "mastra_knowledge_semantic_outbox",
4780
+ "mastra_knowledge_node_scopes",
4781
+ "mastra_knowledge_record_scopes",
4782
+ "mastra_knowledge_scope_grants",
4783
+ "mastra_knowledge_access_state",
4784
+ "mastra_knowledge_scope_addresses",
4785
+ "mastra_knowledge_node_addresses",
4786
+ "mastra_knowledge_import_state",
4787
+ "mastra_knowledge_import_runs",
4788
+ "mastra_knowledge_proposals"
4789
+ ];
4790
+ /** Knowledge v1 tables with no v2 equivalent; an explicit schema reset drops them. */
4791
+ const RETIRED_KNOWLEDGE_TABLE_NAMES = ["mastra_knowledge_cursors"];
4792
+ const KNOWLEDGE_PAGES_CORE_FEATURE = "knowledge-pages";
4793
+ const KNOWLEDGE_PAGES_TABLE_NAMES = [
4794
+ "mastra_knowledge_pages",
4795
+ "mastra_knowledge_notes",
4796
+ "mastra_knowledge_note_stamps",
4797
+ "mastra_knowledge_mentions",
4798
+ "mastra_knowledge_pins",
4799
+ "mastra_knowledge_activity",
4800
+ "mastra_knowledge_access_state"
4801
+ ];
4802
+ /** Every Knowledge table any schema version created. Reset drops these and nothing else. */
4803
+ const KNOWLEDGE_RESETTABLE_TABLE_NAMES = [.../* @__PURE__ */ new Set([
4804
+ ...KNOWLEDGE_PAGES_TABLE_NAMES,
4805
+ ...KNOWLEDGE_TABLE_NAMES,
4806
+ ...RETIRED_KNOWLEDGE_TABLE_NAMES
4807
+ ])];
4808
+ /** Schema-1/2 tables whose presence means the store needs a reset before schema 4 can run. */
4809
+ const LEGACY_KNOWLEDGE_TABLE_NAMES = new Set([...KNOWLEDGE_TABLE_NAMES, ...RETIRED_KNOWLEDGE_TABLE_NAMES].filter((name) => !KNOWLEDGE_PAGES_TABLE_NAMES.includes(name)));
4810
+ /**
4811
+ * Classifies what an adapter found before creating schema-4 tables. `tableNames` is every
4812
+ * `mastra_knowledge_*` table present; `schemaVersion` is the state row's version, if any.
4813
+ */
4814
+ function inspectKnowledgePagesSchema(snapshot) {
4815
+ const legacy = snapshot.tableNames.filter((name) => LEGACY_KNOWLEDGE_TABLE_NAMES.has(name));
4816
+ if (legacy.length > 0) return {
4817
+ status: "incompatible-reset-required",
4818
+ schemaVersion: snapshot.schemaVersion ?? null,
4819
+ reason: `found Knowledge tables from an earlier schema (${legacy.join(", ")})`
4820
+ };
4821
+ if (snapshot.schemaVersion === 4) return {
4822
+ status: "compatible",
4823
+ schemaVersion: 4
4824
+ };
4825
+ if (snapshot.schemaVersion === void 0) {
4826
+ const present = snapshot.tableNames.filter((name) => KNOWLEDGE_PAGES_TABLE_NAMES.includes(name));
4827
+ if (present.length === 0) return {
4828
+ status: "uninitialized",
4829
+ schemaVersion: null
4830
+ };
4831
+ return {
4832
+ status: "incompatible-reset-required",
4833
+ schemaVersion: null,
4834
+ reason: `found Knowledge tables (${present.join(", ")}) without a schema version`
4835
+ };
4836
+ }
4837
+ return {
4838
+ status: "incompatible-reset-required",
4839
+ schemaVersion: snapshot.schemaVersion,
4840
+ reason: `Knowledge schema version ${snapshot.schemaVersion} is not 4`
4841
+ };
4842
+ }
4843
+ /** Schema-2 table names schema 4 reuses with a different shape. */
4844
+ const REUSED_KNOWLEDGE_TABLE_NAMES = KNOWLEDGE_TABLE_NAMES.filter((name) => KNOWLEDGE_PAGES_TABLE_NAMES.includes(name));
4845
+ /**
4846
+ * The old Knowledge tables an adapter drops on init, rows included: Knowledge before schema 4 was an
4847
+ * experimental store with no migration. Every schema-1/2-only table present is dropped. The table
4848
+ * names schema 4 reuses (mentions, activity, the state table) are dropped too, but only when an old
4849
+ * table is present and no schema-4 state row exists, so they are old-shaped. Schema-4-only tables
4850
+ * are never listed. On a schema-4 store this lists only tables an older process recreated during a
4851
+ * rolling deploy. Drop order is safe for adapters that enforce references.
4852
+ */
4853
+ function legacyKnowledgeTablesToDrop(snapshot) {
4854
+ const present = new Set(snapshot.tableNames);
4855
+ const legacy = [...LEGACY_KNOWLEDGE_TABLE_NAMES].filter((name) => present.has(name));
4856
+ if (legacy.length === 0) return [];
4857
+ const reused = snapshot.schemaVersion === 4 ? [] : REUSED_KNOWLEDGE_TABLE_NAMES.filter((name) => present.has(name));
4858
+ const drop = /* @__PURE__ */ new Set([...legacy, ...reused]);
4859
+ return [...RETIRED_KNOWLEDGE_TABLE_NAMES, ...[...KNOWLEDGE_TABLE_NAMES].reverse()].filter((name) => drop.has(name));
4860
+ }
4861
+ /** Message for the error an adapter throws on `incompatible-reset-required`. */
4862
+ function knowledgePagesResetMessage(reason) {
4863
+ return `Knowledge storage needs a reset before this version can use it: ${reason}. Knowledge data has no migration; run \`await storage.stores?.knowledge?.dangerouslyReset()\` to drop the Knowledge tables (Memory tables are untouched).`;
4864
+ }
4865
+ const KNOWLEDGE_PAGES_CORE_FUNCTIONS = [
4866
+ "assertKnowledgePageDescriptionWithinBound",
4867
+ "assertKnowledgeNoteTextWithinBound",
4868
+ "canonicalKnowledgeName",
4869
+ "knowledgePositionBetween",
4870
+ "KnowledgeMoveTooLargeError",
4871
+ "KnowledgePageDepthError",
4872
+ "KnowledgePageHasChildrenError",
4873
+ "KnowledgePageKeyConflictError"
4874
+ ];
4875
+ const KNOWLEDGE_PAGES_CORE_NUMBERS = [
4876
+ "MAX_KNOWLEDGE_MOVE_PAGES",
4877
+ "MAX_KNOWLEDGE_PAGE_DEPTH",
4878
+ "MAX_KNOWLEDGE_PAGE_LIST_LIMIT"
4879
+ ];
4880
+ function resolveKnowledgePagesCore(storageModule) {
4881
+ const module = typeof storageModule === "object" && storageModule !== null ? storageModule : {};
4882
+ const missing = [...KNOWLEDGE_PAGES_CORE_FUNCTIONS.filter((name) => typeof module[name] !== "function"), ...KNOWLEDGE_PAGES_CORE_NUMBERS.filter((name) => typeof module[name] !== "number")];
4883
+ if (missing.length > 0) throw new Error(`@mastra/core advertises Knowledge pages without the required storage API (missing ${missing.join(", ")})`);
4884
+ return module;
4885
+ }
4886
+ /** Loads core's page-store runtime once, after checking core advertises `knowledge-pages`. */
4887
+ function createKnowledgePagesCoreLoader(features, loadStorageModule) {
4888
+ let core;
4889
+ return async () => {
4890
+ if (!features.has("knowledge-pages")) throw new Error(`Knowledge requires a @mastra/core release with the "${KNOWLEDGE_PAGES_CORE_FEATURE}" feature. Upgrade @mastra/core to use Knowledge; other storage domains keep working on this version.`);
4891
+ core ??= loadStorageModule().then(resolveKnowledgePagesCore).catch((error) => {
4892
+ core = void 0;
4893
+ throw error;
4779
4894
  });
4780
- assertDescriptionWithinBound = resolvedAssert;
4781
- assertWithinBound = resolvedAssert;
4895
+ return core;
4896
+ };
4897
+ }
4898
+ /**
4899
+ * Keyword-search words: the query split on whitespace, lowercased, deduplicated. A hit needs at
4900
+ * least one of them (as a case-insensitive substring); an empty list means the search returns nothing.
4901
+ */
4902
+ function knowledgeSearchWords(query) {
4903
+ return [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))];
4904
+ }
4905
+ /**
4906
+ * Points one matched search word earns on a page, by the best field it appears in: name, then
4907
+ * description, then body. Pages rank by how many query words they match first; these points only
4908
+ * break ties between pages that match the same number of words.
4909
+ */
4910
+ const KNOWLEDGE_SEARCH_WEIGHTS = {
4911
+ name: 3,
4912
+ description: 2,
4913
+ body: 1
4914
+ };
4915
+ /**
4916
+ * Why `key` can't be a Knowledge page key, or undefined when it can. Keys are one path segment:
4917
+ * non-empty, with no `/` (path separator), `#` (scope/path separator) or `%` (escape character).
4918
+ */
4919
+ function knowledgePageKeyProblem(key) {
4920
+ if (!key) return "Knowledge page key must not be empty";
4921
+ if (/[/#%]/.test(key)) return `Knowledge page key "${key}" must not contain "/", "#" or "%"`;
4922
+ }
4923
+ // src/storage/domains/knowledge/pages.ts
4924
+ const loadPagesCore = createKnowledgePagesCoreLoader(_mastra_core_features.coreFeatures, () => import("@mastra/core/storage"));
4925
+ const DEFAULT_LIST_LIMIT = 50;
4926
+ const MONGO_DUPLICATE_KEY = 11e3;
4927
+ const MONGO_KNOWLEDGE_PAGES_COLLECTIONS = {
4928
+ pages: "mastra_knowledge_pages",
4929
+ notes: "mastra_knowledge_notes",
4930
+ pins: "mastra_knowledge_pins",
4931
+ activity: "mastra_knowledge_activity",
4932
+ state: "mastra_knowledge_access_state"
4933
+ };
4934
+ /** Thrown when existing Knowledge collections can't be used as schema 4 without a reset. */
4935
+ var MongoKnowledgeResetRequiredError = class extends Error {
4936
+ inspection;
4937
+ constructor(inspection) {
4938
+ super(knowledgePagesResetMessage(inspection.reason));
4939
+ this.name = "KnowledgeSchemaResetRequiredError";
4940
+ this.inspection = inspection;
4782
4941
  }
4783
- assertWithinBound(description);
4942
+ };
4943
+ function escapeRegex(value) {
4944
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4784
4945
  }
4785
- let assertRecordTextWithinBound;
4786
- async function assertKnowledgeRecordTextWithinBoundCompat(text) {
4787
- if (!assertRecordTextWithinBound) assertRecordTextWithinBound = (await import("@mastra/core/storage")).assertKnowledgeRecordTextWithinBound ?? ((value) => {
4788
- if (value.length > 1e3) throw new Error("Knowledge record text exceeds the 1000 UTF-16 code unit limit; split it into separate facts or summarize it");
4789
- });
4790
- assertRecordTextWithinBound(text);
4946
+ function isDuplicateKey(error) {
4947
+ return typeof error === "object" && error !== null && error.code === MONGO_DUPLICATE_KEY;
4791
4948
  }
4792
- const cloneScope = (scope) => [...scope];
4793
- const canonicalName = (name) => name.trim().toLocaleLowerCase();
4794
- const nodeReferenceId = (node) => typeof node === "string" ? node : node.id;
4795
- const sessionOptions = (session) => session ? { session } : {};
4796
- function visibleScopeKeys(scope) {
4797
- const canonical = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(scope);
4798
- const subsets = [[]];
4799
- for (const entry of canonical) subsets.push(...subsets.map((subset) => [...subset, entry]));
4800
- const keys = /* @__PURE__ */ new Set();
4801
- for (const subset of subsets.slice(1)) try {
4802
- keys.add((0, _mastra_core_storage.knowledgeScopeKey)(subset));
4949
+ function encodeCursor(parts) {
4950
+ return Buffer.from(JSON.stringify(parts)).toString("base64url");
4951
+ }
4952
+ function decodeCursor(cursor) {
4953
+ try {
4954
+ const parts = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
4955
+ if (Array.isArray(parts) && parts.length === 2 && parts.every((part) => typeof part === "string")) return parts;
4803
4956
  } catch {}
4804
- return [...keys];
4957
+ throw new Error("Invalid Knowledge cursor");
4958
+ }
4959
+ function clampLimit(limit, max) {
4960
+ const value = limit ?? DEFAULT_LIST_LIMIT;
4961
+ if (!Number.isInteger(value) || value < 1) throw new Error("Knowledge list limit must be a positive integer");
4962
+ return Math.min(value, max);
4963
+ }
4964
+ const live = { deletedAt: { $exists: false } };
4965
+ const notScope = { isScope: { $ne: true } };
4966
+ /** Unique-while-live page key per parent; unset on delete so the key can be reused. */
4967
+ function activeKeyOf(parentId, key) {
4968
+ return `${parentId}\u0000${key}`;
4805
4969
  }
4806
- function recordCursorFilter(cursor, expected) {
4807
- const parsed = (0, _mastra_core_storage.parseKnowledgeNodeCursor)(cursor, expected);
4808
- return { $or: [{ updatedAt: { $lt: parsed.updatedAt } }, {
4809
- updatedAt: parsed.updatedAt,
4810
- $or: [{ name: { $gt: parsed.name } }, {
4811
- name: parsed.name,
4812
- id: { $gt: parsed.id }
4813
- }]
4814
- }] };
4970
+ /** Pipeline stage recomputing `activeKey` for pages that have a live key after their parent changed. */
4971
+ function recomputeActiveKey(parentId) {
4972
+ return { $set: { activeKey: { $cond: [
4973
+ { $and: [{ $eq: [{ $type: "$key" }, "string"] }, { $eq: [{ $type: "$deletedAt" }, "missing"] }] },
4974
+ { $concat: [
4975
+ parentId,
4976
+ "\0",
4977
+ "$key"
4978
+ ] },
4979
+ "$$REMOVE"
4980
+ ] } } };
4815
4981
  }
4816
- function nodeFromDocument(row) {
4982
+ function toPage(row) {
4817
4983
  return {
4818
4984
  id: String(row.id),
4819
- type: "node",
4985
+ scopeId: String(row.scopeId),
4986
+ parentId: row.parentId == null ? null : String(row.parentId),
4987
+ isScope: row.isScope === true,
4988
+ ...row.address == null ? {} : { address: String(row.address) },
4989
+ ...row.declaration == null ? {} : { declaration: String(row.declaration) },
4990
+ ...row.key == null ? {} : { key: String(row.key) },
4991
+ position: String(row.position),
4820
4992
  name: String(row.name),
4821
- kind: String(row.kind),
4822
- content: row.content == null ? void 0 : String(row.content),
4823
- description: row.description == null ? void 0 : String(row.description),
4824
- scope: cloneScope(row.scope),
4993
+ ...row.description == null ? {} : { description: String(row.description) },
4994
+ ...row.body == null ? {} : { body: String(row.body) },
4825
4995
  version: Number(row.version),
4826
- mergedInto: row.mergedInto ?? void 0,
4996
+ ...row.mergedInto == null ? {} : { mergedInto: String(row.mergedInto) },
4997
+ createdBy: row.createdBy,
4998
+ updatedBy: row.updatedBy,
4827
4999
  createdAt: new Date(row.createdAt),
4828
- updatedAt: new Date(row.updatedAt)
5000
+ updatedAt: new Date(row.updatedAt),
5001
+ ...row.deletedAt == null ? {} : { deletedAt: new Date(row.deletedAt) },
5002
+ ...row.deletedBy == null ? {} : { deletedBy: String(row.deletedBy) }
4829
5003
  };
4830
5004
  }
4831
- function recordFromDocument(row) {
5005
+ function toNote(row) {
4832
5006
  return {
4833
5007
  id: String(row.id),
4834
- node: String(row.node),
5008
+ pageId: String(row.pageId),
4835
5009
  text: String(row.text),
4836
- scope: cloneScope(row.scope),
4837
- sourceThreadId: String(row.sourceThreadId),
4838
- capturedAt: new Date(row.capturedAt),
4839
- when: row.when ? new Date(row.when) : void 0,
4840
- metadata: row.metadata ?? void 0,
4841
- deletedAt: row.deletedAt ? new Date(row.deletedAt) : void 0,
4842
- deletedBy: row.deletedBy ?? void 0
5010
+ ...row.when == null ? {} : { when: new Date(row.when) },
5011
+ stampScopeIds: [...row.stampScopeIds ?? []].sort(),
5012
+ mentions: [...row.mentions ?? []].sort(),
5013
+ provenance: row.provenance,
5014
+ version: Number(row.version),
5015
+ createdAt: new Date(row.createdAt),
5016
+ updatedAt: new Date(row.updatedAt),
5017
+ ...row.deletedAt == null ? {} : { deletedAt: new Date(row.deletedAt) },
5018
+ ...row.deletedBy == null ? {} : { deletedBy: String(row.deletedBy) }
5019
+ };
5020
+ }
5021
+ function toListedPin(row) {
5022
+ return {
5023
+ ...toPin(row),
5024
+ pageName: String(row.pageName)
4843
5025
  };
4844
5026
  }
4845
- function outboxFromDocument(row) {
5027
+ function toPin(row) {
4846
5028
  return {
4847
5029
  id: String(row.id),
4848
- idempotencyKey: String(row.idempotencyKey),
4849
- documentId: String(row.documentId),
4850
- documentType: row.documentType,
4851
- operation: row.operation,
4852
- scope: cloneScope(row.scope),
4853
- status: row.status,
4854
- attempts: Number(row.attempts),
4855
- availableAt: new Date(row.availableAt),
4856
- claimedAt: row.claimedAt ? new Date(row.claimedAt) : void 0,
4857
- claimedBy: row.claimedBy ?? void 0,
5030
+ pageId: String(row.pageId),
5031
+ audience: [...row.audience ?? []],
5032
+ createdBy: String(row.createdBy),
4858
5033
  createdAt: new Date(row.createdAt),
4859
- completedAt: row.completedAt ? new Date(row.completedAt) : void 0
5034
+ updatedAt: new Date(row.updatedAt)
4860
5035
  };
4861
5036
  }
4862
- const KNOWLEDGE_CURATION_CURSOR_REMOVED_MESSAGE = "Knowledge curation cursors were removed: observation-time curate is the only Knowledge writer and needs no cursor.";
4863
- var KnowledgeMongoDB = class KnowledgeMongoDB extends _mastra_core_storage.KnowledgeStorage {
4864
- static MANAGED_COLLECTIONS = [
4865
- _mastra_core_storage.TABLE_KNOWLEDGE_NODES,
4866
- _mastra_core_storage.TABLE_KNOWLEDGE_RECORDS,
4867
- _mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS,
4868
- _mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY,
4869
- _mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX
4870
- ];
5037
+ const noProjection = { projection: { _id: 0 } };
5038
+ /**
5039
+ * MongoDB implementation of the schema-4 {@link KnowledgePageStore}.
5040
+ *
5041
+ * Notes embed their stamps and mentions and carry two denormalized copies of page scope
5042
+ * (`pageScopeId`, `mentionScopeIds`); activity events carry `pageScopeId`. Moves and merges rewrite
5043
+ * those copies in the same transaction as the page rows, so a read is one indexed filter against the
5044
+ * set of readable scope ids resolved from the read scope (never a per-address query).
5045
+ */
5046
+ var MongoKnowledgePages = class {
4871
5047
  #connector;
4872
- constructor(config) {
4873
- super();
4874
- this.#connector = resolveMongoDBConfig(config);
5048
+ #bounds;
5049
+ constructor(options) {
5050
+ this.#connector = options.connector;
5051
+ this.#bounds = options.bounds;
5052
+ }
5053
+ #c(name) {
5054
+ return this.#connector.getCollection(MONGO_KNOWLEDGE_PAGES_COLLECTIONS[name]);
5055
+ }
5056
+ #tx(operation) {
5057
+ return this.#connector.withTransaction(operation);
5058
+ }
5059
+ async inspectSchema() {
5060
+ return inspectKnowledgePagesSchema(await this.#snapshot());
5061
+ }
5062
+ async #snapshot() {
5063
+ const tableNames = [];
5064
+ for (const name of KNOWLEDGE_RESETTABLE_TABLE_NAMES) if (await this.#connector.collectionExists(name)) tableNames.push(name);
5065
+ let schemaVersion;
5066
+ if (tableNames.includes(MONGO_KNOWLEDGE_PAGES_COLLECTIONS.state)) {
5067
+ const state = await (await this.#c("state")).findOne({ id: "knowledge" });
5068
+ schemaVersion = typeof state?.schemaVersion === "number" ? state.schemaVersion : void 0;
5069
+ }
5070
+ return {
5071
+ tableNames,
5072
+ schemaVersion
5073
+ };
5074
+ }
5075
+ async #drop(name) {
5076
+ const collection = await this.#connector.getCollection(name);
5077
+ try {
5078
+ await collection.drop();
5079
+ } catch (error) {
5080
+ if (error.codeName !== "NamespaceNotFound") throw error;
5081
+ }
4875
5082
  }
4876
5083
  async init() {
4877
- const nodes = await this.#collection(_mastra_core_storage.TABLE_KNOWLEDGE_NODES);
4878
- const knowledge = await this.#collection(_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS);
4879
- const mentions = await this.#collection(_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS);
4880
- const activity = await this.#collection(_mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY);
4881
- const outbox = await this.#collection(_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX);
5084
+ const stateName = MONGO_KNOWLEDGE_PAGES_COLLECTIONS.state;
5085
+ for (const name of legacyKnowledgeTablesToDrop(await this.#snapshot())) if (name === stateName) await (await this.#c("state")).deleteMany({ schemaVersion: { $ne: 4 } });
5086
+ else await this.#drop(name);
5087
+ await (await this.#c("state")).updateOne({ id: "knowledge" }, { $setOnInsert: {
5088
+ id: "knowledge",
5089
+ schemaVersion: 4
5090
+ } }, { upsert: true });
5091
+ const inspection = await this.inspectSchema();
5092
+ if (inspection.status === "incompatible-reset-required") throw new MongoKnowledgeResetRequiredError(inspection);
5093
+ const [pages, notes, pins, activity] = await Promise.all([
5094
+ this.#c("pages"),
5095
+ this.#c("notes"),
5096
+ this.#c("pins"),
5097
+ this.#c("activity")
5098
+ ]);
4882
5099
  await Promise.all([
4883
- nodes.createIndex({
4884
- type: 1,
4885
- scopeKey: 1,
4886
- canonicalName: 1
4887
- }, { unique: true }),
4888
- nodes.createIndex({
4889
- scopeKey: 1,
4890
- type: 1
5100
+ pages.createIndex({ id: 1 }, { unique: true }),
5101
+ pages.createIndex({ address: 1 }, {
5102
+ unique: true,
5103
+ partialFilterExpression: { isScope: true }
4891
5104
  }),
4892
- nodes.createIndex({
4893
- type: 1,
4894
- canonicalName: 1
5105
+ pages.createIndex({ activeKey: 1 }, {
5106
+ unique: true,
5107
+ partialFilterExpression: { activeKey: { $type: "string" } }
4895
5108
  }),
4896
- knowledge.createIndex({
4897
- node: 1,
4898
- id: -1
5109
+ pages.createIndex({
5110
+ parentId: 1,
5111
+ position: 1,
5112
+ id: 1
4899
5113
  }),
4900
- knowledge.createIndex({
4901
- sourceThreadId: 1,
4902
- id: -1
5114
+ pages.createIndex({
5115
+ scopeId: 1,
5116
+ name: 1,
5117
+ id: 1
4903
5118
  }),
4904
- knowledge.createIndex({
4905
- scopeKey: 1,
4906
- id: -1
5119
+ pages.createIndex({
5120
+ canonicalName: 1,
5121
+ scopeId: 1
5122
+ }),
5123
+ pages.createIndex({
5124
+ isScope: 1,
5125
+ declaration: 1,
5126
+ parentId: 1
4907
5127
  }),
4908
- mentions.createIndex({
4909
- sourceType: 1,
4910
- sourceId: 1,
4911
- recordId: 1
4912
- }, { unique: true }),
4913
- mentions.createIndex({
4914
- recordId: 1,
4915
- sourceType: 1,
4916
- sourceId: 1
5128
+ notes.createIndex({ id: 1 }, { unique: true }),
5129
+ notes.createIndex({
5130
+ pageId: 1,
5131
+ createdAt: 1,
5132
+ id: 1
4917
5133
  }),
4918
- activity.createIndex({ id: -1 }),
5134
+ notes.createIndex({ mentions: 1 }),
5135
+ notes.createIndex({ pageScopeId: 1 }),
5136
+ notes.createIndex({ stampScopeIds: 1 }),
5137
+ pins.createIndex({ id: 1 }, { unique: true }),
5138
+ pins.createIndex({ pageId: 1 }, { unique: true }),
5139
+ pins.createIndex({ audience: 1 }),
5140
+ activity.createIndex({ id: 1 }, { unique: true }),
4919
5141
  activity.createIndex({
4920
- scopeKey: 1,
5142
+ pageScopeId: 1,
5143
+ createdAt: -1,
4921
5144
  id: -1
4922
5145
  }),
4923
- outbox.createIndex({ idempotencyKey: 1 }, { unique: true }),
4924
- outbox.createIndex({
4925
- status: 1,
4926
- availableAt: 1,
4927
- createdAt: 1
5146
+ activity.createIndex({
5147
+ pageId: 1,
5148
+ createdAt: -1,
5149
+ id: -1
4928
5150
  })
4929
5151
  ]);
4930
5152
  }
4931
- async dangerouslyClearAll() {
4932
- await this.#connector.withTransaction(async (session) => {
4933
- for (const name of KnowledgeMongoDB.MANAGED_COLLECTIONS) await (await this.#collection(name)).deleteMany({}, sessionOptions(session));
5153
+ /** Drops exactly the Knowledge collections (never Memory's) and recreates schema 4. */
5154
+ async reset() {
5155
+ for (const name of KNOWLEDGE_RESETTABLE_TABLE_NAMES) await this.#drop(name);
5156
+ await this.init();
5157
+ }
5158
+ /** The ids of every scope page the read scope can see; `null` means everything. */
5159
+ async #readable(read, session) {
5160
+ if (read === "all") return null;
5161
+ const any = this.#readableClauses(read);
5162
+ if (!any.length) return [];
5163
+ return (await (await this.#c("pages")).find({
5164
+ isScope: true,
5165
+ $or: any
5166
+ }, {
5167
+ projection: {
5168
+ _id: 0,
5169
+ id: 1
5170
+ },
5171
+ session
5172
+ }).toArray()).map((row) => String(row.id));
5173
+ }
5174
+ #readableClauses(read) {
5175
+ const any = [];
5176
+ if (read.addresses.length) any.push({ address: { $in: read.addresses } });
5177
+ for (const entry of read.prefixes) any.push({
5178
+ declaration: entry.declaration,
5179
+ address: { $regex: `^${escapeRegex(entry.prefix)}` }
5180
+ });
5181
+ for (const entry of read.children) any.push({
5182
+ declaration: entry.declaration,
5183
+ parentId: entry.parentId
4934
5184
  });
5185
+ return any;
4935
5186
  }
4936
- async createNode(input) {
4937
- await assertKnowledgeDescriptionWithinBoundCompat(input.description);
4938
- if (input.scopeAddresses?.length) {
4939
- const error = /* @__PURE__ */ new Error("This Knowledge storage adapter does not expose structural scope placement.");
4940
- error.name = "KnowledgeUnsupportedCapabilityError";
4941
- throw error;
5187
+ /**
5188
+ * Whether one scope page is readable, answered by a single indexed lookup instead of resolving the
5189
+ * whole frontier. Use it when a call targets one scope; the frontier can be thousands of scopes.
5190
+ */
5191
+ async #scopeReadable(read, scopeId) {
5192
+ if (read === "all") return true;
5193
+ const any = this.#readableClauses(read);
5194
+ if (!any.length) return false;
5195
+ return await (await this.#c("pages")).countDocuments({
5196
+ id: scopeId,
5197
+ isScope: true,
5198
+ $or: any
5199
+ }, { limit: 1 }) > 0;
5200
+ }
5201
+ #inScopes(field, ids) {
5202
+ return ids === null ? {} : { [field]: { $in: ids } };
5203
+ }
5204
+ #visibleNotes(ids) {
5205
+ if (ids === null) return {};
5206
+ return {
5207
+ pageScopeId: { $in: ids },
5208
+ stampScopeIds: { $in: ids },
5209
+ mentionScopeIds: { $not: { $elemMatch: { $nin: ids } } }
5210
+ };
5211
+ }
5212
+ async #page(id, session) {
5213
+ const row = await (await this.#c("pages")).findOne({ id }, {
5214
+ ...noProjection,
5215
+ session
5216
+ });
5217
+ return row ? toPage(row) : null;
5218
+ }
5219
+ async #requireLivePage(id, session) {
5220
+ const page = await this.#page(id, session);
5221
+ if (!page || page.deletedAt) throw new _mastra_core_storage.KnowledgeNotFoundError("page", id);
5222
+ return page;
5223
+ }
5224
+ async #log(session, event) {
5225
+ await (await this.#c("activity")).insertOne({
5226
+ id: (0, _mastra_core_storage.createKnowledgeUlid)(),
5227
+ action: event.action,
5228
+ scopeId: event.scopeId,
5229
+ pageScopeId: event.pageScopeId ?? event.scopeId,
5230
+ pageId: event.pageId,
5231
+ ...event.noteId ? { noteId: event.noteId } : {},
5232
+ provenance: event.provenance,
5233
+ createdAt: event.at
5234
+ }, { session });
5235
+ }
5236
+ async #lastPosition(parentId, session) {
5237
+ const row = await (await this.#c("pages")).find({
5238
+ parentId,
5239
+ ...live
5240
+ }, {
5241
+ projection: {
5242
+ _id: 0,
5243
+ position: 1
5244
+ },
5245
+ session
5246
+ }).sort({ position: -1 }).limit(1).next();
5247
+ return row ? String(row.position) : void 0;
5248
+ }
5249
+ /**
5250
+ * Ordinary descendants of `rootId`, level by level. Stops counting once the live total passes the
5251
+ * move cap, so an oversize subtree is reported without being walked to the end.
5252
+ */
5253
+ async #subtree(rootId, session, find) {
5254
+ const core = await loadPagesCore();
5255
+ const pages = await this.#c("pages");
5256
+ const ids = [];
5257
+ let liveCount = 0;
5258
+ let maxDepth = 0;
5259
+ let frontier = [rootId];
5260
+ while (frontier.length) {
5261
+ const rows = await pages.find({
5262
+ parentId: { $in: frontier },
5263
+ ...notScope
5264
+ }, {
5265
+ projection: {
5266
+ _id: 0,
5267
+ id: 1,
5268
+ depth: 1,
5269
+ deletedAt: 1
5270
+ },
5271
+ session
5272
+ }).toArray();
5273
+ frontier = [];
5274
+ for (const row of rows) {
5275
+ const id = String(row.id);
5276
+ if (find !== void 0 && id === find) return {
5277
+ ids,
5278
+ live: liveCount,
5279
+ maxDepth,
5280
+ found: true,
5281
+ truncated: false
5282
+ };
5283
+ ids.push(id);
5284
+ frontier.push(id);
5285
+ if (row.deletedAt == null) {
5286
+ liveCount++;
5287
+ maxDepth = Math.max(maxDepth, Number(row.depth));
5288
+ }
5289
+ }
5290
+ if (liveCount > core.MAX_KNOWLEDGE_MOVE_PAGES) return {
5291
+ ids,
5292
+ live: liveCount,
5293
+ maxDepth,
5294
+ found: false,
5295
+ truncated: true
5296
+ };
4942
5297
  }
4943
- const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
4944
- return this.#connector.withTransaction(async (session) => {
4945
- const existing = await this.#getNodeByName(input.name, scope, session);
4946
- if (existing) {
4947
- const terminal = await this.#resolveTerminalNode(existing.id, session);
4948
- if (!(0, _mastra_core_storage.isKnowledgeScopeVisible)(terminal.scope, scope)) throw new Error(`Merged knowledge node is not visible from scope: ${input.name}`);
4949
- return terminal;
5298
+ return {
5299
+ ids,
5300
+ live: liveCount,
5301
+ maxDepth,
5302
+ found: false,
5303
+ truncated: false
5304
+ };
5305
+ }
5306
+ /** Refuses before any write when a live arriving page's key is already live under `parentId`. */
5307
+ async #assertNoKeyConflicts(keys, parentId, session, exceptId) {
5308
+ const core = await loadPagesCore();
5309
+ if (!keys.length) return;
5310
+ const clash = await (await this.#c("pages")).findOne({
5311
+ ...live,
5312
+ parentId,
5313
+ key: { $in: keys },
5314
+ ...exceptId ? { id: { $ne: exceptId } } : {}
5315
+ }, {
5316
+ projection: {
5317
+ _id: 0,
5318
+ key: 1
5319
+ },
5320
+ session
5321
+ });
5322
+ if (clash) throw new core.KnowledgePageKeyConflictError(String(clash.key), parentId);
5323
+ }
5324
+ /** Recomputes the denormalized scope of every page a note mentions, for notes touching `pageIds`. */
5325
+ async #refreshMentionScopes(pageIds, session) {
5326
+ if (!pageIds.length) return;
5327
+ const notes = await this.#c("notes");
5328
+ const pages = await this.#c("pages");
5329
+ const affected = await notes.find({ mentions: { $in: pageIds } }, {
5330
+ projection: {
5331
+ _id: 0,
5332
+ id: 1,
5333
+ mentions: 1
5334
+ },
5335
+ session
5336
+ }).toArray();
5337
+ for (const note of affected) {
5338
+ const mentioned = await pages.find({ id: { $in: note.mentions } }, {
5339
+ projection: {
5340
+ _id: 0,
5341
+ scopeId: 1
5342
+ },
5343
+ session
5344
+ }).toArray();
5345
+ await notes.updateOne({ id: note.id }, { $set: { mentionScopeIds: [...new Set(mentioned.map((page) => String(page.scopeId)))] } }, { session });
5346
+ }
5347
+ }
5348
+ async materializeScope(input) {
5349
+ for (let attempt = 0;; attempt++) try {
5350
+ return await this.#materializeScopeOnce(input);
5351
+ } catch (error) {
5352
+ if (!(error instanceof (await loadPagesCore()).KnowledgePageKeyConflictError || error instanceof _mastra_core_storage.KnowledgeConflictError || isDuplicateKey(error) || error?.hasErrorLabel?.("TransientTransactionError")) || attempt >= 4) throw error;
5353
+ }
5354
+ }
5355
+ async #materializeScopeOnce(input) {
5356
+ const bounds = await this.#bounds();
5357
+ bounds.assertKnowledgePageDescriptionWithinBound(input.description);
5358
+ for (const child of input.children ?? []) bounds.assertKnowledgePageDescriptionWithinBound(child.description);
5359
+ const checkTemplates = (templates) => {
5360
+ for (const template of templates) {
5361
+ bounds.assertKnowledgePageDescriptionWithinBound(template.description);
5362
+ checkTemplates(template.pages ?? []);
4950
5363
  }
5364
+ };
5365
+ checkTemplates(input.pages ?? []);
5366
+ return this.#tx(async (session) => {
4951
5367
  const now = /* @__PURE__ */ new Date();
4952
- const node = {
4953
- id: input.id ?? crypto.randomUUID(),
4954
- type: "node",
4955
- name: input.name.trim(),
4956
- kind: input.kind,
4957
- content: input.content,
4958
- description: input.description,
5368
+ let scope = await this.#scopeByAddress(input.address, session);
5369
+ let created = false;
5370
+ let parentConflict;
5371
+ if (!scope) {
5372
+ if (input.parentId) await this.#requireLivePage(input.parentId, session);
5373
+ scope = await this.#insertScope(session, {
5374
+ address: input.address,
5375
+ declaration: input.declaration,
5376
+ name: input.name,
5377
+ description: input.description,
5378
+ parentId: input.parentId ?? null,
5379
+ provenance: input.provenance,
5380
+ at: now
5381
+ });
5382
+ created = true;
5383
+ } else if (input.parentId && scope.parentId === null) {
5384
+ await this.#requireLivePage(input.parentId, session);
5385
+ const linked = await (await this.#c("pages")).findOneAndUpdate({
5386
+ id: scope.id,
5387
+ parentId: null
5388
+ }, { $set: { parentId: input.parentId } }, {
5389
+ returnDocument: "after",
5390
+ projection: { _id: 0 },
5391
+ session
5392
+ });
5393
+ scope = toPage(linked ?? await this.#scopeByAddress(input.address, session));
5394
+ if (!linked && input.parentId !== scope.parentId) parentConflict = {
5395
+ existingParentId: scope.parentId,
5396
+ requestedParentId: input.parentId
5397
+ };
5398
+ } else if (input.parentId !== void 0 && (input.parentId ?? null) !== scope.parentId) parentConflict = {
5399
+ existingParentId: scope.parentId,
5400
+ requestedParentId: input.parentId ?? null
5401
+ };
5402
+ for (const child of input.children ?? []) {
5403
+ if (await this.#scopeByAddress(child.address, session)) continue;
5404
+ await this.#insertScope(session, {
5405
+ address: child.address,
5406
+ declaration: child.declaration,
5407
+ name: child.name,
5408
+ description: child.description,
5409
+ parentId: scope.id,
5410
+ provenance: input.provenance,
5411
+ at: now
5412
+ });
5413
+ }
5414
+ await this.#materializeTemplates(session, scope, input.pages ?? [], input.provenance, now);
5415
+ return {
4959
5416
  scope,
4960
- version: 1,
4961
- createdAt: now,
4962
- updatedAt: now
5417
+ created,
5418
+ ...parentConflict ? { parentConflict } : {}
4963
5419
  };
4964
- try {
4965
- await (await this.#nodes()).insertOne({
4966
- ...node,
4967
- canonicalName: canonicalName(node.name),
4968
- scopeKey: (0, _mastra_core_storage.knowledgeScopeKey)(scope),
4969
- mergedInto: null
4970
- }, sessionOptions(session));
4971
- } catch (error) {
4972
- if (error.code !== 11e3) throw error;
4973
- const concurrent = await this.#getNodeByName(input.name, scope, session);
4974
- if (!concurrent) throw error;
4975
- return await this.#resolveTerminalNode(concurrent.id, session);
4976
- }
4977
- await this.#replaceMentions("node", node.id, node.content ?? "", input.resolutionScope ?? scope, scope, session);
4978
- await this.#activity("node-created", "node", node.id, scope, void 0, session);
4979
- await this.#outbox("node", node.id, "upsert", 1, scope, session);
4980
- return node;
4981
5420
  });
4982
5421
  }
4983
- async getNode(id) {
4984
- return this.#getNode(id);
5422
+ async #materializeTemplates(session, parent, templates, provenance, at) {
5423
+ const pages = await this.#c("pages");
5424
+ for (const template of templates) {
5425
+ const problem = knowledgePageKeyProblem(template.key);
5426
+ if (problem) throw new Error(problem);
5427
+ const existing = await pages.findOne({
5428
+ parentId: parent.id,
5429
+ key: template.key,
5430
+ ...live
5431
+ }, {
5432
+ ...noProjection,
5433
+ session
5434
+ });
5435
+ const page = existing ? toPage(existing) : await this.#insertPage(session, {
5436
+ parent,
5437
+ key: template.key,
5438
+ name: template.name,
5439
+ description: template.description,
5440
+ provenance,
5441
+ at
5442
+ });
5443
+ if (template.pages?.length) await this.#materializeTemplates(session, page, template.pages, provenance, at);
5444
+ }
5445
+ }
5446
+ async #scopeByAddress(address, session) {
5447
+ const row = await (await this.#c("pages")).findOne({
5448
+ isScope: true,
5449
+ address
5450
+ }, {
5451
+ ...noProjection,
5452
+ session
5453
+ });
5454
+ return row ? toPage(row) : null;
5455
+ }
5456
+ async #insertScope(session, input) {
5457
+ const core = await loadPagesCore();
5458
+ const id = (0, _mastra_core_storage.createKnowledgeUlid)();
5459
+ const doc = {
5460
+ id,
5461
+ scopeId: id,
5462
+ parentId: input.parentId,
5463
+ isScope: true,
5464
+ address: input.address,
5465
+ declaration: input.declaration,
5466
+ position: core.knowledgePositionBetween(await this.#lastPosition(input.parentId, session)),
5467
+ name: input.name,
5468
+ canonicalName: core.canonicalKnowledgeName(input.name),
5469
+ ...input.description === void 0 ? {} : { description: input.description },
5470
+ depth: 0,
5471
+ version: 1,
5472
+ createdBy: input.provenance,
5473
+ updatedBy: input.provenance,
5474
+ createdAt: input.at,
5475
+ updatedAt: input.at
5476
+ };
5477
+ try {
5478
+ await (await this.#c("pages")).insertOne({ ...doc }, { session });
5479
+ } catch (error) {
5480
+ if (isDuplicateKey(error)) throw new _mastra_core_storage.KnowledgeConflictError(input.address);
5481
+ throw error;
5482
+ }
5483
+ await this.#log(session, {
5484
+ action: "scope-created",
5485
+ scopeId: id,
5486
+ pageId: id,
5487
+ provenance: input.provenance,
5488
+ at: input.at
5489
+ });
5490
+ return toPage(doc);
5491
+ }
5492
+ async getScopesByAddress(addresses) {
5493
+ if (addresses.length === 0) return [];
5494
+ const rows = await (await this.#c("pages")).find({
5495
+ isScope: true,
5496
+ address: { $in: addresses }
5497
+ }, noProjection).toArray();
5498
+ const byAddress = new Map(rows.map((row) => [String(row.address), toPage(row)]));
5499
+ return [...new Set(addresses)].flatMap((address) => byAddress.get(address) ?? []);
5500
+ }
5501
+ async listScopeDeclarations() {
5502
+ return (await (await this.#c("pages")).aggregate([{ $match: {
5503
+ isScope: true,
5504
+ declaration: { $type: "string" }
5505
+ } }, { $group: {
5506
+ _id: "$declaration",
5507
+ scopes: { $sum: 1 }
5508
+ } }]).toArray()).map((row) => ({
5509
+ declaration: String(row._id),
5510
+ scopes: Number(row.scopes)
5511
+ })).sort((a, b) => a.declaration < b.declaration ? -1 : a.declaration > b.declaration ? 1 : 0);
5512
+ }
5513
+ async renameScopeDeclaration(input) {
5514
+ return this.#tx(async (session) => {
5515
+ const pages = await this.#c("pages");
5516
+ const rows = await pages.find({
5517
+ isScope: true,
5518
+ $or: [{ declaration: input.from }, { declaration: { $regex: `^${escapeRegex(`${input.from}/`)}` } }]
5519
+ }, {
5520
+ projection: {
5521
+ _id: 0,
5522
+ id: 1,
5523
+ address: 1,
5524
+ declaration: 1
5525
+ },
5526
+ session
5527
+ }).toArray();
5528
+ if (rows.length === 0) return 0;
5529
+ const renames = rows.map((row) => ({
5530
+ address: String(row.address),
5531
+ from: String(row.declaration),
5532
+ to: input.to + String(row.declaration).slice(input.from.length)
5533
+ }));
5534
+ input.check(renames);
5535
+ if ((await pages.bulkWrite(rows.map((row, index) => ({ updateOne: {
5536
+ filter: {
5537
+ id: row.id,
5538
+ isScope: true
5539
+ },
5540
+ update: { $set: { declaration: renames[index].to } }
5541
+ } })), { session })).matchedCount < rows.length) throw new _mastra_core_storage.KnowledgeConflictError("Knowledge scope declarations changed while renaming; retry the rename");
5542
+ return rows.length;
5543
+ });
5544
+ }
5545
+ async listChildScopes(input) {
5546
+ const core = await loadPagesCore();
5547
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
5548
+ const filter = {
5549
+ isScope: true,
5550
+ parentId: input.parentId,
5551
+ ...live
5552
+ };
5553
+ if (input.cursor) {
5554
+ const [position, id] = decodeCursor(input.cursor);
5555
+ filter.$or = [{ position: { $gt: position } }, {
5556
+ position,
5557
+ id: { $gt: id }
5558
+ }];
5559
+ }
5560
+ const rows = await (await this.#c("pages")).find(filter, noProjection).sort({
5561
+ position: 1,
5562
+ id: 1
5563
+ }).limit(limit + 1).toArray();
5564
+ return this.#pageOutput(rows, limit, (page) => [page.position, page.id]);
5565
+ }
5566
+ #pageOutput(rows, limit, cursorOf) {
5567
+ const pages = rows.slice(0, limit).map(toPage);
5568
+ const last = pages[pages.length - 1];
5569
+ return {
5570
+ pages,
5571
+ ...rows.length > limit && last ? { nextCursor: encodeCursor(cursorOf(last)) } : {}
5572
+ };
5573
+ }
5574
+ async getPage(input) {
5575
+ const row = await (await this.#c("pages")).findOne({ id: input.id }, noProjection);
5576
+ return row && await this.#scopeReadable(input.read, String(row.scopeId)) ? toPage(row) : null;
5577
+ }
5578
+ async getPageByPath(input) {
5579
+ if (!input.path.length) return null;
5580
+ if (!await this.#scopeReadable(input.read, input.scopeId)) return null;
5581
+ const pages = await this.#c("pages");
5582
+ let page;
5583
+ let parentId = input.scopeId;
5584
+ for (const key of input.path) {
5585
+ const row = await pages.findOne({
5586
+ parentId,
5587
+ key,
5588
+ scopeId: input.scopeId,
5589
+ ...live,
5590
+ ...notScope
5591
+ }, noProjection);
5592
+ if (!row) return null;
5593
+ page = toPage(row);
5594
+ parentId = page.id;
5595
+ }
5596
+ return page ?? null;
5597
+ }
5598
+ async findPagesByName(input) {
5599
+ const core = await loadPagesCore();
5600
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
5601
+ const filter = {
5602
+ canonicalName: core.canonicalKnowledgeName(input.name),
5603
+ ...live
5604
+ };
5605
+ if (!await this.#scopeFilter(filter, input.read, input.scopeId)) return [];
5606
+ return (await (await this.#c("pages")).find(filter, noProjection).sort({
5607
+ createdAt: -1,
5608
+ id: -1
5609
+ }).limit(limit).toArray()).map(toPage);
4985
5610
  }
4986
- async getNodeByName(input) {
4987
- return this.#getNodeByName(input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
5611
+ /**
5612
+ * Adds the home-scope constraint: the explicit scope when given (one indexed readability check),
5613
+ * otherwise the readable frontier. Returns false when nothing can match.
5614
+ */
5615
+ async #scopeFilter(filter, read, scopeId) {
5616
+ if (scopeId !== void 0) {
5617
+ if (!await this.#scopeReadable(read, scopeId)) return false;
5618
+ filter.scopeId = scopeId;
5619
+ return true;
5620
+ }
5621
+ const ids = await this.#readable(read);
5622
+ if (ids !== null) filter.scopeId = { $in: ids };
5623
+ return true;
4988
5624
  }
4989
- async resolveNode(input) {
4990
- return this.#resolveNode(input.name, (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope));
5625
+ async listChildPages(input) {
5626
+ const core = await loadPagesCore();
5627
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
5628
+ const ids = await this.#readable(input.read);
5629
+ const filter = {
5630
+ parentId: input.parentId,
5631
+ ...notScope,
5632
+ ...live,
5633
+ ...this.#inScopes("scopeId", ids)
5634
+ };
5635
+ if (input.cursor) {
5636
+ const [position, id] = decodeCursor(input.cursor);
5637
+ filter.$or = [{ position: { $gt: position } }, {
5638
+ position,
5639
+ id: { $gt: id }
5640
+ }];
5641
+ }
5642
+ const rows = await (await this.#c("pages")).find(filter, noProjection).sort({
5643
+ position: 1,
5644
+ id: 1
5645
+ }).limit(limit + 1).toArray();
5646
+ return this.#pageOutput(rows, limit, (page) => [page.position, page.id]);
4991
5647
  }
4992
- async listNodes(input) {
5648
+ async listPages(input) {
5649
+ const core = await loadPagesCore();
5650
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
4993
5651
  const filter = {
4994
- type: "node",
4995
- mergedInto: null,
4996
- scopeKey: { $in: visibleScopeKeys((0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope)) },
4997
- ...input.namePrefix ? { canonicalName: { $regex: `^${this.#escapeRegex(canonicalName(input.namePrefix))}` } } : {},
4998
- ...input.kind ? { kind: input.kind } : {},
4999
- ...input.hasContent === void 0 ? {} : input.hasContent ? { content: {
5000
- $exists: true,
5001
- $nin: [null, ""]
5002
- } } : { $or: [
5003
- { content: { $exists: false } },
5004
- { content: null },
5005
- { content: "" }
5006
- ] },
5007
- ...input.cursor ? recordCursorFilter(input.cursor, {
5008
- namePrefix: input.namePrefix,
5009
- kind: input.kind,
5010
- hasContent: input.hasContent
5011
- }) : {}
5652
+ ...notScope,
5653
+ ...live
5012
5654
  };
5013
- return (await (await this.#nodes()).find(filter).sort({
5014
- updatedAt: -1,
5655
+ if (!await this.#scopeFilter(filter, input.read, input.scopeId)) return { pages: [] };
5656
+ if (input.namePrefix) filter.canonicalName = { $regex: `^${escapeRegex(core.canonicalKnowledgeName(input.namePrefix))}` };
5657
+ if (input.cursor) {
5658
+ const [name, id] = decodeCursor(input.cursor);
5659
+ filter.$or = [{ name: { $gt: name } }, {
5660
+ name,
5661
+ id: { $gt: id }
5662
+ }];
5663
+ }
5664
+ const rows = await (await this.#c("pages")).find(filter, noProjection).sort({
5015
5665
  name: 1,
5016
5666
  id: 1
5017
- }).limit(input.limit ?? 100).toArray()).map(nodeFromDocument);
5667
+ }).limit(limit + 1).toArray();
5668
+ return this.#pageOutput(rows, limit, (page) => [page.name, page.id]);
5669
+ }
5670
+ async createPage(input) {
5671
+ (await this.#bounds()).assertKnowledgePageDescriptionWithinBound(input.description);
5672
+ if (input.key !== void 0) {
5673
+ const problem = knowledgePageKeyProblem(input.key);
5674
+ if (problem) throw new Error(problem);
5675
+ }
5676
+ return this.#tx(async (session) => {
5677
+ const parent = await this.#requireLivePage(input.parentId, session);
5678
+ return this.#insertPage(session, {
5679
+ id: input.id,
5680
+ parent,
5681
+ key: input.key,
5682
+ name: input.name,
5683
+ description: input.description,
5684
+ body: input.body,
5685
+ position: input.position,
5686
+ provenance: input.provenance,
5687
+ at: /* @__PURE__ */ new Date()
5688
+ });
5689
+ });
5018
5690
  }
5019
- async updateNode(input) {
5020
- await assertKnowledgeDescriptionWithinBoundCompat(input.description);
5021
- return this.#connector.withTransaction(async (session) => {
5022
- const existing = await this.#getNode(input.id, session);
5023
- if (!existing) throw new _mastra_core_storage.KnowledgeNotFoundError("node", input.id);
5024
- if (existing.mergedInto) throw new Error(`Cannot update merged knowledge node: ${input.id}`);
5025
- const scope = input.scope ? (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope) : existing.scope;
5026
- const name = input.name?.trim() ?? existing.name;
5027
- const content = input.content ?? existing.content;
5028
- const description = input.description ?? existing.description;
5691
+ async #insertPage(session, input) {
5692
+ const core = await loadPagesCore();
5693
+ const id = input.id ?? (0, _mastra_core_storage.createKnowledgeUlid)();
5694
+ const scopeId = input.parent.isScope ? input.parent.id : input.parent.scopeId;
5695
+ const depth = input.parent.isScope ? 1 : await this.#depthOf(input.parent.id, session) + 1;
5696
+ if (depth > core.MAX_KNOWLEDGE_PAGE_DEPTH) throw new core.KnowledgePageDepthError(id);
5697
+ const doc = {
5698
+ id,
5699
+ scopeId,
5700
+ parentId: input.parent.id,
5701
+ isScope: false,
5702
+ ...input.key === void 0 ? {} : {
5703
+ key: input.key,
5704
+ activeKey: activeKeyOf(input.parent.id, input.key)
5705
+ },
5706
+ position: input.position ?? core.knowledgePositionBetween(await this.#lastPosition(input.parent.id, session)),
5707
+ name: input.name,
5708
+ canonicalName: core.canonicalKnowledgeName(input.name),
5709
+ ...input.description === void 0 ? {} : { description: input.description },
5710
+ ...input.body === void 0 ? {} : { body: input.body },
5711
+ depth,
5712
+ version: 1,
5713
+ createdBy: input.provenance,
5714
+ updatedBy: input.provenance,
5715
+ createdAt: input.at,
5716
+ updatedAt: input.at
5717
+ };
5718
+ try {
5719
+ await (await this.#c("pages")).insertOne({ ...doc }, { session });
5720
+ } catch (error) {
5721
+ if (isDuplicateKey(error)) {
5722
+ if (input.key) throw new core.KnowledgePageKeyConflictError(input.key, input.parent.id);
5723
+ throw new _mastra_core_storage.KnowledgeConflictError(id);
5724
+ }
5725
+ throw error;
5726
+ }
5727
+ await this.#log(session, {
5728
+ action: "page-created",
5729
+ scopeId,
5730
+ pageId: id,
5731
+ provenance: input.provenance,
5732
+ at: input.at
5733
+ });
5734
+ return toPage(doc);
5735
+ }
5736
+ async #depthOf(id, session) {
5737
+ const row = await (await this.#c("pages")).findOne({ id }, {
5738
+ projection: {
5739
+ _id: 0,
5740
+ depth: 1
5741
+ },
5742
+ session
5743
+ });
5744
+ return Number(row?.depth ?? 0);
5745
+ }
5746
+ async updatePage(input) {
5747
+ const core = await loadPagesCore();
5748
+ (await this.#bounds()).assertKnowledgePageDescriptionWithinBound(input.description);
5749
+ return this.#tx(async (session) => {
5750
+ const page = await this.#requireLivePage(input.id, session);
5751
+ if (page.version !== input.expectedVersion) throw new _mastra_core_storage.KnowledgeConflictError(input.id);
5029
5752
  const now = /* @__PURE__ */ new Date();
5030
- const result = await (await this.#nodes()).findOneAndUpdate({
5753
+ const set = {
5754
+ updatedAt: now,
5755
+ updatedBy: input.provenance
5756
+ };
5757
+ const unset = {};
5758
+ if (input.name !== void 0) {
5759
+ set.name = input.name;
5760
+ set.canonicalName = core.canonicalKnowledgeName(input.name);
5761
+ }
5762
+ if (input.description !== void 0) {
5763
+ if (input.description === "") unset.description = "";
5764
+ else set.description = input.description;
5765
+ }
5766
+ if (input.body !== void 0) set.body = input.body;
5767
+ const updated = await (await this.#c("pages")).findOneAndUpdate({
5031
5768
  id: input.id,
5032
- type: "node",
5033
- version: input.version
5769
+ version: input.expectedVersion,
5770
+ ...live
5034
5771
  }, {
5035
- $set: {
5036
- name,
5037
- canonicalName: canonicalName(name),
5038
- kind: input.kind ?? existing.kind,
5039
- content: content ?? null,
5040
- description: description ?? null,
5041
- scope,
5042
- scopeKey: (0, _mastra_core_storage.knowledgeScopeKey)(scope),
5043
- updatedAt: now
5044
- },
5045
- $inc: { version: 1 }
5772
+ $set: set,
5773
+ $inc: { version: 1 },
5774
+ ...Object.keys(unset).length ? { $unset: unset } : {}
5046
5775
  }, {
5047
- ...sessionOptions(session),
5048
- returnDocument: "after"
5776
+ returnDocument: "after",
5777
+ projection: { _id: 0 },
5778
+ session
5049
5779
  });
5050
- if (!result) throw new _mastra_core_storage.KnowledgeConflictError(input.id);
5051
- if (input.content !== void 0 || input.name !== void 0 || input.scope !== void 0) await this.#replaceMentions("node", input.id, content ?? "", input.resolutionScope ?? scope, scope, session);
5052
- if ((0, _mastra_core_storage.knowledgeScopeKey)(scope) !== (0, _mastra_core_storage.knowledgeScopeKey)(existing.scope)) {
5053
- await this.#outbox("node", input.id, "delete", (0, _mastra_core_storage.createKnowledgeUlid)(), existing.scope, session);
5054
- const records = await (await this.#knowledge()).find({ node: input.id }, sessionOptions(session)).toArray();
5055
- for (const record of records) {
5056
- await this.#outbox("record", record.id, "delete", (0, _mastra_core_storage.createKnowledgeUlid)(), record.scope, session);
5057
- if (!record.deletedAt) await this.#outbox("record", record.id, "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), record.scope, session);
5058
- }
5780
+ if (!updated) throw new _mastra_core_storage.KnowledgeConflictError(input.id);
5781
+ await this.#log(session, {
5782
+ action: "page-updated",
5783
+ scopeId: page.scopeId,
5784
+ pageId: page.id,
5785
+ provenance: input.provenance,
5786
+ at: now
5787
+ });
5788
+ return toPage(updated);
5789
+ });
5790
+ }
5791
+ /** Rewrites everything that follows a page's home scope to `scopeId`, for the pages in `moved`. */
5792
+ async #rehome(moved, scopeId, depthDelta, session) {
5793
+ const pages = await this.#c("pages");
5794
+ const descendants = moved.slice(1);
5795
+ if (descendants.length) await pages.updateMany({ id: { $in: descendants } }, [{ $set: {
5796
+ scopeId,
5797
+ depth: { $add: ["$depth", depthDelta] }
5798
+ } }], { session });
5799
+ await (await this.#c("notes")).updateMany({ pageId: { $in: moved } }, { $set: { pageScopeId: scopeId } }, { session });
5800
+ await (await this.#c("activity")).updateMany({ pageId: { $in: moved } }, { $set: { pageScopeId: scopeId } }, { session });
5801
+ }
5802
+ async movePage(input) {
5803
+ const core = await loadPagesCore();
5804
+ return this.#tx(async (session) => {
5805
+ const page = await this.#requireLivePage(input.id, session);
5806
+ if (page.version !== input.expectedVersion) throw new _mastra_core_storage.KnowledgeConflictError(input.id);
5807
+ if (page.isScope) throw new Error(`Knowledge scope page ${input.id} can't be moved`);
5808
+ if (input.parentId === input.id) throw new Error(`Knowledge page ${input.id} can't move under itself or its own subtree`);
5809
+ const tree = await this.#subtree(input.id, session, input.parentId);
5810
+ if (tree.found) throw new Error(`Knowledge page ${input.id} can't move under itself or its own subtree`);
5811
+ const parent = await this.#requireLivePage(input.parentId, session);
5812
+ if (tree.live + 1 > core.MAX_KNOWLEDGE_MOVE_PAGES) throw new core.KnowledgeMoveTooLargeError(input.id, tree.live + 1);
5813
+ const newScopeId = parent.isScope ? parent.id : parent.scopeId;
5814
+ const newDepth = parent.isScope ? 1 : await this.#depthOf(parent.id, session) + 1;
5815
+ const delta = newDepth - await this.#depthOf(page.id, session);
5816
+ if (page.key) await this.#assertNoKeyConflicts([page.key], parent.id, session, page.id);
5817
+ if (tree.maxDepth + delta > core.MAX_KNOWLEDGE_PAGE_DEPTH || newDepth > core.MAX_KNOWLEDGE_PAGE_DEPTH) throw new core.KnowledgePageDepthError(input.id);
5818
+ const position = input.position ?? core.knowledgePositionBetween(await this.#lastPosition(parent.id, session));
5819
+ const now = /* @__PURE__ */ new Date();
5820
+ let updated;
5821
+ try {
5822
+ await this.#rehome([page.id, ...tree.ids], newScopeId, delta, session);
5823
+ updated = await (await this.#c("pages")).findOneAndUpdate({
5824
+ id: input.id,
5825
+ version: input.expectedVersion
5826
+ }, {
5827
+ $set: {
5828
+ parentId: parent.id,
5829
+ scopeId: newScopeId,
5830
+ ...page.key ? { activeKey: activeKeyOf(parent.id, page.key) } : {},
5831
+ depth: newDepth,
5832
+ position,
5833
+ updatedAt: now,
5834
+ updatedBy: input.provenance
5835
+ },
5836
+ $inc: { version: 1 }
5837
+ }, {
5838
+ returnDocument: "after",
5839
+ projection: { _id: 0 },
5840
+ session
5841
+ });
5842
+ } catch (error) {
5843
+ if (isDuplicateKey(error)) throw new _mastra_core_storage.KnowledgeConflictError(page.key ? `${parent.id}#${page.key}` : input.id);
5844
+ throw error;
5059
5845
  }
5060
- await this.#activity("node-updated", "node", input.id, scope, void 0, session);
5061
- await this.#outbox("node", input.id, "upsert", Number(result.version), scope, session);
5062
- return nodeFromDocument(result);
5846
+ if (!updated) throw new _mastra_core_storage.KnowledgeConflictError(input.id);
5847
+ await this.#refreshMentionScopes([page.id, ...tree.ids], session);
5848
+ await this.#log(session, {
5849
+ action: "page-moved",
5850
+ scopeId: newScopeId,
5851
+ pageId: input.id,
5852
+ provenance: input.provenance,
5853
+ at: now
5854
+ });
5855
+ return toPage(updated);
5063
5856
  });
5064
5857
  }
5065
- async mergeNodes(input) {
5066
- if (input.sourceId === input.targetId) throw new Error("Cannot merge a knowledge node into itself");
5067
- return this.#connector.withTransaction(async (session) => {
5068
- const source = await this.#getNode(input.sourceId, session);
5069
- if (!source) throw new _mastra_core_storage.KnowledgeNotFoundError("node", input.sourceId);
5070
- const target = await this.#resolveTerminalNode(input.targetId, session);
5071
- if (!target) throw new _mastra_core_storage.KnowledgeNotFoundError("node", input.targetId);
5072
- if (target.id === source.id) throw new Error("Cannot create a knowledge merge cycle");
5073
- if (!(0, _mastra_core_storage.isKnowledgeScopeVisible)(target.scope, source.scope)) throw new Error("Cannot merge a knowledge node into a target that is narrower than its source scope");
5074
- const mentions = await this.#mentions();
5075
- const affected = await mentions.find({ recordId: source.id }, sessionOptions(session)).toArray();
5076
- const movedFacts = await (await this.#knowledge()).find({ node: source.id }, sessionOptions(session)).toArray();
5077
- if ((await (await this.#nodes()).updateOne({
5858
+ async mergePages(input) {
5859
+ const core = await loadPagesCore();
5860
+ return this.#tx(async (session) => {
5861
+ if (input.sourceId === input.targetId) throw new Error(`Knowledge page ${input.sourceId} can't merge into itself or its own subtree`);
5862
+ const source = await this.#requireLivePage(input.sourceId, session);
5863
+ const target = await this.#requireLivePage(input.targetId, session);
5864
+ if (source.version !== input.sourceVersion) throw new _mastra_core_storage.KnowledgeConflictError(input.sourceId);
5865
+ if (source.isScope || target.isScope) throw new Error("Knowledge scope pages can't be merged");
5866
+ const tree = await this.#subtree(source.id, session, target.id);
5867
+ if (tree.found) throw new Error(`Knowledge page ${source.id} can't merge into itself or its own subtree`);
5868
+ if (tree.live > core.MAX_KNOWLEDGE_MOVE_PAGES) throw new core.KnowledgeMoveTooLargeError(source.id, tree.live);
5869
+ const delta = await this.#depthOf(target.id, session) - await this.#depthOf(source.id, session);
5870
+ const arriving = await (await this.#c("pages")).find({
5871
+ parentId: source.id,
5872
+ ...live,
5873
+ ...notScope,
5874
+ key: { $type: "string" }
5875
+ }, {
5876
+ projection: {
5877
+ _id: 0,
5878
+ key: 1
5879
+ },
5880
+ session
5881
+ }).toArray();
5882
+ await this.#assertNoKeyConflicts(arriving.map((row) => String(row.key)), target.id, session, source.id);
5883
+ if (tree.maxDepth > 0 && tree.maxDepth + delta > core.MAX_KNOWLEDGE_PAGE_DEPTH) throw new core.KnowledgePageDepthError(source.id);
5884
+ const now = /* @__PURE__ */ new Date();
5885
+ const pages = await this.#c("pages");
5886
+ const notes = await this.#c("notes");
5887
+ if ((await pages.updateOne({
5078
5888
  id: source.id,
5079
- type: "node",
5080
- version: input.sourceVersion,
5081
- mergedInto: null
5889
+ version: input.sourceVersion
5082
5890
  }, {
5083
5891
  $set: {
5892
+ deletedAt: now,
5893
+ deletedBy: input.provenance.author,
5084
5894
  mergedInto: target.id,
5085
- updatedAt: /* @__PURE__ */ new Date()
5895
+ scopeId: target.scopeId,
5896
+ updatedAt: now,
5897
+ updatedBy: input.provenance
5086
5898
  },
5899
+ $unset: { activeKey: "" },
5087
5900
  $inc: { version: 1 }
5088
- }, sessionOptions(session))).modifiedCount === 0) throw new _mastra_core_storage.KnowledgeConflictError(source.id);
5089
- await (await this.#knowledge()).updateMany({ node: source.id }, { $set: { node: target.id } }, sessionOptions(session));
5090
- for (const mention of affected) if (await mentions.findOne({
5091
- sourceType: mention.sourceType,
5092
- sourceId: mention.sourceId,
5093
- recordId: target.id
5094
- }, sessionOptions(session))) await mentions.deleteOne({ _id: mention._id }, sessionOptions(session));
5095
- else await mentions.updateOne({ _id: mention._id }, { $set: { recordId: target.id } }, sessionOptions(session));
5096
- for (const record of movedFacts) if (!record.deletedAt) await this.#outbox("record", record.id, "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), record.scope, session);
5097
- for (const mention of affected) {
5098
- const scope = mention.sourceType === "record" ? (await (await this.#knowledge()).findOne({ id: mention.sourceId }, sessionOptions(session)))?.scope : (await (await this.#nodes()).findOne({
5099
- id: mention.sourceId,
5100
- type: "node"
5101
- }, sessionOptions(session)))?.scope;
5102
- if (scope) await this.#outbox(mention.sourceType, mention.sourceId, "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), scope, session);
5901
+ }, { session })).matchedCount === 0) throw new _mastra_core_storage.KnowledgeConflictError(input.sourceId);
5902
+ try {
5903
+ if (tree.ids.length) {
5904
+ await pages.updateMany({ id: { $in: tree.ids } }, [{ $set: {
5905
+ scopeId: target.scopeId,
5906
+ depth: { $add: ["$depth", delta] }
5907
+ } }], { session });
5908
+ await notes.updateMany({ pageId: { $in: tree.ids } }, { $set: { pageScopeId: target.scopeId } }, { session });
5909
+ await (await this.#c("activity")).updateMany({ pageId: { $in: tree.ids } }, { $set: { pageScopeId: target.scopeId } }, { session });
5910
+ }
5911
+ await pages.updateMany({
5912
+ parentId: source.id,
5913
+ ...notScope
5914
+ }, [{ $set: { parentId: target.id } }, recomputeActiveKey(target.id)], { session });
5915
+ } catch (error) {
5916
+ if (isDuplicateKey(error)) throw new _mastra_core_storage.KnowledgeConflictError(source.id);
5917
+ throw error;
5103
5918
  }
5104
- let mergedTarget = target;
5105
- if (target.description === void 0 && source.description) {
5106
- const adoptedAt = /* @__PURE__ */ new Date();
5107
- if ((await (await this.#nodes()).updateOne({
5108
- id: target.id,
5109
- type: "node",
5110
- version: target.version,
5111
- description: null
5112
- }, {
5113
- $set: {
5114
- description: source.description,
5115
- updatedAt: adoptedAt
5116
- },
5117
- $inc: { version: 1 }
5118
- }, sessionOptions(session))).modifiedCount > 0) {
5119
- mergedTarget = {
5120
- ...target,
5121
- description: source.description,
5122
- version: target.version + 1,
5123
- updatedAt: adoptedAt
5124
- };
5125
- await this.#activity("node-updated", "node", target.id, target.scope, void 0, session);
5126
- }
5919
+ await notes.updateMany({ pageId: source.id }, { $set: {
5920
+ pageId: target.id,
5921
+ pageScopeId: target.scopeId
5922
+ } }, { session });
5923
+ await notes.updateMany({ mentions: source.id }, [{ $set: { mentions: { $setUnion: [{ $map: {
5924
+ input: "$mentions",
5925
+ in: { $cond: [
5926
+ { $eq: ["$$this", source.id] },
5927
+ target.id,
5928
+ "$$this"
5929
+ ] }
5930
+ } }] } } }], { session });
5931
+ await this.#refreshMentionScopes([target.id, ...tree.ids], session);
5932
+ const pins = await this.#c("pins");
5933
+ const sourcePin = await pins.findOne({ pageId: source.id }, {
5934
+ ...noProjection,
5935
+ session
5936
+ });
5937
+ if (sourcePin) {
5938
+ await this.#upsertPinAudience(session, target.id, sourcePin.audience ?? [], String(sourcePin.createdBy), now);
5939
+ await pins.deleteOne({ id: sourcePin.id }, { session });
5127
5940
  }
5128
- await this.#activity("node-merged", "node", source.id, source.scope, void 0, session);
5129
- await this.#outbox("node", source.id, "delete", input.sourceVersion + 1, source.scope, session);
5130
- await this.#outbox("node", target.id, "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), mergedTarget.scope, session);
5131
- return mergedTarget;
5941
+ await (await this.#c("activity")).updateMany({ pageId: source.id }, { $set: { pageScopeId: target.scopeId } }, { session });
5942
+ await this.#log(session, {
5943
+ action: "page-merged",
5944
+ scopeId: target.scopeId,
5945
+ pageScopeId: target.scopeId,
5946
+ pageId: source.id,
5947
+ provenance: input.provenance,
5948
+ at: now
5949
+ });
5950
+ return await this.#page(target.id, session);
5132
5951
  });
5133
5952
  }
5134
- async appendKnowledge(input) {
5135
- await assertKnowledgeRecordTextWithinBoundCompat(input.text);
5136
- const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
5137
- const defaultScope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.defaultScope);
5138
- return this.#connector.withTransaction(async (session) => {
5139
- const parent = await this.#resolveTerminalNode(nodeReferenceId(input.node), session);
5140
- if (!parent) throw new _mastra_core_storage.KnowledgeNotFoundError("node", nodeReferenceId(input.node));
5141
- const id = input.id ?? (0, _mastra_core_storage.createKnowledgeUlid)();
5142
- const existing = await (await this.#knowledge()).findOne({ id }, sessionOptions(session));
5143
- if (existing) return recordFromDocument(existing);
5144
- const record = {
5145
- id,
5146
- node: parent.id,
5147
- text: input.text,
5148
- scope,
5149
- sourceThreadId: input.sourceThreadId,
5150
- capturedAt: /* @__PURE__ */ new Date(),
5151
- when: input.when,
5152
- metadata: input.metadata
5153
- };
5154
- await (await this.#knowledge()).insertOne({
5155
- ...record,
5156
- scopeKey: (0, _mastra_core_storage.knowledgeScopeKey)(scope),
5157
- when: record.when ?? null,
5158
- deletedAt: null,
5159
- deletedBy: null
5160
- }, sessionOptions(session));
5161
- await this.#replaceMentions("record", id, record.text, input.resolutionScope, defaultScope, session);
5162
- await this.#activity("record-created", "record", id, scope, input.sourceThreadId, session);
5163
- await this.#outbox("record", id, "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), scope, session);
5164
- return record;
5953
+ async deletePage(input) {
5954
+ const core = await loadPagesCore();
5955
+ return this.#tx(async (session) => {
5956
+ const page = await this.#requireLivePage(input.id, session);
5957
+ if (page.version !== input.expectedVersion) throw new _mastra_core_storage.KnowledgeConflictError(input.id);
5958
+ if (page.isScope) throw new Error(`Knowledge scope page ${input.id} can't be deleted`);
5959
+ const pages = await this.#c("pages");
5960
+ if (await pages.findOne({
5961
+ parentId: input.id,
5962
+ ...live
5963
+ }, {
5964
+ projection: { id: 1 },
5965
+ session
5966
+ })) throw new core.KnowledgePageHasChildrenError(input.id);
5967
+ const now = /* @__PURE__ */ new Date();
5968
+ const updated = await pages.findOneAndUpdate({
5969
+ id: input.id,
5970
+ version: input.expectedVersion,
5971
+ ...live
5972
+ }, {
5973
+ $set: {
5974
+ deletedAt: now,
5975
+ deletedBy: input.deletedBy,
5976
+ updatedAt: now,
5977
+ updatedBy: { author: input.deletedBy }
5978
+ },
5979
+ $unset: { activeKey: "" },
5980
+ $inc: { version: 1 }
5981
+ }, {
5982
+ returnDocument: "after",
5983
+ projection: { _id: 0 },
5984
+ session
5985
+ });
5986
+ if (!updated) throw new _mastra_core_storage.KnowledgeConflictError(input.id);
5987
+ await (await this.#c("pins")).deleteOne({ pageId: input.id }, { session });
5988
+ await this.#log(session, {
5989
+ action: "page-deleted",
5990
+ scopeId: page.scopeId,
5991
+ pageId: page.id,
5992
+ provenance: { author: input.deletedBy },
5993
+ at: now
5994
+ });
5995
+ return toPage(updated);
5165
5996
  });
5166
5997
  }
5167
- async getKnowledge(input) {
5168
- const row = await (await this.#knowledge()).findOne({
5998
+ async getNote(input) {
5999
+ const ids = await this.#readable(input.read);
6000
+ const filter = {
5169
6001
  id: input.id,
5170
- ...input.includeDeleted ? {} : { deletedAt: null }
5171
- });
5172
- return row ? recordFromDocument(row) : null;
5173
- }
5174
- async listKnowledgeAbout(input) {
5175
- return this.#queryKnowledge(input, "about");
5176
- }
5177
- async listKnowledgeMentioning(input) {
5178
- return this.#queryKnowledge(input, "mentioning");
5179
- }
5180
- async listKnowledgeRelatedTo(input) {
5181
- return this.#queryKnowledge(input, "related");
5182
- }
5183
- async knowledgeBySource(input) {
5184
- const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
5185
- const limit = input.limit ?? 100;
5186
- const rows = await (await this.#knowledge()).find({
5187
- sourceThreadId: input.sourceThreadId,
5188
- scopeKey: { $in: visibleScopeKeys(scope) },
5189
- ...input.includeDeleted ? {} : { deletedAt: null },
5190
- ...input.after ? { id: { $gt: input.after } } : {}
5191
- }).sort({ id: 1 }).limit(limit + 1).toArray();
6002
+ ...this.#visibleNotes(ids)
6003
+ };
6004
+ if (!input.includeDeleted) Object.assign(filter, live);
6005
+ const row = await (await this.#c("notes")).findOne(filter, noProjection);
6006
+ return row ? toNote(row) : null;
6007
+ }
6008
+ async listNotes(input) {
6009
+ const core = await loadPagesCore();
6010
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
6011
+ const ids = await this.#readable(input.read);
6012
+ const filter = {
6013
+ pageId: input.pageId,
6014
+ ...this.#visibleNotes(ids)
6015
+ };
6016
+ if (!input.includeDeleted) Object.assign(filter, live);
6017
+ if (input.cursor) {
6018
+ const [createdAt, id] = decodeCursor(input.cursor);
6019
+ const at = new Date(createdAt);
6020
+ filter.$or = [{ createdAt: { $gt: at } }, {
6021
+ createdAt: at,
6022
+ id: { $gt: id }
6023
+ }];
6024
+ }
6025
+ const rows = await (await this.#c("notes")).find(filter, noProjection).sort({
6026
+ createdAt: 1,
6027
+ id: 1
6028
+ }).limit(limit + 1).toArray();
6029
+ return this.#noteOutput(rows, limit);
6030
+ }
6031
+ async countChildPages(input) {
6032
+ const ids = [...new Set(input.parentIds)];
6033
+ const counts = Object.fromEntries(ids.map((id) => [id, 0]));
6034
+ if (!ids.length) return counts;
6035
+ const readable = await this.#readable(input.read);
6036
+ const rows = await (await this.#c("pages")).aggregate([{ $match: {
6037
+ parentId: { $in: ids },
6038
+ ...notScope,
6039
+ ...live,
6040
+ ...this.#inScopes("scopeId", readable)
6041
+ } }, { $group: {
6042
+ _id: "$parentId",
6043
+ count: { $sum: 1 }
6044
+ } }]).toArray();
6045
+ for (const row of rows) counts[row._id] = row.count;
6046
+ return counts;
6047
+ }
6048
+ async countNotes(input) {
6049
+ const ids = [...new Set(input.pageIds)];
6050
+ const counts = Object.fromEntries(ids.map((id) => [id, 0]));
6051
+ if (!ids.length) return counts;
6052
+ const readable = await this.#readable(input.read);
6053
+ const rows = await (await this.#c("notes")).aggregate([{ $match: {
6054
+ pageId: { $in: ids },
6055
+ ...live,
6056
+ ...this.#visibleNotes(readable)
6057
+ } }, { $group: {
6058
+ _id: "$pageId",
6059
+ count: { $sum: 1 }
6060
+ } }]).toArray();
6061
+ for (const row of rows) counts[row._id] = row.count;
6062
+ return counts;
6063
+ }
6064
+ async listNotesMentioning(input) {
6065
+ const core = await loadPagesCore();
6066
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
6067
+ const ids = await this.#readable(input.read);
6068
+ const match = {
6069
+ mentions: input.pageId,
6070
+ pageId: { $ne: input.pageId },
6071
+ ...live,
6072
+ ...this.#visibleNotes(ids)
6073
+ };
6074
+ if (input.cursor) {
6075
+ const [createdAt, id] = decodeCursor(input.cursor);
6076
+ const at = new Date(createdAt);
6077
+ match.$or = [{ createdAt: { $lt: at } }, {
6078
+ createdAt: at,
6079
+ id: { $lt: id }
6080
+ }];
6081
+ }
6082
+ const rows = await (await this.#c("notes")).aggregate([
6083
+ { $match: match },
6084
+ { $lookup: {
6085
+ from: MONGO_KNOWLEDGE_PAGES_COLLECTIONS.pages,
6086
+ localField: "pageId",
6087
+ foreignField: "id",
6088
+ as: "page"
6089
+ } },
6090
+ { $match: { "page.deletedAt": { $exists: false } } },
6091
+ { $project: {
6092
+ _id: 0,
6093
+ page: 0
6094
+ } },
6095
+ { $sort: {
6096
+ createdAt: -1,
6097
+ id: -1
6098
+ } },
6099
+ { $limit: limit + 1 }
6100
+ ]).toArray();
6101
+ return this.#noteOutput(rows, limit);
6102
+ }
6103
+ #noteOutput(rows, limit) {
6104
+ const notes = rows.slice(0, limit).map(toNote);
6105
+ const last = notes[notes.length - 1];
5192
6106
  return {
5193
- records: rows.slice(0, limit).map(recordFromDocument),
5194
- nextCursor: rows.length > limit ? rows[limit - 1]?.id : void 0
6107
+ notes,
6108
+ ...rows.length > limit && last ? { nextCursor: encodeCursor([last.createdAt.toISOString(), last.id]) } : {}
5195
6109
  };
5196
6110
  }
5197
- async removeKnowledge(input) {
5198
- return this.#connector.withTransaction(async (session) => {
5199
- const record = await this.#getKnowledge(input.id, true, session);
5200
- if (!record) throw new _mastra_core_storage.KnowledgeNotFoundError("record", input.id);
5201
- if (record.deletedAt) return record;
5202
- const deletedAt = /* @__PURE__ */ new Date();
5203
- await (await this.#knowledge()).updateOne({
5204
- id: input.id,
5205
- deletedAt: null
5206
- }, { $set: {
5207
- deletedAt,
5208
- deletedBy: input.deletedBy
5209
- } }, sessionOptions(session));
5210
- await this.#activity("record-deleted", "record", input.id, record.scope, record.sourceThreadId, session);
5211
- await this.#outbox("record", input.id, "delete", (0, _mastra_core_storage.createKnowledgeUlid)(), record.scope, session);
5212
- return {
5213
- ...record,
5214
- deletedAt,
5215
- deletedBy: input.deletedBy
6111
+ async #assertScopePages(ids, session) {
6112
+ const rows = await (await this.#c("pages")).find({
6113
+ id: { $in: ids },
6114
+ isScope: true
6115
+ }, {
6116
+ projection: {
6117
+ _id: 0,
6118
+ id: 1
6119
+ },
6120
+ session
6121
+ }).toArray();
6122
+ const found = new Set(rows.map((row) => String(row.id)));
6123
+ const missing = ids.find((id) => !found.has(id));
6124
+ if (missing) throw new Error(`Knowledge note stamp ${missing} is not a scope page`);
6125
+ }
6126
+ async addNote(input) {
6127
+ (await this.#bounds()).assertKnowledgeNoteTextWithinBound(input.text);
6128
+ if (input.stampScopeIds.length === 0) throw new Error("A Knowledge note needs at least one stamp scope");
6129
+ return this.#tx(async (session) => {
6130
+ const page = await this.#requireLivePage(input.pageId, session);
6131
+ const stampIds = [...new Set(input.stampScopeIds)];
6132
+ await this.#assertScopePages(stampIds, session);
6133
+ const mentionIds = [...new Set(input.mentions)];
6134
+ let mentionScopeIds = [];
6135
+ if (mentionIds.length) {
6136
+ const found = await (await this.#c("pages")).find({ id: { $in: mentionIds } }, {
6137
+ projection: {
6138
+ _id: 0,
6139
+ id: 1,
6140
+ scopeId: 1
6141
+ },
6142
+ session
6143
+ }).toArray();
6144
+ const known = new Set(found.map((row) => String(row.id)));
6145
+ const missing = mentionIds.find((id) => !known.has(id));
6146
+ if (missing) throw new _mastra_core_storage.KnowledgeNotFoundError("page", missing);
6147
+ mentionScopeIds = [...new Set(found.map((row) => String(row.scopeId)))];
6148
+ }
6149
+ const id = input.id ?? (0, _mastra_core_storage.createKnowledgeUlid)();
6150
+ const now = /* @__PURE__ */ new Date();
6151
+ const doc = {
6152
+ id,
6153
+ pageId: page.id,
6154
+ pageScopeId: page.scopeId,
6155
+ text: input.text,
6156
+ ...input.when ? { when: input.when } : {},
6157
+ stampScopeIds: stampIds,
6158
+ mentions: mentionIds,
6159
+ mentionScopeIds,
6160
+ provenance: input.provenance,
6161
+ version: 1,
6162
+ createdAt: now,
6163
+ updatedAt: now
5216
6164
  };
6165
+ try {
6166
+ await (await this.#c("notes")).insertOne({ ...doc }, { session });
6167
+ } catch (error) {
6168
+ if (isDuplicateKey(error)) throw new _mastra_core_storage.KnowledgeConflictError(id);
6169
+ throw error;
6170
+ }
6171
+ await this.#log(session, {
6172
+ action: "note-added",
6173
+ scopeId: page.scopeId,
6174
+ pageId: page.id,
6175
+ noteId: id,
6176
+ provenance: input.provenance,
6177
+ at: now
6178
+ });
6179
+ return toNote(doc);
5217
6180
  });
5218
6181
  }
5219
- async restoreKnowledge(input) {
5220
- return this.#connector.withTransaction(async (session) => {
5221
- const record = await this.#getKnowledge(input.id, true, session);
5222
- if (!record) throw new _mastra_core_storage.KnowledgeNotFoundError("record", input.id);
5223
- if (!record.deletedAt) return record;
5224
- await (await this.#knowledge()).updateOne({ id: input.id }, { $set: {
5225
- deletedAt: null,
5226
- deletedBy: null
5227
- } }, sessionOptions(session));
5228
- await this.#activity("record-restored", "record", input.id, record.scope, record.sourceThreadId, session);
5229
- await this.#outbox("record", input.id, "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), record.scope, session);
5230
- return {
5231
- ...record,
5232
- deletedAt: void 0,
5233
- deletedBy: void 0
5234
- };
6182
+ async #requireNote(id, session) {
6183
+ const row = await (await this.#c("notes")).findOne({ id }, {
6184
+ ...noProjection,
6185
+ session
6186
+ });
6187
+ if (!row) throw new _mastra_core_storage.KnowledgeNotFoundError("note", id);
6188
+ return row;
6189
+ }
6190
+ async restampNote(input) {
6191
+ if (input.stampScopeIds.length === 0) throw new Error("A Knowledge note needs at least one stamp scope");
6192
+ return this.#tx(async (session) => {
6193
+ const note = await this.#requireNote(input.id, session);
6194
+ if (note.deletedAt) throw new _mastra_core_storage.KnowledgeNotFoundError("note", input.id);
6195
+ if (Number(note.version) !== input.expectedVersion) throw new _mastra_core_storage.KnowledgeConflictError(input.id);
6196
+ const stampIds = [...new Set(input.stampScopeIds)];
6197
+ await this.#assertScopePages(stampIds, session);
6198
+ const now = /* @__PURE__ */ new Date();
6199
+ const updated = await (await this.#c("notes")).findOneAndUpdate({
6200
+ id: input.id,
6201
+ version: input.expectedVersion
6202
+ }, {
6203
+ $set: {
6204
+ stampScopeIds: stampIds,
6205
+ updatedAt: now
6206
+ },
6207
+ $inc: { version: 1 }
6208
+ }, {
6209
+ returnDocument: "after",
6210
+ projection: { _id: 0 },
6211
+ session
6212
+ });
6213
+ if (!updated) throw new _mastra_core_storage.KnowledgeConflictError(input.id);
6214
+ await this.#log(session, {
6215
+ action: "note-restamped",
6216
+ scopeId: String(note.pageScopeId),
6217
+ pageId: String(note.pageId),
6218
+ noteId: input.id,
6219
+ provenance: input.provenance,
6220
+ at: now
6221
+ });
6222
+ return toNote(updated);
5235
6223
  });
5236
6224
  }
5237
- async rescopeKnowledge(input) {
5238
- const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
5239
- return this.#connector.withTransaction(async (session) => {
5240
- const record = await this.#getKnowledge(input.id, true, session);
5241
- if (!record) throw new _mastra_core_storage.KnowledgeNotFoundError("record", input.id);
5242
- await (await this.#knowledge()).updateOne({ id: input.id }, { $set: {
5243
- scope,
5244
- scopeKey: (0, _mastra_core_storage.knowledgeScopeKey)(scope)
5245
- } }, sessionOptions(session));
5246
- await this.#activity("record-rescoped", "record", input.id, scope, record.sourceThreadId, session);
5247
- await this.#outbox("record", input.id, "delete", (0, _mastra_core_storage.createKnowledgeUlid)(), record.scope, session);
5248
- if (!record.deletedAt) await this.#outbox("record", input.id, "upsert", (0, _mastra_core_storage.createKnowledgeUlid)(), scope, session);
5249
- return {
5250
- ...record,
5251
- scope
5252
- };
6225
+ async removeNote(input) {
6226
+ return this.#tx(async (session) => {
6227
+ const note = await this.#requireNote(input.id, session);
6228
+ if (note.deletedAt) return toNote(note);
6229
+ const now = /* @__PURE__ */ new Date();
6230
+ const updated = await (await this.#c("notes")).findOneAndUpdate({ id: input.id }, {
6231
+ $set: {
6232
+ deletedAt: now,
6233
+ deletedBy: input.deletedBy,
6234
+ updatedAt: now
6235
+ },
6236
+ $inc: { version: 1 }
6237
+ }, {
6238
+ returnDocument: "after",
6239
+ projection: { _id: 0 },
6240
+ session
6241
+ });
6242
+ await this.#log(session, {
6243
+ action: "note-removed",
6244
+ scopeId: String(note.pageScopeId),
6245
+ pageId: String(note.pageId),
6246
+ noteId: input.id,
6247
+ provenance: input.provenance,
6248
+ at: now
6249
+ });
6250
+ return toNote(updated);
5253
6251
  });
5254
6252
  }
5255
- async search(input) {
5256
- const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
5257
- const query = input.query.trim();
5258
- if (!query) return [];
5259
- const regex = new RegExp(this.#escapeRegex(query), "i");
5260
- const limit = input.limit ?? 20;
5261
- const results = (await (await this.#nodes()).find({
5262
- mergedInto: null,
5263
- scopeKey: { $in: visibleScopeKeys(scope) },
5264
- $or: [
5265
- { name: regex },
5266
- { kind: regex },
5267
- { content: regex },
5268
- { description: regex }
5269
- ]
5270
- }).sort({ updatedAt: -1 }).limit(limit).toArray()).map((row) => ({
5271
- type: "node",
5272
- id: row.id,
5273
- recordId: row.id,
5274
- name: row.name,
5275
- text: [
5276
- row.name,
5277
- ...row.description ? [row.description] : [],
5278
- ...row.content ? [row.content] : []
5279
- ].join("\n"),
5280
- scope: cloneScope(row.scope)
6253
+ async restoreNote(input) {
6254
+ return this.#tx(async (session) => {
6255
+ const note = await this.#requireNote(input.id, session);
6256
+ if (!note.deletedAt) return toNote(note);
6257
+ const now = /* @__PURE__ */ new Date();
6258
+ const updated = await (await this.#c("notes")).findOneAndUpdate({ id: input.id }, {
6259
+ $set: { updatedAt: now },
6260
+ $unset: {
6261
+ deletedAt: "",
6262
+ deletedBy: ""
6263
+ },
6264
+ $inc: { version: 1 }
6265
+ }, {
6266
+ returnDocument: "after",
6267
+ projection: { _id: 0 },
6268
+ session
6269
+ });
6270
+ await this.#log(session, {
6271
+ action: "note-restored",
6272
+ scopeId: String(note.pageScopeId),
6273
+ pageId: String(note.pageId),
6274
+ noteId: input.id,
6275
+ provenance: input.provenance,
6276
+ at: now
6277
+ });
6278
+ return toNote(updated);
6279
+ });
6280
+ }
6281
+ async searchPages(input) {
6282
+ const core = await loadPagesCore();
6283
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
6284
+ const words = knowledgeSearchWords(input.query);
6285
+ if (!words.length) return [];
6286
+ const phrase = input.query.trim().toLowerCase().replace(/\s+/g, " ");
6287
+ const ids = await this.#readable(input.read);
6288
+ const scopes = input.scopeIds?.length ? input.scopeIds : void 0;
6289
+ const inScope = (field) => {
6290
+ if (ids === null) return scopes ? { [field]: { $in: scopes } } : {};
6291
+ const allowed = scopes ? scopes.filter((id) => ids.includes(id)) : ids;
6292
+ return { [field]: { $in: allowed } };
6293
+ };
6294
+ const matcher = (word) => ({
6295
+ $regex: escapeRegex(word),
6296
+ $options: "i"
6297
+ });
6298
+ const pages = await this.#c("pages");
6299
+ const pageFilter = {
6300
+ ...live,
6301
+ ...notScope,
6302
+ ...inScope("scopeId"),
6303
+ $or: words.flatMap((word) => [
6304
+ { name: matcher(word) },
6305
+ { description: matcher(word) },
6306
+ { body: matcher(word) }
6307
+ ])
6308
+ };
6309
+ const has = (field, word) => ({ $regexMatch: {
6310
+ input: { $ifNull: [`$${field}`, ""] },
6311
+ regex: escapeRegex(word),
6312
+ options: "i"
6313
+ } });
6314
+ const hits = (await pages.aggregate([
6315
+ { $match: pageFilter },
6316
+ { $addFields: {
6317
+ searchTier: { $cond: [
6318
+ { $regexMatch: {
6319
+ input: "$canonicalName",
6320
+ regex: escapeRegex(phrase)
6321
+ } },
6322
+ 0,
6323
+ 1
6324
+ ] },
6325
+ searchCount: { $add: words.map((word) => ({ $cond: [
6326
+ { $or: [
6327
+ has("name", word),
6328
+ has("description", word),
6329
+ has("body", word)
6330
+ ] },
6331
+ 1,
6332
+ 0
6333
+ ] })) },
6334
+ searchScore: { $add: words.map((word) => ({ $switch: {
6335
+ branches: [
6336
+ {
6337
+ case: has("name", word),
6338
+ then: KNOWLEDGE_SEARCH_WEIGHTS.name
6339
+ },
6340
+ {
6341
+ case: has("description", word),
6342
+ then: KNOWLEDGE_SEARCH_WEIGHTS.description
6343
+ },
6344
+ {
6345
+ case: has("body", word),
6346
+ then: KNOWLEDGE_SEARCH_WEIGHTS.body
6347
+ }
6348
+ ],
6349
+ default: 0
6350
+ } })) }
6351
+ } },
6352
+ { $sort: {
6353
+ searchTier: 1,
6354
+ searchCount: -1,
6355
+ searchScore: -1,
6356
+ updatedAt: -1,
6357
+ id: 1
6358
+ } },
6359
+ { $limit: limit },
6360
+ { $project: {
6361
+ searchTier: 0,
6362
+ searchCount: 0,
6363
+ searchScore: 0,
6364
+ _id: 0
6365
+ } }
6366
+ ]).toArray()).map((row) => ({
6367
+ type: "page",
6368
+ page: toPage(row)
5281
6369
  }));
5282
- if (results.length < limit) {
5283
- const records = await (await this.#knowledge()).find({
5284
- deletedAt: null,
5285
- scopeKey: { $in: visibleScopeKeys(scope) },
5286
- text: regex
5287
- }).sort({ id: -1 }).limit(limit - results.length).toArray();
5288
- for (const record of records) {
5289
- const parent = await this.#resolveTerminalNode(record.node);
5290
- const parentVisible = parent && (0, _mastra_core_storage.isKnowledgeScopeVisible)(parent.scope, scope);
5291
- results.push({
5292
- type: "record",
5293
- id: record.id,
5294
- recordId: parentVisible ? record.node : record.id,
5295
- name: parentVisible ? parent.name : "(private node)",
5296
- text: record.text,
5297
- scope: cloneScope(record.scope)
5298
- });
5299
- }
6370
+ if (hits.length >= limit) return hits;
6371
+ const noteRows = await (await this.#c("notes")).aggregate([
6372
+ { $match: {
6373
+ ...live,
6374
+ ...this.#visibleNotes(ids),
6375
+ ...scopes ? { pageScopeId: { $in: ids === null ? scopes : scopes.filter((id) => ids.includes(id)) } } : {},
6376
+ $or: words.map((word) => ({ text: matcher(word) }))
6377
+ } },
6378
+ { $addFields: { searchScore: { $add: words.map((word) => ({ $cond: [
6379
+ has("text", word),
6380
+ 1,
6381
+ 0
6382
+ ] })) } } },
6383
+ { $sort: {
6384
+ searchScore: -1,
6385
+ updatedAt: -1,
6386
+ id: -1
6387
+ } },
6388
+ { $limit: limit - hits.length },
6389
+ { $project: {
6390
+ searchScore: 0,
6391
+ _id: 0
6392
+ } }
6393
+ ]).toArray();
6394
+ const notePages = new Map((await pages.find({
6395
+ id: { $in: [...new Set(noteRows.map((row) => String(row.pageId)))] },
6396
+ ...live
6397
+ }, noProjection).toArray()).map((row) => [String(row.id), toPage(row)]));
6398
+ for (const row of noteRows) {
6399
+ const page = notePages.get(String(row.pageId));
6400
+ if (page) hits.push({
6401
+ type: "note",
6402
+ note: toNote(row),
6403
+ page
6404
+ });
5300
6405
  }
5301
- return results.slice(0, limit);
6406
+ return hits;
5302
6407
  }
5303
- /**
5304
- * @deprecated Curation cursors were removed. Observation-time curate is the only Knowledge writer and needs no
5305
- * cursor. Always throws.
5306
- */
5307
- async getCurationCursor(_input) {
5308
- throw new Error(KNOWLEDGE_CURATION_CURSOR_REMOVED_MESSAGE);
5309
- }
5310
- /**
5311
- * @deprecated Curation cursors were removed. Observation-time curate is the only Knowledge writer and needs no
5312
- * cursor. Always throws.
5313
- */
5314
- async advanceCurationCursor(_input) {
5315
- throw new Error(KNOWLEDGE_CURATION_CURSOR_REMOVED_MESSAGE);
5316
- }
5317
- async listActivity(input) {
5318
- const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
5319
- return (await (await this.#activityCollection()).find({
5320
- scopeKey: { $in: visibleScopeKeys(scope) },
5321
- ...input.after ? { id: { $lt: input.after } } : {}
5322
- }).sort({ id: -1 }).limit(input.limit ?? 100).toArray()).map((row) => ({
5323
- id: row.id,
5324
- action: row.action,
5325
- recordType: row.recordType,
5326
- recordId: row.recordId,
5327
- scope: cloneScope(row.scope),
5328
- sourceThreadId: row.sourceThreadId ?? void 0,
6408
+ async listPageActivity(input) {
6409
+ const core = await loadPagesCore();
6410
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
6411
+ const ids = await this.#readable(input.read);
6412
+ const activity = await this.#c("activity");
6413
+ const notes = await this.#c("notes");
6414
+ const filter = {};
6415
+ if (ids !== null) filter.pageScopeId = { $in: ids };
6416
+ delete filter.scopeId;
6417
+ if (input.scopeId) {
6418
+ if (ids !== null && !ids.includes(input.scopeId)) filter.pageScopeId = { $in: [] };
6419
+ else filter.pageScopeId = input.scopeId;
6420
+ }
6421
+ if (input.pageId) filter.pageId = input.pageId;
6422
+ if (input.cursor) {
6423
+ const [createdAt, id] = decodeCursor(input.cursor);
6424
+ const at = new Date(createdAt);
6425
+ filter.$or = [{ createdAt: { $lt: at } }, {
6426
+ createdAt: at,
6427
+ id: { $lt: id }
6428
+ }];
6429
+ }
6430
+ const events = [];
6431
+ let cursorFilter = filter;
6432
+ for (;;) {
6433
+ const batch = await activity.find(cursorFilter, noProjection).sort({
6434
+ createdAt: -1,
6435
+ id: -1
6436
+ }).limit(limit * 4 + 1).toArray();
6437
+ const noteIds = [...new Set(batch.flatMap((row) => row.noteId ? [String(row.noteId)] : []))];
6438
+ const visible = new Set(noteIds.length ? (await notes.find({
6439
+ id: { $in: noteIds },
6440
+ ...this.#visibleNotes(ids)
6441
+ }, { projection: {
6442
+ _id: 0,
6443
+ id: 1
6444
+ } }).toArray()).map((row) => String(row.id)) : []);
6445
+ for (const row of batch) {
6446
+ if (row.noteId && !visible.has(String(row.noteId))) continue;
6447
+ events.push(row);
6448
+ if (events.length > limit) break;
6449
+ }
6450
+ if (events.length > limit || batch.length <= limit * 4) break;
6451
+ const last = batch[batch.length - 1];
6452
+ cursorFilter = {
6453
+ ...filter,
6454
+ $or: [{ createdAt: { $lt: last.createdAt } }, {
6455
+ createdAt: last.createdAt,
6456
+ id: { $lt: last.id }
6457
+ }]
6458
+ };
6459
+ }
6460
+ const page = events.slice(0, limit).map((row) => ({
6461
+ id: String(row.id),
6462
+ action: String(row.action),
6463
+ scopeId: String(row.scopeId),
6464
+ pageId: String(row.pageId),
6465
+ ...row.noteId == null ? {} : { noteId: String(row.noteId) },
6466
+ provenance: row.provenance,
5329
6467
  createdAt: new Date(row.createdAt)
5330
6468
  }));
5331
- }
5332
- async listSemanticOutbox(input = {}) {
5333
- const filter = {
5334
- ...input.status ? { status: input.status } : {},
5335
- ...input.scope ? { scopeKey: { $in: visibleScopeKeys(input.scope) } } : {}
6469
+ const last = page[page.length - 1];
6470
+ return {
6471
+ events: page,
6472
+ ...events.length > limit && last ? { nextCursor: encodeCursor([last.createdAt.toISOString(), last.id]) } : {}
5336
6473
  };
5337
- return (await (await this.#outboxCollection()).find(filter).sort({
5338
- createdAt: 1,
5339
- id: 1
5340
- }).limit(input.limit ?? 100).toArray()).map(outboxFromDocument);
5341
6474
  }
5342
- async claimSemanticOutbox(input) {
5343
- return this.#connector.withTransaction(async (session) => {
5344
- const collection = await this.#outboxCollection();
5345
- const now = input.now ?? /* @__PURE__ */ new Date();
5346
- const staleBefore = new Date(now.getTime() - (input.claimTimeoutMs ?? 6e4));
5347
- const filter = {
5348
- $or: [{
5349
- status: "pending",
5350
- availableAt: { $lte: now }
5351
- }, {
5352
- status: "processing",
5353
- claimedAt: { $lte: staleBefore }
5354
- }],
5355
- ...input.scope ? { scopeKey: { $in: visibleScopeKeys(input.scope) } } : {}
6475
+ /** Deletes every document but keeps the collections, indexes and schema-version marker. */
6476
+ async clearAll() {
6477
+ await this.#tx(async (session) => {
6478
+ for (const name of [
6479
+ "activity",
6480
+ "pins",
6481
+ "notes",
6482
+ "pages"
6483
+ ]) await (await this.#c(name)).deleteMany({}, { session });
6484
+ });
6485
+ }
6486
+ async addPinAudience(input) {
6487
+ return this.#tx(async (session) => {
6488
+ const page = await this.#requireLivePage(input.pageId, session);
6489
+ const now = /* @__PURE__ */ new Date();
6490
+ const { pin, changed } = await this.#upsertPinAudience(session, page.id, input.audience, input.createdBy, now);
6491
+ if (changed) await this.#log(session, {
6492
+ action: "pin-added",
6493
+ scopeId: page.scopeId,
6494
+ pageId: page.id,
6495
+ provenance: { author: input.createdBy },
6496
+ at: now
6497
+ });
6498
+ return pin;
6499
+ });
6500
+ }
6501
+ async #upsertPinAudience(session, pageId, audience, createdBy, now) {
6502
+ const pins = await this.#c("pins");
6503
+ const existing = await pins.findOne({ pageId }, {
6504
+ ...noProjection,
6505
+ session
6506
+ });
6507
+ if (!existing) {
6508
+ const doc = {
6509
+ id: (0, _mastra_core_storage.createKnowledgeUlid)(),
6510
+ pageId,
6511
+ audience: [...new Set(audience)],
6512
+ createdBy,
6513
+ createdAt: now,
6514
+ updatedAt: now
5356
6515
  };
5357
- const limit = input.limit ?? 100;
5358
- const candidates = await collection.find(filter, sessionOptions(session)).sort({
5359
- createdAt: 1,
6516
+ try {
6517
+ await pins.insertOne({ ...doc }, { session });
6518
+ } catch (error) {
6519
+ if (isDuplicateKey(error)) throw new _mastra_core_storage.KnowledgeConflictError(pageId);
6520
+ throw error;
6521
+ }
6522
+ return {
6523
+ pin: toPin(doc),
6524
+ changed: true
6525
+ };
6526
+ }
6527
+ const current = existing.audience ?? [];
6528
+ const merged = [.../* @__PURE__ */ new Set([...current, ...audience])];
6529
+ if (merged.length === current.length) return {
6530
+ pin: toPin(existing),
6531
+ changed: false
6532
+ };
6533
+ return {
6534
+ pin: toPin(await pins.findOneAndUpdate({ id: existing.id }, { $set: {
6535
+ audience: merged,
6536
+ updatedAt: now
6537
+ } }, {
6538
+ returnDocument: "after",
6539
+ projection: { _id: 0 },
6540
+ session
6541
+ })),
6542
+ changed: true
6543
+ };
6544
+ }
6545
+ async removePinAudience(input) {
6546
+ return this.#tx(async (session) => {
6547
+ const pins = await this.#c("pins");
6548
+ const existing = await pins.findOne({ pageId: input.pageId }, {
6549
+ ...noProjection,
6550
+ session
6551
+ });
6552
+ if (!existing) return null;
6553
+ const current = existing.audience ?? [];
6554
+ const remaining = current.filter((entry) => !input.audience.includes(entry));
6555
+ if (remaining.length === current.length) return toPin(existing);
6556
+ const now = /* @__PURE__ */ new Date();
6557
+ let pin = null;
6558
+ if (remaining.length === 0) await pins.deleteOne({ id: existing.id }, { session });
6559
+ else pin = toPin(await pins.findOneAndUpdate({ id: existing.id }, { $set: {
6560
+ audience: remaining,
6561
+ updatedAt: now
6562
+ } }, {
6563
+ returnDocument: "after",
6564
+ projection: { _id: 0 },
6565
+ session
6566
+ }));
6567
+ const page = await this.#page(input.pageId, session);
6568
+ await this.#log(session, {
6569
+ action: "pin-removed",
6570
+ scopeId: page?.scopeId ?? input.pageId,
6571
+ pageId: input.pageId,
6572
+ provenance: { author: input.removedBy },
6573
+ at: now
6574
+ });
6575
+ return pin;
6576
+ });
6577
+ }
6578
+ async getPages(input) {
6579
+ if (!input.ids.length) return [];
6580
+ const rows = await (await this.#c("pages")).find({
6581
+ id: { $in: [...new Set(input.ids)] },
6582
+ ...live
6583
+ }, noProjection).toArray();
6584
+ if (input.read === "all") return rows.map(toPage);
6585
+ const read = input.read;
6586
+ const scopeIds = [...new Set(rows.map((row) => String(row.scopeId)))];
6587
+ const readable = /* @__PURE__ */ new Set();
6588
+ const any = this.#readableClauses(read);
6589
+ if (scopeIds.length && any.length) {
6590
+ const scopes = await (await this.#c("pages")).find({
6591
+ id: { $in: scopeIds },
6592
+ isScope: true,
6593
+ $or: any
6594
+ }, { projection: {
6595
+ _id: 0,
5360
6596
  id: 1
5361
- }).limit(Math.max(limit * 10, 100)).toArray();
5362
- const claimed = [];
5363
- for (const candidate of candidates) {
5364
- if (claimed.length >= limit) break;
5365
- if (await collection.findOne({
5366
- documentId: candidate.documentId,
5367
- status: { $ne: "completed" },
5368
- $or: [{ createdAt: { $lt: candidate.createdAt } }, {
5369
- createdAt: candidate.createdAt,
5370
- id: { $lt: candidate.id }
5371
- }]
5372
- }, sessionOptions(session))) continue;
5373
- const result = await collection.findOneAndUpdate({
5374
- id: candidate.id,
5375
- $or: [{
5376
- status: "pending",
5377
- availableAt: { $lte: now }
5378
- }, {
5379
- status: "processing",
5380
- claimedAt: { $lte: staleBefore }
5381
- }]
5382
- }, {
5383
- $set: {
5384
- status: "processing",
5385
- claimedAt: now,
5386
- claimedBy: input.workerId
5387
- },
5388
- $inc: { attempts: 1 }
5389
- }, {
5390
- ...sessionOptions(session),
5391
- returnDocument: "after"
5392
- });
5393
- if (result) claimed.push(result);
6597
+ } }).toArray();
6598
+ for (const scope of scopes) readable.add(String(scope.id));
6599
+ }
6600
+ return rows.filter((row) => readable.has(String(row.scopeId))).map(toPage);
6601
+ }
6602
+ async listPins(input) {
6603
+ const core = await loadPagesCore();
6604
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
6605
+ const ids = await this.#readable(input.read);
6606
+ const match = {};
6607
+ if (input.audience !== "all") match.audience = { $in: input.audience };
6608
+ const pageId = {};
6609
+ if (input.pageIds) pageId.$in = input.pageIds;
6610
+ if (input.excludePageIds?.length) pageId.$nin = input.excludePageIds;
6611
+ if (Object.keys(pageId).length) match.pageId = pageId;
6612
+ const pins = await this.#c("pins");
6613
+ const base = [
6614
+ { $match: match },
6615
+ { $lookup: {
6616
+ from: MONGO_KNOWLEDGE_PAGES_COLLECTIONS.pages,
6617
+ localField: "pageId",
6618
+ foreignField: "id",
6619
+ as: "page"
6620
+ } },
6621
+ { $match: {
6622
+ "page.deletedAt": { $exists: false },
6623
+ ...ids === null ? {} : { "page.scopeId": { $in: ids } },
6624
+ ...input.withBody ? { "page.body": { $regex: "\\S" } } : {}
6625
+ } }
6626
+ ];
6627
+ const pageMatch = [];
6628
+ if (input.cursor) {
6629
+ const [createdAt, id] = decodeCursor(input.cursor);
6630
+ const at = new Date(createdAt);
6631
+ pageMatch.push({ $match: { $or: [{ createdAt: { $lt: at } }, {
6632
+ createdAt: at,
6633
+ id: { $lt: id }
6634
+ }] } });
6635
+ }
6636
+ const rows = await pins.aggregate([
6637
+ ...base,
6638
+ ...pageMatch,
6639
+ { $addFields: { pageName: { $arrayElemAt: ["$page.name", 0] } } },
6640
+ { $project: {
6641
+ _id: 0,
6642
+ page: 0
6643
+ } },
6644
+ { $sort: {
6645
+ createdAt: -1,
6646
+ id: -1
6647
+ } },
6648
+ { $limit: limit + 1 }
6649
+ ]).toArray();
6650
+ let total;
6651
+ if (input.count) {
6652
+ const counted = await pins.aggregate([...base, { $count: "total" }]).toArray();
6653
+ total = Number(counted[0]?.total ?? 0);
6654
+ }
6655
+ const listed = rows.slice(0, limit).map(toListedPin);
6656
+ const last = listed[listed.length - 1];
6657
+ return {
6658
+ pins: listed,
6659
+ ...rows.length > limit && last ? { nextCursor: encodeCursor([last.createdAt.toISOString(), last.id]) } : {},
6660
+ ...total === void 0 ? {} : { total }
6661
+ };
6662
+ }
6663
+ };
6664
+ // src/storage/domains/knowledge/index.ts
6665
+ const loadKnowledgePagesCore = createKnowledgePagesCoreLoader(_mastra_core_features.coreFeatures, () => import("@mastra/core/storage"));
6666
+ /** @experimental Knowledge APIs are experimental and may change without notice. */
6667
+ var KnowledgeMongoDB = class extends _mastra_core_storage.KnowledgeStorage {
6668
+ static MANAGED_COLLECTIONS = Object.values(MONGO_KNOWLEDGE_PAGES_COLLECTIONS);
6669
+ #connector;
6670
+ #pages;
6671
+ constructor(config) {
6672
+ super();
6673
+ this.#connector = resolveMongoDBConfig(config);
6674
+ this.#pages = new MongoKnowledgePages({
6675
+ connector: this.#connector,
6676
+ bounds: async () => {
6677
+ const core = await loadKnowledgePagesCore();
6678
+ return {
6679
+ assertKnowledgePageDescriptionWithinBound: core.assertKnowledgePageDescriptionWithinBound,
6680
+ assertKnowledgeNoteTextWithinBound: core.assertKnowledgeNoteTextWithinBound
6681
+ };
5394
6682
  }
5395
- return claimed.map(outboxFromDocument);
5396
6683
  });
5397
6684
  }
5398
- async completeSemanticOutbox(input) {
5399
- if (!input.ids.length) return;
5400
- await (await this.#outboxCollection()).updateMany({
5401
- id: { $in: input.ids },
5402
- status: "processing",
5403
- claimedBy: input.workerId
5404
- }, { $set: {
5405
- status: "completed",
5406
- completedAt: /* @__PURE__ */ new Date(),
5407
- claimedAt: null,
5408
- claimedBy: null
5409
- } });
6685
+ getCapabilities() {
6686
+ return {
6687
+ ...super.getCapabilities(),
6688
+ schemaVersion: 4,
6689
+ supportsSchemaInspection: true,
6690
+ supportsExplicitReset: true
6691
+ };
5410
6692
  }
5411
- async releaseSemanticOutbox(input) {
5412
- if (!input.ids.length) return;
5413
- await (await this.#outboxCollection()).updateMany({
5414
- id: { $in: input.ids },
5415
- status: "processing",
5416
- claimedBy: input.workerId
5417
- }, { $set: {
5418
- status: "pending",
5419
- availableAt: input.retryAt ?? /* @__PURE__ */ new Date(),
5420
- claimedAt: null,
5421
- claimedBy: null
5422
- } });
6693
+ async init() {
6694
+ await this.#pages.init();
5423
6695
  }
5424
- async #collection(name) {
5425
- return this.#connector.getCollection(name);
6696
+ async inspectSchema() {
6697
+ return this.#pages.inspectSchema();
5426
6698
  }
5427
- #nodes() {
5428
- return this.#collection(_mastra_core_storage.TABLE_KNOWLEDGE_NODES);
6699
+ async dangerouslyReset() {
6700
+ await this.#pages.reset();
5429
6701
  }
5430
- #knowledge() {
5431
- return this.#collection(_mastra_core_storage.TABLE_KNOWLEDGE_RECORDS);
6702
+ async dangerouslyClearAll() {
6703
+ await this.#pages.clearAll();
5432
6704
  }
5433
- #mentions() {
5434
- return this.#collection(_mastra_core_storage.TABLE_KNOWLEDGE_MENTIONS);
6705
+ materializeScope(input) {
6706
+ return this.#pages.materializeScope(input);
5435
6707
  }
5436
- #activityCollection() {
5437
- return this.#collection(_mastra_core_storage.TABLE_KNOWLEDGE_ACTIVITY);
6708
+ getScopesByAddress(input) {
6709
+ return this.#pages.getScopesByAddress(input);
5438
6710
  }
5439
- #outboxCollection() {
5440
- return this.#collection(_mastra_core_storage.TABLE_KNOWLEDGE_SEMANTIC_OUTBOX);
6711
+ listScopeDeclarations() {
6712
+ return this.#pages.listScopeDeclarations();
5441
6713
  }
5442
- async #getNode(id, session) {
5443
- const row = await (await this.#nodes()).findOne({
5444
- id,
5445
- type: "node"
5446
- }, sessionOptions(session));
5447
- return row ? nodeFromDocument(row) : null;
5448
- }
5449
- async #getNodeByName(name, scope, session) {
5450
- const row = await (await this.#nodes()).findOne({
5451
- type: "node",
5452
- scopeKey: (0, _mastra_core_storage.knowledgeScopeKey)(scope),
5453
- canonicalName: canonicalName(name)
5454
- }, sessionOptions(session));
5455
- return row ? nodeFromDocument(row) : null;
5456
- }
5457
- async #resolveNode(name, scope, session) {
5458
- const candidates = (await (await this.#nodes()).find({
5459
- type: "node",
5460
- canonicalName: canonicalName(name),
5461
- $or: [{ scopeKey: { $in: visibleScopeKeys(scope) } }, { mergedInto: { $ne: null } }]
5462
- }, sessionOptions(session)).toArray()).map(nodeFromDocument).sort((left, right) => right.scope.length - left.scope.length);
5463
- for (const candidate of candidates) {
5464
- const terminal = await this.#resolveTerminalNode(candidate.id, session);
5465
- if (terminal && (0, _mastra_core_storage.isKnowledgeScopeVisible)(terminal.scope, scope)) return terminal;
5466
- }
5467
- return null;
5468
- }
5469
- async #resolveTerminalNode(id, session) {
5470
- let node = await this.#getNode(id, session);
5471
- const seen = /* @__PURE__ */ new Set();
5472
- while (node?.mergedInto) {
5473
- if (seen.has(node.id)) throw new Error(`Knowledge merge cycle detected at ${node.id}`);
5474
- seen.add(node.id);
5475
- node = await this.#getNode(node.mergedInto, session);
5476
- }
5477
- return node;
6714
+ renameScopeDeclaration(input) {
6715
+ return this.#pages.renameScopeDeclaration(input);
5478
6716
  }
5479
- async #getPageByExactName(name, scope, session) {
5480
- const row = await (await this.#nodes()).findOne({
5481
- type: "page",
5482
- scopeKey: (0, _mastra_core_storage.knowledgeScopeKey)(scope),
5483
- canonicalName: canonicalName(name)
5484
- }, sessionOptions(session));
5485
- return row ? nodeFromDocument(row) : null;
6717
+ listChildScopes(input) {
6718
+ return this.#pages.listChildScopes(input);
5486
6719
  }
5487
- async #getKnowledge(id, includeDeleted, session) {
5488
- const row = await (await this.#knowledge()).findOne({
5489
- id,
5490
- ...includeDeleted ? {} : { deletedAt: null }
5491
- }, sessionOptions(session));
5492
- return row ? recordFromDocument(row) : null;
5493
- }
5494
- async #queryKnowledge(input, relationship) {
5495
- const scope = (0, _mastra_core_storage.canonicalizeKnowledgeScope)(input.scope);
5496
- const node = await this.#resolveTerminalNode(nodeReferenceId(input.node));
5497
- if (!node) return { records: [] };
5498
- const nodeIds = [node.id];
5499
- if (relationship !== "about") {
5500
- const mentions = await (await this.#mentions()).find({
5501
- recordId: node.id,
5502
- sourceType: "record"
5503
- }).toArray();
5504
- nodeIds.push(...mentions.map((row) => row.sourceId));
5505
- }
5506
- const limit = input.limit ?? 100;
5507
- const filter = relationship === "about" ? { node: node.id } : relationship === "mentioning" ? { id: { $in: nodeIds.slice(1) } } : { $or: [{ node: node.id }, { id: { $in: nodeIds.slice(1) } }] };
5508
- Object.assign(filter, {
5509
- scopeKey: { $in: visibleScopeKeys(scope) },
5510
- ...input.includeDeleted ? {} : { deletedAt: null },
5511
- ...input.after ? { id: { $lt: input.after } } : {}
5512
- });
5513
- const rows = await (await this.#knowledge()).find(filter).sort({ id: -1 }).limit(limit + 1).toArray();
5514
- return {
5515
- records: rows.slice(0, limit).map(recordFromDocument),
5516
- nextCursor: rows.length > limit ? rows[limit - 1]?.id : void 0
5517
- };
6720
+ getPages(input) {
6721
+ return this.#pages.getPages(input);
5518
6722
  }
5519
- async #replaceMentions(sourceType, sourceId, text, resolutionScope, defaultScope, session) {
5520
- const mentions = await this.#mentions();
5521
- await mentions.deleteMany({
5522
- sourceType,
5523
- sourceId
5524
- }, sessionOptions(session));
5525
- for (const name of (0, _mastra_core_storage.parseKnowledgeWikilinks)(text)) {
5526
- let node = await this.#resolveNode(name, resolutionScope, session);
5527
- if (!node) {
5528
- const existing = await this.#getNodeByName(name, defaultScope, session);
5529
- node = existing ? await this.#resolveTerminalNode(existing.id, session) : null;
5530
- }
5531
- if (!node) {
5532
- const now = /* @__PURE__ */ new Date();
5533
- node = {
5534
- id: crypto.randomUUID(),
5535
- type: "node",
5536
- name,
5537
- kind: "node",
5538
- scope: defaultScope,
5539
- version: 1,
5540
- createdAt: now,
5541
- updatedAt: now
5542
- };
5543
- try {
5544
- await (await this.#nodes()).insertOne({
5545
- ...node,
5546
- canonicalName: canonicalName(name),
5547
- scopeKey: (0, _mastra_core_storage.knowledgeScopeKey)(defaultScope),
5548
- mergedInto: null
5549
- }, sessionOptions(session));
5550
- await this.#activity("node-created", "node", node.id, defaultScope, void 0, session);
5551
- await this.#outbox("node", node.id, "upsert", 1, defaultScope, session);
5552
- } catch (error) {
5553
- if (error.code !== 11e3) throw error;
5554
- node = await this.#getNodeByName(name, defaultScope, session);
5555
- if (!node) throw error;
5556
- }
5557
- }
5558
- await mentions.updateOne({
5559
- sourceType,
5560
- sourceId,
5561
- recordId: node.id
5562
- }, { $setOnInsert: {
5563
- sourceType,
5564
- sourceId,
5565
- recordId: node.id
5566
- } }, {
5567
- ...sessionOptions(session),
5568
- upsert: true
5569
- });
5570
- }
6723
+ getPage(input) {
6724
+ return this.#pages.getPage(input);
5571
6725
  }
5572
- async #activity(action, recordType, recordId, scope, sourceThreadId, session) {
5573
- await (await this.#activityCollection()).insertOne({
5574
- id: (0, _mastra_core_storage.createKnowledgeUlid)(),
5575
- action,
5576
- recordType,
5577
- recordId,
5578
- scope,
5579
- scopeKey: (0, _mastra_core_storage.knowledgeScopeKey)(scope),
5580
- sourceThreadId: sourceThreadId ?? null,
5581
- createdAt: /* @__PURE__ */ new Date()
5582
- }, sessionOptions(session));
5583
- }
5584
- async #outbox(documentType, id, operation, version, scope, session) {
5585
- const documentId = (0, _mastra_core_storage.knowledgeSemanticDocumentId)(documentType, id);
5586
- const idempotencyKey = (0, _mastra_core_storage.knowledgeSemanticIdempotencyKey)(documentId, operation, version);
5587
- const now = /* @__PURE__ */ new Date();
5588
- try {
5589
- await (await this.#outboxCollection()).insertOne({
5590
- id: (0, _mastra_core_storage.createKnowledgeUlid)(),
5591
- idempotencyKey,
5592
- documentId,
5593
- documentType,
5594
- operation,
5595
- scope,
5596
- scopeKey: (0, _mastra_core_storage.knowledgeScopeKey)(scope),
5597
- status: "pending",
5598
- attempts: 0,
5599
- availableAt: now,
5600
- claimedAt: null,
5601
- claimedBy: null,
5602
- createdAt: now,
5603
- completedAt: null
5604
- }, sessionOptions(session));
5605
- } catch (error) {
5606
- if (error.code !== 11e3) throw error;
5607
- }
6726
+ getPageByPath(input) {
6727
+ return this.#pages.getPageByPath(input);
6728
+ }
6729
+ findPagesByName(input) {
6730
+ return this.#pages.findPagesByName(input);
6731
+ }
6732
+ listChildPages(input) {
6733
+ return this.#pages.listChildPages(input);
6734
+ }
6735
+ listPages(input) {
6736
+ return this.#pages.listPages(input);
6737
+ }
6738
+ createPage(input) {
6739
+ return this.#pages.createPage(input);
6740
+ }
6741
+ updatePage(input) {
6742
+ return this.#pages.updatePage(input);
6743
+ }
6744
+ movePage(input) {
6745
+ return this.#pages.movePage(input);
6746
+ }
6747
+ mergePages(input) {
6748
+ return this.#pages.mergePages(input);
6749
+ }
6750
+ deletePage(input) {
6751
+ return this.#pages.deletePage(input);
6752
+ }
6753
+ getNote(input) {
6754
+ return this.#pages.getNote(input);
6755
+ }
6756
+ listNotes(input) {
6757
+ return this.#pages.listNotes(input);
6758
+ }
6759
+ countChildPages(input) {
6760
+ return this.#pages.countChildPages(input);
6761
+ }
6762
+ countNotes(input) {
6763
+ return this.#pages.countNotes(input);
6764
+ }
6765
+ listNotesMentioning(input) {
6766
+ return this.#pages.listNotesMentioning(input);
6767
+ }
6768
+ addNote(input) {
6769
+ return this.#pages.addNote(input);
6770
+ }
6771
+ restampNote(input) {
6772
+ return this.#pages.restampNote(input);
6773
+ }
6774
+ removeNote(input) {
6775
+ return this.#pages.removeNote(input);
6776
+ }
6777
+ restoreNote(input) {
6778
+ return this.#pages.restoreNote(input);
6779
+ }
6780
+ searchPages(input) {
6781
+ return this.#pages.searchPages(input);
6782
+ }
6783
+ listPageActivity(input) {
6784
+ return this.#pages.listPageActivity(input);
6785
+ }
6786
+ addPinAudience(input) {
6787
+ return this.#pages.addPinAudience(input);
6788
+ }
6789
+ removePinAudience(input) {
6790
+ return this.#pages.removePinAudience(input);
5608
6791
  }
5609
- #escapeRegex(value) {
5610
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6792
+ listPins(input) {
6793
+ return this.#pages.listPins(input);
5611
6794
  }
5612
6795
  };
5613
6796
  // src/storage/domains/mcp-clients/index.ts