@mastra/mongodb 1.26.0-alpha.0 → 1.26.0-alpha.2

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
@@ -10,7 +10,7 @@ import { MessageList } from "@mastra/core/agent";
10
10
  import { saveScorePayloadSchema } from "@mastra/core/evals";
11
11
  import { skillSnapshotFieldValuesEqual } from "@mastra/core/storage/domains/skills";
12
12
  // package.json
13
- var version = "1.26.0-alpha.0";
13
+ var version = "1.26.0-alpha.2";
14
14
  // src/vector/filter.ts
15
15
  /**
16
16
  * Translator for MongoDB filter queries.
@@ -1729,6 +1729,7 @@ const SNAPSHOT_FIELDS$6 = [
1729
1729
  "description",
1730
1730
  "instructions",
1731
1731
  "model",
1732
+ "modelList",
1732
1733
  "tools",
1733
1734
  "defaultOptions",
1734
1735
  "workflows",
@@ -4873,7 +4874,8 @@ const KNOWLEDGE_PAGES_CORE_FUNCTIONS = [
4873
4874
  const KNOWLEDGE_PAGES_CORE_NUMBERS = [
4874
4875
  "MAX_KNOWLEDGE_MOVE_PAGES",
4875
4876
  "MAX_KNOWLEDGE_PAGE_DEPTH",
4876
- "MAX_KNOWLEDGE_PAGE_LIST_LIMIT"
4877
+ "MAX_KNOWLEDGE_PAGE_LIST_LIMIT",
4878
+ "MAX_KNOWLEDGE_PAGE_LINKS"
4877
4879
  ];
4878
4880
  function resolveKnowledgePagesCore(storageModule) {
4879
4881
  const module = typeof storageModule === "object" && storageModule !== null ? storageModule : {};
@@ -4894,13 +4896,25 @@ function createKnowledgePagesCoreLoader(features, loadStorageModule) {
4894
4896
  };
4895
4897
  }
4896
4898
  /**
4897
- * Keyword-search words: the query split on whitespace, lowercased, deduplicated. Every word must
4898
- * appear (as a case-insensitive substring) in a hit; an empty list means the search returns nothing.
4899
+ * Keyword-search words: the query split on whitespace, lowercased, deduplicated, keeping the first
4900
+ * {@link KNOWLEDGE_SEARCH_MAX_WORDS}. A hit needs at least one of them (as a case-insensitive
4901
+ * substring); an empty list means the search returns nothing.
4899
4902
  */
4900
4903
  function knowledgeSearchWords(query) {
4901
- return [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))];
4904
+ return [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))].slice(0, 16);
4902
4905
  }
4903
4906
  /**
4907
+ * Points one matched search word earns on a page, by the best field it appears in: name, then
4908
+ * description, then body. A page whose name contains the whole query ranks first; below that, pages
4909
+ * rank by how many query words they match, and these points only break ties between pages that
4910
+ * match the same number of words.
4911
+ */
4912
+ const KNOWLEDGE_SEARCH_WEIGHTS = {
4913
+ name: 3,
4914
+ description: 2,
4915
+ body: 1
4916
+ };
4917
+ /**
4904
4918
  * Why `key` can't be a Knowledge page key, or undefined when it can. Keys are one path segment:
4905
4919
  * non-empty, with no `/` (path separator), `#` (scope/path separator) or `%` (escape character).
4906
4920
  */
@@ -4912,11 +4926,13 @@ function knowledgePageKeyProblem(key) {
4912
4926
  const loadPagesCore = createKnowledgePagesCoreLoader(coreFeatures, () => import("@mastra/core/storage"));
4913
4927
  const DEFAULT_LIST_LIMIT = 50;
4914
4928
  const MONGO_DUPLICATE_KEY = 11e3;
4929
+ const DEFAULT_LINK_LIMIT = 1e3;
4915
4930
  const MONGO_KNOWLEDGE_PAGES_COLLECTIONS = {
4916
4931
  pages: "mastra_knowledge_pages",
4917
4932
  notes: "mastra_knowledge_notes",
4918
4933
  pins: "mastra_knowledge_pins",
4919
4934
  activity: "mastra_knowledge_activity",
4935
+ links: "mastra_knowledge_page_links",
4920
4936
  state: "mastra_knowledge_access_state"
4921
4937
  };
4922
4938
  /** Thrown when existing Knowledge collections can't be used as schema 4 without a reset. */
@@ -5012,10 +5028,17 @@ function toListedPin(row) {
5012
5028
  pageName: String(row.pageName)
5013
5029
  };
5014
5030
  }
5031
+ /** IndexNotFound, or NamespaceNotFound when the collection doesn't exist yet. */
5032
+ function isMissingIndex(error) {
5033
+ const code = error?.code;
5034
+ return code === 27 || code === 26;
5035
+ }
5015
5036
  function toPin(row) {
5016
5037
  return {
5017
5038
  id: String(row.id),
5018
5039
  pageId: String(row.pageId),
5040
+ kind: row.kind ?? "page",
5041
+ ...row.depth == null ? {} : { depth: Number(row.depth) },
5019
5042
  audience: [...row.audience ?? []],
5020
5043
  createdBy: String(row.createdBy),
5021
5044
  createdAt: new Date(row.createdAt),
@@ -5078,12 +5101,17 @@ var MongoKnowledgePages = class {
5078
5101
  } }, { upsert: true });
5079
5102
  const inspection = await this.inspectSchema();
5080
5103
  if (inspection.status === "incompatible-reset-required") throw new MongoKnowledgeResetRequiredError(inspection);
5081
- const [pages, notes, pins, activity] = await Promise.all([
5104
+ const [pages, notes, pins, activity, links] = await Promise.all([
5082
5105
  this.#c("pages"),
5083
5106
  this.#c("notes"),
5084
5107
  this.#c("pins"),
5085
- this.#c("activity")
5108
+ this.#c("activity"),
5109
+ this.#c("links")
5086
5110
  ]);
5111
+ await pins.updateMany({ kind: { $exists: false } }, { $set: { kind: "page" } });
5112
+ await pins.dropIndex("pageId_1").catch((error) => {
5113
+ if (!isMissingIndex(error)) throw error;
5114
+ });
5087
5115
  await Promise.all([
5088
5116
  pages.createIndex({ id: 1 }, { unique: true }),
5089
5117
  pages.createIndex({ address: 1 }, {
@@ -5123,7 +5151,10 @@ var MongoKnowledgePages = class {
5123
5151
  notes.createIndex({ pageScopeId: 1 }),
5124
5152
  notes.createIndex({ stampScopeIds: 1 }),
5125
5153
  pins.createIndex({ id: 1 }, { unique: true }),
5126
- pins.createIndex({ pageId: 1 }, { unique: true }),
5154
+ pins.createIndex({
5155
+ pageId: 1,
5156
+ kind: 1
5157
+ }, { unique: true }),
5127
5158
  pins.createIndex({ audience: 1 }),
5128
5159
  activity.createIndex({ id: 1 }, { unique: true }),
5129
5160
  activity.createIndex({
@@ -5135,12 +5166,19 @@ var MongoKnowledgePages = class {
5135
5166
  pageId: 1,
5136
5167
  createdAt: -1,
5137
5168
  id: -1
5138
- })
5169
+ }),
5170
+ links.createIndex({
5171
+ fromPageId: 1,
5172
+ ref: 1
5173
+ }, { unique: true }),
5174
+ links.createIndex({ toPageId: 1 }),
5175
+ links.createIndex({ ref: 1 })
5139
5176
  ]);
5140
5177
  }
5141
5178
  /** Drops exactly the Knowledge collections (never Memory's) and recreates schema 4. */
5142
5179
  async reset() {
5143
5180
  for (const name of KNOWLEDGE_RESETTABLE_TABLE_NAMES) await this.#drop(name);
5181
+ await this.#drop(MONGO_KNOWLEDGE_PAGES_COLLECTIONS.links);
5144
5182
  await this.init();
5145
5183
  }
5146
5184
  /** The ids of every scope page the read scope can see; `null` means everything. */
@@ -5533,10 +5571,12 @@ var MongoKnowledgePages = class {
5533
5571
  async listChildScopes(input) {
5534
5572
  const core = await loadPagesCore();
5535
5573
  const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
5574
+ const readable = input.read ? await this.#readable(input.read) : null;
5536
5575
  const filter = {
5537
5576
  isScope: true,
5538
5577
  parentId: input.parentId,
5539
- ...live
5578
+ ...live,
5579
+ ...this.#inScopes("id", readable)
5540
5580
  };
5541
5581
  if (input.cursor) {
5542
5582
  const [position, id] = decodeCursor(input.cursor);
@@ -5918,12 +5958,20 @@ var MongoKnowledgePages = class {
5918
5958
  } }] } } }], { session });
5919
5959
  await this.#refreshMentionScopes([target.id, ...tree.ids], session);
5920
5960
  const pins = await this.#c("pins");
5921
- const sourcePin = await pins.findOne({ pageId: source.id }, {
5961
+ const sourcePins = await pins.find({ pageId: source.id }, {
5922
5962
  ...noProjection,
5923
5963
  session
5924
- });
5925
- if (sourcePin) {
5926
- await this.#upsertPinAudience(session, target.id, sourcePin.audience ?? [], String(sourcePin.createdBy), now);
5964
+ }).sort({ kind: 1 }).toArray();
5965
+ for (const sourcePin of sourcePins) {
5966
+ await this.#upsertPinAudience(session, {
5967
+ pageId: target.id,
5968
+ kind: sourcePin.kind ?? "page",
5969
+ depth: sourcePin.depth == null ? null : Number(sourcePin.depth),
5970
+ audience: sourcePin.audience ?? [],
5971
+ createdBy: String(sourcePin.createdBy),
5972
+ now,
5973
+ keepDepth: true
5974
+ });
5927
5975
  await pins.deleteOne({ id: sourcePin.id }, { session });
5928
5976
  }
5929
5977
  await (await this.#c("activity")).updateMany({ pageId: source.id }, { $set: { pageScopeId: target.scopeId } }, { session });
@@ -6016,6 +6064,151 @@ var MongoKnowledgePages = class {
6016
6064
  }).limit(limit + 1).toArray();
6017
6065
  return this.#noteOutput(rows, limit);
6018
6066
  }
6067
+ async countChildScopes(input) {
6068
+ const ids = [...new Set(input.parentIds)];
6069
+ const counts = Object.fromEntries(ids.map((id) => [id, 0]));
6070
+ if (!ids.length) return counts;
6071
+ const readable = await this.#readable(input.read);
6072
+ const rows = await (await this.#c("pages")).aggregate([{ $match: {
6073
+ parentId: { $in: ids },
6074
+ isScope: true,
6075
+ ...live,
6076
+ ...this.#inScopes("id", readable)
6077
+ } }, { $group: {
6078
+ _id: "$parentId",
6079
+ count: { $sum: 1 }
6080
+ } }]).toArray();
6081
+ for (const row of rows) counts[row._id] = row.count;
6082
+ return counts;
6083
+ }
6084
+ async countChildPages(input) {
6085
+ const ids = [...new Set(input.parentIds)];
6086
+ const counts = Object.fromEntries(ids.map((id) => [id, 0]));
6087
+ if (!ids.length) return counts;
6088
+ const readable = await this.#readable(input.read);
6089
+ const rows = await (await this.#c("pages")).aggregate([{ $match: {
6090
+ parentId: { $in: ids },
6091
+ ...notScope,
6092
+ ...live,
6093
+ ...this.#inScopes("scopeId", readable)
6094
+ } }, { $group: {
6095
+ _id: "$parentId",
6096
+ count: { $sum: 1 }
6097
+ } }]).toArray();
6098
+ for (const row of rows) counts[row._id] = row.count;
6099
+ return counts;
6100
+ }
6101
+ async replacePageBodyLinks(input) {
6102
+ await this.#tx(async (session) => {
6103
+ const links = await this.#c("links");
6104
+ await links.deleteMany({ fromPageId: input.pageId }, { session });
6105
+ if (!input.links.length) return;
6106
+ await links.insertMany(input.links.map((link) => ({
6107
+ fromPageId: input.pageId,
6108
+ ref: link.ref,
6109
+ toPageId: link.toPageId,
6110
+ count: link.count
6111
+ })), { session });
6112
+ });
6113
+ }
6114
+ async listPageBodyLinkSources(input) {
6115
+ const any = [];
6116
+ if (input.refs?.length) any.push({
6117
+ toPageId: null,
6118
+ ref: { $in: input.refs }
6119
+ });
6120
+ if (input.toPageIds?.length) any.push({ toPageId: { $in: input.toPageIds } });
6121
+ if (!any.length) return [];
6122
+ return (await (await this.#c("links")).distinct("fromPageId", { $or: any })).map(String);
6123
+ }
6124
+ /** Resolved links touching `pageIds`, both ends live and readable, notes only through visible notes. */
6125
+ async #visibleLinks(pageIds, read, direction, kinds) {
6126
+ const ids = [...new Set(pageIds)];
6127
+ if (!ids.length) return [];
6128
+ const wanted = new Set(kinds ?? ["body", "note"]);
6129
+ const touching = (from, to) => direction !== "in" && ids.includes(from) || direction !== "out" && !!to && ids.includes(to);
6130
+ const readable = await this.#readable(read);
6131
+ const raw = /* @__PURE__ */ new Map();
6132
+ const add = (fromPageId, toPageId, kind, count) => {
6133
+ if (fromPageId === toPageId) return;
6134
+ const key = `${fromPageId}\u0000${toPageId}\u0000${kind}`;
6135
+ const edge = raw.get(key);
6136
+ if (edge) edge.count += count;
6137
+ else raw.set(key, {
6138
+ fromPageId,
6139
+ toPageId,
6140
+ kind,
6141
+ count
6142
+ });
6143
+ };
6144
+ const side = [];
6145
+ if (direction !== "in") side.push({ fromPageId: { $in: ids } });
6146
+ if (direction !== "out") side.push({ toPageId: { $in: ids } });
6147
+ if (wanted.has("body")) {
6148
+ const rows = await (await this.#c("links")).find({
6149
+ toPageId: { $ne: null },
6150
+ $or: side
6151
+ }, { projection: {
6152
+ _id: 0,
6153
+ fromPageId: 1,
6154
+ toPageId: 1,
6155
+ count: 1
6156
+ } }).toArray();
6157
+ for (const row of rows) if (touching(String(row.fromPageId), String(row.toPageId))) add(String(row.fromPageId), String(row.toPageId), "body", Number(row.count));
6158
+ }
6159
+ if (wanted.has("note")) {
6160
+ const noteSide = [];
6161
+ if (direction !== "in") noteSide.push({ pageId: { $in: ids } });
6162
+ if (direction !== "out") noteSide.push({ mentions: { $in: ids } });
6163
+ const rows = await (await this.#c("notes")).find({
6164
+ ...live,
6165
+ ...this.#visibleNotes(readable),
6166
+ mentions: {
6167
+ $exists: true,
6168
+ $ne: []
6169
+ },
6170
+ $or: noteSide
6171
+ }, { projection: {
6172
+ _id: 0,
6173
+ pageId: 1,
6174
+ mentions: 1
6175
+ } }).toArray();
6176
+ for (const row of rows) for (const mentioned of new Set(row.mentions ?? [])) if (touching(String(row.pageId), mentioned)) add(String(row.pageId), mentioned, "note", 1);
6177
+ }
6178
+ if (!raw.size) return [];
6179
+ const ends = [...new Set([...raw.values()].flatMap((edge) => [edge.fromPageId, edge.toPageId]))];
6180
+ const visible = new Set((await (await this.#c("pages")).find({
6181
+ id: { $in: ends },
6182
+ ...live,
6183
+ ...this.#inScopes("scopeId", readable)
6184
+ }, { projection: {
6185
+ _id: 0,
6186
+ id: 1
6187
+ } }).toArray()).map((row) => String(row.id)));
6188
+ return [...raw.values()].filter((edge) => visible.has(edge.fromPageId) && visible.has(edge.toPageId));
6189
+ }
6190
+ async countPageLinks(input) {
6191
+ const linked = new Map(input.pageIds.map((id) => [id, {
6192
+ in: /* @__PURE__ */ new Set(),
6193
+ out: /* @__PURE__ */ new Set()
6194
+ }]));
6195
+ for (const edge of await this.#visibleLinks(input.pageIds, input.read, "both", input.kinds)) {
6196
+ linked.get(edge.fromPageId)?.out.add(edge.toPageId);
6197
+ linked.get(edge.toPageId)?.in.add(edge.fromPageId);
6198
+ }
6199
+ return Object.fromEntries([...linked].map(([id, sets]) => [id, {
6200
+ in: sets.in.size,
6201
+ out: sets.out.size
6202
+ }]));
6203
+ }
6204
+ async listPageLinks(input) {
6205
+ const limit = input.limit ?? DEFAULT_LINK_LIMIT;
6206
+ if (!Number.isInteger(limit) || limit < 1) throw new RangeError("Knowledge link limit must be a positive integer");
6207
+ const core = await loadPagesCore();
6208
+ const kindOrder = (kind) => kind === "body" ? 0 : 1;
6209
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
6210
+ return (await this.#visibleLinks(input.pageIds, input.read, input.direction ?? "both", input.kinds)).sort((a, b) => compare(a.fromPageId, b.fromPageId) || compare(a.toPageId, b.toPageId) || kindOrder(a.kind) - kindOrder(b.kind)).slice(0, Math.min(limit, core.MAX_KNOWLEDGE_PAGE_LINKS));
6211
+ }
6019
6212
  async countNotes(input) {
6020
6213
  const ids = [...new Set(input.pageIds)];
6021
6214
  const counts = Object.fromEntries(ids.map((id) => [id, 0]));
@@ -6196,7 +6389,7 @@ var MongoKnowledgePages = class {
6196
6389
  async removeNote(input) {
6197
6390
  return this.#tx(async (session) => {
6198
6391
  const note = await this.#requireNote(input.id, session);
6199
- if (note.deletedAt) return toNote(note);
6392
+ if (note.deletedAt) throw new KnowledgeNotFoundError("note", input.id);
6200
6393
  const now = /* @__PURE__ */ new Date();
6201
6394
  const updated = await (await this.#c("notes")).findOneAndUpdate({ id: input.id }, {
6202
6395
  $set: {
@@ -6271,38 +6464,67 @@ var MongoKnowledgePages = class {
6271
6464
  ...live,
6272
6465
  ...notScope,
6273
6466
  ...inScope("scopeId"),
6274
- $and: words.map((word) => ({ $or: [
6467
+ $or: words.flatMap((word) => [
6275
6468
  { name: matcher(word) },
6276
6469
  { description: matcher(word) },
6277
6470
  { body: matcher(word) }
6278
- ] }))
6471
+ ])
6279
6472
  };
6473
+ const has = (field, word) => ({ $regexMatch: {
6474
+ input: { $ifNull: [`$${field}`, ""] },
6475
+ regex: escapeRegex(word),
6476
+ options: "i"
6477
+ } });
6280
6478
  const hits = (await pages.aggregate([
6281
6479
  { $match: pageFilter },
6282
- { $addFields: { searchTier: { $cond: [
6283
- { $regexMatch: {
6284
- input: "$canonicalName",
6285
- regex: escapeRegex(phrase)
6286
- } },
6287
- 0,
6288
- { $cond: [
6289
- { $and: words.map((word) => ({ $regexMatch: {
6290
- input: "$name",
6291
- regex: escapeRegex(word),
6292
- options: "i"
6293
- } })) },
6480
+ { $addFields: {
6481
+ searchTier: { $cond: [
6482
+ { $regexMatch: {
6483
+ input: "$canonicalName",
6484
+ regex: escapeRegex(phrase)
6485
+ } },
6486
+ 0,
6487
+ 1
6488
+ ] },
6489
+ searchCount: { $add: words.map((word) => ({ $cond: [
6490
+ { $or: [
6491
+ has("name", word),
6492
+ has("description", word),
6493
+ has("body", word)
6494
+ ] },
6294
6495
  1,
6295
- 2
6296
- ] }
6297
- ] } } },
6496
+ 0
6497
+ ] })) },
6498
+ searchScore: { $add: words.map((word) => ({ $switch: {
6499
+ branches: [
6500
+ {
6501
+ case: has("name", word),
6502
+ then: KNOWLEDGE_SEARCH_WEIGHTS.name
6503
+ },
6504
+ {
6505
+ case: has("description", word),
6506
+ then: KNOWLEDGE_SEARCH_WEIGHTS.description
6507
+ },
6508
+ {
6509
+ case: has("body", word),
6510
+ then: KNOWLEDGE_SEARCH_WEIGHTS.body
6511
+ }
6512
+ ],
6513
+ default: 0
6514
+ } })) }
6515
+ } },
6298
6516
  { $sort: {
6299
6517
  searchTier: 1,
6518
+ searchCount: -1,
6519
+ searchScore: -1,
6300
6520
  updatedAt: -1,
6301
6521
  id: 1
6302
6522
  } },
6303
6523
  { $limit: limit },
6304
6524
  { $project: {
6305
6525
  searchTier: 0,
6526
+ searchCount: 0,
6527
+ searchScore: 0,
6306
6528
  _id: 0
6307
6529
  } }
6308
6530
  ]).toArray()).map((row) => ({
@@ -6310,15 +6532,29 @@ var MongoKnowledgePages = class {
6310
6532
  page: toPage(row)
6311
6533
  }));
6312
6534
  if (hits.length >= limit) return hits;
6313
- const noteRows = await (await this.#c("notes")).find({
6314
- ...live,
6315
- ...this.#visibleNotes(ids),
6316
- ...scopes ? { pageScopeId: { $in: ids === null ? scopes : scopes.filter((id) => ids.includes(id)) } } : {},
6317
- $and: words.map((word) => ({ text: matcher(word) }))
6318
- }, noProjection).sort({
6319
- updatedAt: -1,
6320
- id: -1
6321
- }).limit(limit - hits.length).toArray();
6535
+ const noteRows = await (await this.#c("notes")).aggregate([
6536
+ { $match: {
6537
+ ...live,
6538
+ ...this.#visibleNotes(ids),
6539
+ ...scopes ? { pageScopeId: { $in: ids === null ? scopes : scopes.filter((id) => ids.includes(id)) } } : {},
6540
+ $or: words.map((word) => ({ text: matcher(word) }))
6541
+ } },
6542
+ { $addFields: { searchScore: { $add: words.map((word) => ({ $cond: [
6543
+ has("text", word),
6544
+ 1,
6545
+ 0
6546
+ ] })) } } },
6547
+ { $sort: {
6548
+ searchScore: -1,
6549
+ updatedAt: -1,
6550
+ id: -1
6551
+ } },
6552
+ { $limit: limit - hits.length },
6553
+ { $project: {
6554
+ searchScore: 0,
6555
+ _id: 0
6556
+ } }
6557
+ ]).toArray();
6322
6558
  const notePages = new Map((await pages.find({
6323
6559
  id: { $in: [...new Set(noteRows.map((row) => String(row.pageId)))] },
6324
6560
  ...live
@@ -6407,15 +6643,24 @@ var MongoKnowledgePages = class {
6407
6643
  "activity",
6408
6644
  "pins",
6409
6645
  "notes",
6646
+ "links",
6410
6647
  "pages"
6411
6648
  ]) await (await this.#c(name)).deleteMany({}, { session });
6412
6649
  });
6413
6650
  }
6414
6651
  async addPinAudience(input) {
6652
+ const kind = input.kind ?? "page";
6415
6653
  return this.#tx(async (session) => {
6416
6654
  const page = await this.#requireLivePage(input.pageId, session);
6417
6655
  const now = /* @__PURE__ */ new Date();
6418
- const { pin, changed } = await this.#upsertPinAudience(session, page.id, input.audience, input.createdBy, now);
6656
+ const { pin, changed } = await this.#upsertPinAudience(session, {
6657
+ pageId: page.id,
6658
+ kind,
6659
+ depth: kind === "list" ? input.depth ?? 1 : null,
6660
+ audience: input.audience,
6661
+ createdBy: input.createdBy,
6662
+ now
6663
+ });
6419
6664
  if (changed) await this.#log(session, {
6420
6665
  action: "pin-added",
6421
6666
  scopeId: page.scopeId,
@@ -6426,9 +6671,14 @@ var MongoKnowledgePages = class {
6426
6671
  return pin;
6427
6672
  });
6428
6673
  }
6429
- async #upsertPinAudience(session, pageId, audience, createdBy, now) {
6674
+ /** `keepDepth` (merges) leaves an existing pin's depth as it is instead of setting `depth`. */
6675
+ async #upsertPinAudience(session, input) {
6676
+ const { pageId, kind, audience, now } = input;
6430
6677
  const pins = await this.#c("pins");
6431
- const existing = await pins.findOne({ pageId }, {
6678
+ const existing = await pins.findOne({
6679
+ pageId,
6680
+ kind
6681
+ }, {
6432
6682
  ...noProjection,
6433
6683
  session
6434
6684
  });
@@ -6436,8 +6686,10 @@ var MongoKnowledgePages = class {
6436
6686
  const doc = {
6437
6687
  id: createKnowledgeUlid(),
6438
6688
  pageId,
6689
+ kind,
6690
+ ...input.depth === null ? {} : { depth: input.depth },
6439
6691
  audience: [...new Set(audience)],
6440
- createdBy,
6692
+ createdBy: input.createdBy,
6441
6693
  createdAt: now,
6442
6694
  updatedAt: now
6443
6695
  };
@@ -6454,13 +6706,22 @@ var MongoKnowledgePages = class {
6454
6706
  }
6455
6707
  const current = existing.audience ?? [];
6456
6708
  const merged = [.../* @__PURE__ */ new Set([...current, ...audience])];
6457
- if (merged.length === current.length) return {
6709
+ const currentDepth = existing.depth == null ? null : Number(existing.depth);
6710
+ const depth = input.keepDepth ? currentDepth : input.depth;
6711
+ if (merged.length === current.length && depth === currentDepth) return {
6458
6712
  pin: toPin(existing),
6459
6713
  changed: false
6460
6714
  };
6461
6715
  return {
6462
- pin: toPin(await pins.findOneAndUpdate({ id: existing.id }, { $set: {
6716
+ pin: toPin(await pins.findOneAndUpdate({ id: existing.id }, depth === null ? {
6717
+ $set: {
6718
+ audience: merged,
6719
+ updatedAt: now
6720
+ },
6721
+ $unset: { depth: "" }
6722
+ } : { $set: {
6463
6723
  audience: merged,
6724
+ depth,
6464
6725
  updatedAt: now
6465
6726
  } }, {
6466
6727
  returnDocument: "after",
@@ -6473,7 +6734,10 @@ var MongoKnowledgePages = class {
6473
6734
  async removePinAudience(input) {
6474
6735
  return this.#tx(async (session) => {
6475
6736
  const pins = await this.#c("pins");
6476
- const existing = await pins.findOne({ pageId: input.pageId }, {
6737
+ const existing = await pins.findOne({
6738
+ pageId: input.pageId,
6739
+ kind: input.kind ?? "page"
6740
+ }, {
6477
6741
  ...noProjection,
6478
6742
  session
6479
6743
  });
@@ -6533,10 +6797,11 @@ var MongoKnowledgePages = class {
6533
6797
  const ids = await this.#readable(input.read);
6534
6798
  const match = {};
6535
6799
  if (input.audience !== "all") match.audience = { $in: input.audience };
6536
- const pageId = {};
6537
- if (input.pageIds) pageId.$in = input.pageIds;
6538
- if (input.excludePageIds?.length) pageId.$nin = input.excludePageIds;
6539
- if (Object.keys(pageId).length) match.pageId = pageId;
6800
+ if (input.kind) match.kind = input.kind;
6801
+ if (input.pageIds) match.pageId = { $in: input.pageIds };
6802
+ const pageOnly = [];
6803
+ if (input.excludePageIds?.length) pageOnly.push({ $or: [{ kind: { $ne: "page" } }, { pageId: { $nin: input.excludePageIds } }] });
6804
+ if (input.withBody) pageOnly.push({ $or: [{ kind: { $ne: "page" } }, { "page.body": { $regex: "\\S" } }] });
6540
6805
  const pins = await this.#c("pins");
6541
6806
  const base = [
6542
6807
  { $match: match },
@@ -6549,7 +6814,7 @@ var MongoKnowledgePages = class {
6549
6814
  { $match: {
6550
6815
  "page.deletedAt": { $exists: false },
6551
6816
  ...ids === null ? {} : { "page.scopeId": { $in: ids } },
6552
- ...input.withBody ? { "page.body": { $regex: "\\S" } } : {}
6817
+ ...pageOnly.length ? { $and: pageOnly } : {}
6553
6818
  } }
6554
6819
  ];
6555
6820
  const pageMatch = [];
@@ -6615,7 +6880,8 @@ var KnowledgeMongoDB = class extends KnowledgeStorage {
6615
6880
  ...super.getCapabilities(),
6616
6881
  schemaVersion: 4,
6617
6882
  supportsSchemaInspection: true,
6618
- supportsExplicitReset: true
6883
+ supportsExplicitReset: true,
6884
+ supportsPinKinds: true
6619
6885
  };
6620
6886
  }
6621
6887
  async init() {
@@ -6645,6 +6911,9 @@ var KnowledgeMongoDB = class extends KnowledgeStorage {
6645
6911
  listChildScopes(input) {
6646
6912
  return this.#pages.listChildScopes(input);
6647
6913
  }
6914
+ countChildScopes(input) {
6915
+ return this.#pages.countChildScopes(input);
6916
+ }
6648
6917
  getPages(input) {
6649
6918
  return this.#pages.getPages(input);
6650
6919
  }
@@ -6684,6 +6953,21 @@ var KnowledgeMongoDB = class extends KnowledgeStorage {
6684
6953
  listNotes(input) {
6685
6954
  return this.#pages.listNotes(input);
6686
6955
  }
6956
+ replacePageBodyLinks(input) {
6957
+ return this.#pages.replacePageBodyLinks(input);
6958
+ }
6959
+ listPageBodyLinkSources(input) {
6960
+ return this.#pages.listPageBodyLinkSources(input);
6961
+ }
6962
+ countPageLinks(input) {
6963
+ return this.#pages.countPageLinks(input);
6964
+ }
6965
+ listPageLinks(input) {
6966
+ return this.#pages.listPageLinks(input);
6967
+ }
6968
+ countChildPages(input) {
6969
+ return this.#pages.countChildPages(input);
6970
+ }
6687
6971
  countNotes(input) {
6688
6972
  return this.#pages.countNotes(input);
6689
6973
  }