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