UNPKG

@mastra/core

Version:
1 lines • 123 kB
{"version":3,"file":"index.cjs","names":["compileKnowledgeScopes","KnowledgeDeclarationError","knowledgeReadScopeFor","knowledgeRoleOn","knowledgeRunScopes","parseKnowledgePageRef","knowledgeAccessGrants","strongerKnowledgeRole","updateKnowledgeLinks","refreshKnowledgeLinksTo","knowledgeScopeReadable","KnowledgeUnsupportedCapabilityError","parseKnowledgePageRef","MastraBase","KnowledgeDeclarationError","randomUUID","KnowledgeSemanticIndex","getStorageSource","augmentWithInit","knowledgeAccessGrants","strongerKnowledgeRole","buildKnowledgePageTools","PINNED_READ_MEMO_KEY","upsertKnowledgePage","removeKnowledgePage","moveKnowledgePage","addKnowledgeNote","updateKnowledgeNote","removeKnowledgeNote","reindexKnowledgeLinks","buildKnowledgeInstructions","knowledgeRunPrincipals","KnowledgeRun","knowledgeDeliveredPins"],"sources":["../../src/knowledge/changes.ts","../../src/knowledge/reembed.ts","../../src/knowledge/scope-runtime.ts","../../src/knowledge/explorer-pages.ts","../../src/knowledge/index.ts"],"sourcesContent":["import type { KnowledgeStorage } from '../storage/domains/knowledge/base';\nimport type { KnowledgeNote, KnowledgePage, KnowledgePin } from '../storage/domains/knowledge/pages';\n\n/**\n * One committed write to a Knowledge store. Events carry ids only: a listener serving people (a UI\n * stream) must re-read the page under the viewer's read scope and drop what they can't read.\n * `scopeId` is the page's scope after the write; `fromScopeId` (move, and merge for the page merged\n * away) is its scope before. For notes and pins, read the page by `pageId`. Creating a scope emits one\n * `scope:create` for the scope itself, not for its child scopes or template pages, and template pages\n * added later to an existing scope emit nothing: re-list the scope on `scope:create`.\n * `dangerouslyReset()` emits nothing.\n * @experimental\n */\nexport type KnowledgeChangeEvent = {\n  knowledgeId: string;\n  at: Date;\n} & (\n  | { kind: 'scope'; op: 'create'; pageId: string; scopeId: string }\n  | {\n      kind: 'page';\n      op: 'create' | 'update' | 'move' | 'merge' | 'delete';\n      pageId: string;\n      scopeId: string;\n      /** For `move` and `merge`: the moved or merged-away page's scope before the write. */\n      fromScopeId?: string;\n      /** For `merge`: the page merged away (now deleted); `pageId` is the target. */\n      sourceId?: string;\n    }\n  | { kind: 'note'; op: 'add' | 'restamp' | 'remove' | 'restore'; pageId: string; noteId: string }\n  | { kind: 'pin'; op: 'add' | 'remove'; pageId: string }\n);\n\n/** @experimental */\nexport type KnowledgeChangeListener = (event: KnowledgeChangeEvent) => void;\n\ntype Change = {\n  [K in KnowledgeChangeEvent['kind']]: Omit<Extract<KnowledgeChangeEvent, { kind: K }>, 'knowledgeId' | 'at'>;\n}[KnowledgeChangeEvent['kind']];\n\nconst page = (op: 'create' | 'update' | 'delete') => (result: unknown) => {\n  const { id, scopeId } = result as KnowledgePage;\n  return { kind: 'page', op, pageId: id, scopeId } as Change;\n};\nconst note = (op: 'add' | 'restamp' | 'remove' | 'restore') => (result: unknown) => {\n  const { id, pageId } = result as KnowledgeNote;\n  return { kind: 'note', op, pageId, noteId: id } as Change;\n};\n\ntype Describe = (result: unknown, input: any, fromScopeId: string | undefined) => Change | null;\n\n/** The page-store writes that emit, and the event each one's result maps to. */\nconst WRITES: Record<string, Describe> = {\n  materializeScope: result => {\n    const { scope, created } = result as { scope: KnowledgePage; created: boolean };\n    return created ? { kind: 'scope', op: 'create', pageId: scope.id, scopeId: scope.id } : null;\n  },\n  createPage: page('create'),\n  updatePage: page('update'),\n  movePage: (result, _input, fromScopeId) => {\n    const { id, scopeId } = result as KnowledgePage;\n    return { kind: 'page', op: 'move', pageId: id, scopeId, fromScopeId };\n  },\n  deletePage: page('delete'),\n  mergePages: (result, input: { sourceId: string }, fromScopeId) => {\n    const { id, scopeId } = result as KnowledgePage;\n    return { kind: 'page', op: 'merge', pageId: id, scopeId, sourceId: input.sourceId, fromScopeId };\n  },\n  addNote: note('add'),\n  restampNote: note('restamp'),\n  removeNote: note('remove'),\n  restoreNote: note('restore'),\n  addPinAudience: result => ({ kind: 'pin', op: 'add', pageId: (result as KnowledgePin).pageId }),\n  removePinAudience: (result, input: { pageId: string }) => ({ kind: 'pin', op: 'remove', pageId: input.pageId }),\n};\n\n/** Writes whose event says where the page was before; the page id is read from the input. */\nconst MOVED_PAGE: Record<string, (input: any) => string> = {\n  movePage: (input: { id: string }) => input.id,\n  mergePages: (input: { sourceId: string }) => input.sourceId,\n};\n\n/**\n * Wraps `storage` so each page-store write in {@link WRITES} calls `emit` after it resolves. Every\n * other member passes through, bound to the real store so adapters' private fields keep working.\n * Nothing extra happens while `listening()` is false. Describing or emitting an event never fails a\n * write that committed: errors go to `onError`.\n */\nexport function emitKnowledgeChanges(\n  storage: KnowledgeStorage,\n  emit: (change: Change) => void,\n  listening: () => boolean,\n  onError: (error: unknown) => void,\n): KnowledgeStorage {\n  return new Proxy(storage, {\n    get(target, property) {\n      const value = Reflect.get(target, property, target);\n      if (typeof value !== 'function') return value;\n      const describe = typeof property === 'string' ? WRITES[property] : undefined;\n      if (!describe) return value.bind(target);\n      const moved = typeof property === 'string' ? MOVED_PAGE[property] : undefined;\n      return async (input: unknown, ...rest: unknown[]) => {\n        let fromScopeId: string | undefined;\n        if (moved && listening()) {\n          try {\n            fromScopeId = (await target.getPage({ id: moved(input), read: 'all' }))?.scopeId;\n          } catch (error) {\n            onError(error);\n          }\n        }\n        const result = await value.call(target, input, ...rest);\n        if (!listening()) return result;\n        try {\n          const change = describe(result, input, fromScopeId);\n          if (change) emit(change);\n        } catch (error) {\n          onError(error);\n        }\n        return result;\n      };\n    },\n  });\n}\n","import type { KnowledgePage, KnowledgeStorage } from '../storage/domains/knowledge';\nimport { KNOWLEDGE_MAX_PAGE_CHUNKS } from './semantic';\nimport type { KnowledgeSemanticIndex } from './semantic';\n\nconst DEFAULT_LIMIT = 50;\nconst MAX_LIMIT = 500;\nconst NOTE_PAGE = 100;\n\n/** @experimental */\nexport interface KnowledgeReembedOptions {\n  /** Only this scope's pages and the notes on them, e.g. `org:acme`. Default: the whole store. */\n  scope?: string;\n  /** Pages handled in this call, 1 to 500. A page's notes go with it; in a whole-store run, each scope whose page notes are embedded also counts as one. Default 50. */\n  limit?: number;\n  /** `nextCursor` from the previous call. Omit to start. */\n  cursor?: string;\n}\n\n/** @experimental */\nexport interface KnowledgeReembedResult {\n  /** What this call embedded. */\n  embedded: { pages: number; notes: number };\n  /** Pages and notes whose embed still failed after Knowledge's own retries (other than rate limiting); the rest of the batch went on. A later run retries them. */\n  failed: Array<{ kind: 'page' | 'note'; id: string; error: string }>;\n  /** Pages longer than the chunk cap: embedded up to it, the rest is found by keyword search only. */\n  overChunkCap: Array<{ pageId: string; chunks: number }>;\n  /** The embedder kept rate limiting, so the call stopped early. Wait before passing `nextCursor`, which resumes where it stopped, mid-page if need be. `embedded` and `failed` still count what this call got done. */\n  rateLimited?: true;\n  /** Pass it to the next call to go on. Absent when everything has been handled. */\n  nextCursor?: string;\n}\n\n/**\n * Where a run is: `pages` lists ordinary pages from cursor `c`, `skip` of them already handled;\n * `scopes` walks the scope tree depth first for notes on scope pages, one child per listing:\n * `path` holds, for each scope on the way down, its parent `p` and the listing cursor `c` to its\n * next child. The cursor grows with the depth of the tree, not the number of scopes.\n */\ntype ScopePath = Array<{ p: string | null; c?: string }>;\n\n/**\n * Progress inside the page (or scope page) the position points at, kept when a 429 stops a call\n * part way through it: `bc` body chunks already stored, `body` once the whole page is embedded, then\n * notes from listing cursor `nc` with `ns` of that listing already handled.\n */\ntype Progress = { body: boolean; bc?: number; nc?: string; ns: number };\n\ntype Position = (\n  | { scope?: string; phase: 'scope-notes' }\n  | { scope?: string; phase: 'pages'; c?: string; skip: number }\n  | { scope?: undefined; phase: 'scopes'; path: ScopePath }\n) & { item?: Progress };\n\nfunction encode(position: Position): string {\n  return Buffer.from(JSON.stringify({ v: 2, ...position })).toString('base64url');\n}\n\nfunction decode(cursor: string, scope: string | undefined): Position {\n  let position: (Position & { v?: number }) | undefined;\n  try {\n    position = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));\n  } catch {\n    position = undefined;\n  }\n  if (!position || position.v !== 2 || !['scope-notes', 'pages', 'scopes'].includes(position.phase)) {\n    throw new Error('Knowledge reembed: the cursor is not one reembed() returned.');\n  }\n  if (position.scope !== scope) {\n    throw new Error('Knowledge reembed: the cursor was returned for a different scope.');\n  }\n  return position;\n}\n\n/** A 429 from the embedder, whether thrown directly or as the last try of a retry error. */\nfunction isRateLimit(error: unknown): boolean {\n  const e = error as { statusCode?: number; lastError?: { statusCode?: number } } | undefined;\n  return e?.statusCode === 429 || e?.lastError?.statusCode === 429;\n}\n\nfunction message(error: unknown): string {\n  return error instanceof Error ? error.message : String(error);\n}\n\nclass RateLimited extends Error {}\n\n/**\n * Embeds existing pages and notes in batches, without changing them. Each call handles up to\n * `limit` pages with their notes and returns a cursor to go on from, so a run over a large store\n * can stop and resume. Vector ids are fixed per page chunk and note, so handling a page again\n * overwrites its vectors.\n * @internal\n */\nexport async function reembedKnowledge(\n  storage: KnowledgeStorage,\n  index: KnowledgeSemanticIndex,\n  options: KnowledgeReembedOptions = {},\n): Promise<KnowledgeReembedResult> {\n  const limit = options.limit ?? DEFAULT_LIMIT;\n  if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {\n    throw new Error(`Knowledge reembed: limit must be an integer from 1 to ${MAX_LIMIT}.`);\n  }\n  let scopeId: string | undefined;\n  if (options.scope !== undefined) {\n    const [scope] = await storage.getScopesByAddress([options.scope]);\n    if (!scope) throw new Error(`Knowledge reembed: no scope \"${options.scope}\".`);\n    scopeId = scope.id;\n  }\n  const { item: resumeItem, ...start }: Position = options.cursor\n    ? decode(options.cursor, options.scope)\n    : options.scope\n      ? { scope: options.scope, phase: 'scope-notes' }\n      : { phase: 'pages', skip: 0 };\n  let position: Position | undefined = start as Position;\n\n  const result: KnowledgeReembedResult = { embedded: { pages: 0, notes: 0 }, failed: [], overChunkCap: [] };\n  let handled = 0;\n  // How far into the current page or scope page this call got, so a 429 resumes mid-way instead of\n  // starting the page over: a page with more notes than one quota window would never finish.\n  let item: Progress = resumeItem ?? { body: false, ns: 0 };\n\n  /** Notes on one page, from where `item` says the last call stopped. */\n  const notesOn = async (pageId: string) => {\n    do {\n      const page = await storage.listNotes({ pageId, read: 'all', cursor: item.nc, limit: NOTE_PAGE });\n      for (const note of page.notes.slice(item.ns)) {\n        try {\n          await index.indexNote(note);\n          result.embedded.notes++;\n        } catch (error) {\n          if (isRateLimit(error)) throw new RateLimited();\n          result.failed.push({ kind: 'note', id: note.id, error: message(error) });\n        }\n        item = { ...item, ns: item.ns + 1 };\n      }\n      if (!page.nextCursor) break;\n      item = { ...item, nc: page.nextCursor, ns: 0 };\n    } while (true);\n  };\n\n  /** One ordinary page with its notes. */\n  const handlePage = async (page: KnowledgePage) => {\n    if (!item.body) {\n      try {\n        const chunks = await index.indexPage(page, item.bc ?? 0);\n        result.embedded.pages++;\n        if (chunks > KNOWLEDGE_MAX_PAGE_CHUNKS) result.overChunkCap.push({ pageId: page.id, chunks });\n      } catch (error) {\n        if (isRateLimit(error)) {\n          const stored = (error as { knowledgeStoredChunks?: number }).knowledgeStoredChunks;\n          if (stored) item = { ...item, bc: stored };\n          throw new RateLimited();\n        }\n        result.failed.push({ kind: 'page', id: page.id, error: message(error) });\n      }\n      item = { ...item, body: true, bc: undefined };\n    }\n    await notesOn(page.id);\n  };\n\n  /** Notes on a scope page (scope pages themselves aren't embedded). */\n  const handleScope = (scopePageId: string) => notesOn(scopePageId);\n\n  const done = () => {\n    item = { body: false, ns: 0 };\n  };\n\n  try {\n    while (position && handled < limit) {\n      if (position.phase === 'scope-notes') {\n        await handleScope(scopeId!);\n        done();\n        position = { scope: options.scope, phase: 'pages', skip: 0 };\n        continue;\n      }\n      if (position.phase === 'pages') {\n        const listing = await storage.listPages({\n          read: 'all',\n          scopeId,\n          cursor: position.c,\n          limit: position.skip + (limit - handled),\n        });\n        const pages = listing.pages.slice(position.skip);\n        for (const page of pages) {\n          if (handled >= limit) break;\n          await handlePage(page);\n          done();\n          handled++;\n          position = { ...position, skip: position.skip + 1 };\n        }\n        if (position.skip >= listing.pages.length) {\n          position = listing.nextCursor\n            ? { ...position, c: listing.nextCursor, skip: 0 }\n            : options.scope\n              ? undefined\n              : { phase: 'scopes', path: [{ p: null }] };\n        }\n        continue;\n      }\n      // Scope phase, whole-store runs only. Every listing counts toward the limit: one that finds a\n      // child counts as that scope, an empty one counts on its own.\n      const path: ScopePath = position.path;\n      const { p, c } = path[path.length - 1]!;\n      const listing = await storage.listChildScopes({ parentId: p, cursor: c, limit: 1 });\n      const child = listing.pages[0];\n      const rest: ScopePath = path.slice(0, -1);\n      if (child) {\n        await handleScope(child.id);\n        done();\n        const next: ScopePath = listing.nextCursor ? [{ p, c: listing.nextCursor }] : [];\n        position = { phase: 'scopes', path: [...rest, ...next, { p: child.id }] };\n      } else {\n        position = rest.length ? { phase: 'scopes', path: rest } : undefined;\n      }\n      handled++;\n    }\n  } catch (error) {\n    if (!(error instanceof RateLimited)) throw error;\n    result.rateLimited = true;\n    if (position && (item.body || item.bc || item.ns > 0 || item.nc)) position = { ...position, item };\n  }\n\n  if (position) result.nextCursor = encode(position);\n  return result;\n}\n","import type {\n  KnowledgePage,\n  KnowledgeProvenance,\n  KnowledgeReadScope,\n  KnowledgeStorage,\n} from '../storage/domains/knowledge';\nimport { parseKnowledgePageRef } from '../storage/domains/knowledge';\nimport { knowledgeAccessGrants, knowledgeReadScopeFor, knowledgeRoleOn } from './access';\nimport type { KnowledgeAccessGrant } from './access';\nimport {\n  compileKnowledgeScopes,\n  KnowledgeDeclarationError,\n  knowledgeRunScopes,\n  strongerKnowledgeRole,\n} from './declarations';\nimport type { CompiledKnowledgeScopes, KnowledgeRole, KnowledgeScopeDeclarations } from './declarations';\nimport { refreshKnowledgeLinksTo, updateKnowledgeLinks } from './links';\n\n/** Why a run can or can't reach a scope or page. See {@link Knowledge.explainAccess}. @experimental */\nexport interface KnowledgeAccessExplanation {\n  /** The run's strongest role on the target's scope; null when it can't read it. */\n  role: KnowledgeRole | null;\n  /** Every rule that gives one of the run's principals a role there. */\n  reasons: KnowledgeAccessGrant[];\n  /** The resolved page and its home scope address, for page targets that exist. */\n  page?: { id: string; scope: string };\n  /** `missing`: no such page. `hidden`: the page exists but the run can't read its scope. `no-rule`: a scope no rule gives the run. */\n  reason?: 'missing' | 'hidden' | 'no-rule';\n}\n\ntype ScopeMatch = NonNullable<ReturnType<CompiledKnowledgeScopes['match']>>;\ntype HeldPrincipals = Map<string, Array<{ principal: string; params: ScopeMatch['params'] }>>;\n/** The addresses a write-run start looked up, and the scope pages it found or wrote since. */\ntype KnownScopes = { looked: Set<string>; byAddress: Map<string, KnowledgePage>; byId: Map<string, KnowledgePage> };\ntype MaterializeRun = { held: HeldPrincipals; known?: KnownScopes };\n\n/** How long the store's scope declarations are reused before {@link KnowledgeScopeRuntime.resolve} reads them again. */\nexport const KNOWLEDGE_STORE_DECLARATIONS_TTL_MS = 30_000;\n\n/** Declaration-backed access and lazy scope creation shared by the Knowledge lifecycle and tools. @internal */\nexport class KnowledgeScopeRuntime {\n  readonly #config: KnowledgeScopeDeclarations;\n  readonly #configCompiled: CompiledKnowledgeScopes;\n  /** The last resolved declarations, keyed by what the store supplied. */\n  #resolved: { stored: string; compiled: CompiledKnowledgeScopes; skipped: Map<string, string> };\n  #declarationsChecked?: Promise<void>;\n  /** The store's declarations as last read, shared by concurrent calls until they expire. */\n  #stored?: { readAt: number; declarations: Promise<KnowledgeScopeDeclarations> };\n\n  constructor(\n    declarations: KnowledgeScopeDeclarations,\n    private readonly getStorage: () => Promise<KnowledgeStorage>,\n    private readonly warn: (message: string) => void,\n  ) {\n    this.#config = structuredClone(declarations);\n    this.#configCompiled = compileKnowledgeScopes(structuredClone(declarations));\n    this.#resolved = { stored: '{}', compiled: this.#configCompiled, skipped: new Map() };\n  }\n\n  /** The declarations as last resolved: the config's, plus the store's from the latest {@link resolve}. */\n  get compiled(): CompiledKnowledgeScopes {\n    return this.#resolved.compiled;\n  }\n\n  /**\n   * Reads the store's scope declarations and merges them under the config's: a key the config\n   * declares keeps the config's declaration. Called once at the start of every call. The store's\n   * answer is reused for {@link KNOWLEDGE_STORE_DECLARATIONS_TTL_MS}, so a declaration the store adds\n   * or changes applies within that window, and right away after {@link invalidate}. A store\n   * declaration that doesn't compile next to the others is skipped with a warning. Recompiles only\n   * when the store's answer changes.\n   */\n  async resolve(): Promise<CompiledKnowledgeScopes> {\n    const entry = this.#readStored();\n    const stored = await entry.declarations;\n    // Replaced while this read was in flight, by invalidate() or a newer read once the window\n    // passed: its answer may predate the change, so take the current one instead.\n    if (this.#stored !== entry) return this.resolve();\n    const key = JSON.stringify(stored);\n    if (key === this.#resolved.stored) return this.#resolved.compiled;\n    let merged = this.#config;\n    let compiled = this.#configCompiled;\n    // Declarations can name types declared after them, or each other, so the whole record is tried\n    // first. When that fails, ones that compile on their own are added until a pass adds none, then\n    // the rest without each one in turn, which keeps a group that only compiles together next to one\n    // that doesn't compile.\n    let pending = Object.entries(stored).filter(([name]) => !Object.hasOwn(this.#config, name));\n    const failures = new Map<string, unknown>();\n    const skippedReasons = new Map<string, string>();\n    const add = (entries: typeof pending, failed?: string) => {\n      const next = { ...merged, ...Object.fromEntries(entries) };\n      try {\n        compiled = compileKnowledgeScopes(structuredClone(next));\n        merged = next;\n        return true;\n      } catch (error) {\n        if (failed) failures.set(failed, error);\n        return false;\n      }\n    };\n    if (!add(pending)) {\n      while (pending.length) {\n        const skipped = pending.filter(entry => !add([entry], entry[0]));\n        if (skipped.length < pending.length) {\n          pending = skipped;\n          continue;\n        }\n        const left = skipped.findIndex((_, i) => skipped.length > 1 && add(skipped.filter((__, j) => j !== i)));\n        if (left !== -1) {\n          pending = [skipped[left]!];\n          continue;\n        }\n        for (const [name] of skipped) {\n          const error = failures.get(name);\n          const reason = error instanceof Error ? error.message : String(error);\n          skippedReasons.set(name, reason);\n          this.warn(`Knowledge skipped the store's scope declaration \"${name}\": ${reason}`);\n        }\n        break;\n      }\n    }\n    this.#resolved = { stored: key, compiled, skipped: skippedReasons };\n    this.#declarationsChecked = undefined;\n    return compiled;\n  }\n\n  /** Makes the next {@link resolve} read the store's declarations again. */\n  invalidate(): void {\n    this.#stored = undefined;\n  }\n\n  #readStored(): { readAt: number; declarations: Promise<KnowledgeScopeDeclarations> } {\n    const now = Date.now();\n    // `now >= readAt` keeps a clock that moved backwards from extending the window.\n    if (this.#stored && now >= this.#stored.readAt && now - this.#stored.readAt < KNOWLEDGE_STORE_DECLARATIONS_TTL_MS) {\n      return this.#stored;\n    }\n    const entry = {\n      readAt: now,\n      declarations: this.getStorage().then(storage => storage.getScopeDeclarations()),\n    };\n    this.#stored = entry;\n    // A failed read isn't kept, so the next call tries again.\n    entry.declarations.catch(() => {\n      if (this.#stored === entry) this.#stored = undefined;\n    });\n    return entry;\n  }\n\n  validatePrincipals(principals: readonly string[]): void {\n    for (const principal of principals) {\n      if (!this.compiled.match(principal)) {\n        throw new KnowledgeDeclarationError(`Knowledge run scope \"${principal}\" does not match a declared scope type.`);\n      }\n    }\n  }\n\n  /**\n   * Fails when stored scope pages carry declaration keys neither the config nor the store declares: a\n   * renamed or removed key would otherwise silently cut those scopes off from prefix and `belongsTo`\n   * reach. Checked once per set of resolved declarations; only a pass is remembered, so a store error\n   * is retried next time.\n   */\n  checkDeclarations(): Promise<void> {\n    if (!this.#declarationsChecked) {\n      const check = this.#checkDeclarations();\n      this.#declarationsChecked = check;\n      check.catch(() => {\n        if (this.#declarationsChecked === check) this.#declarationsChecked = undefined;\n      });\n    }\n    return this.#declarationsChecked;\n  }\n\n  async #checkDeclarations(): Promise<void> {\n    const storage = await this.getStorage();\n    const orphans = (await storage.listScopeDeclarations()).filter(\n      ({ declaration }) => !this.compiled.declarations.has(declaration),\n    );\n    if (orphans.length === 0) return;\n    const list = (entries: typeof orphans) =>\n      entries\n        .map(({ declaration, scopes }) => `\"${declaration}\" (${scopes} scope${scopes === 1 ? '' : 's'})`)\n        .join(', ');\n    // A store declaration that didn't compile leaves its stored scopes, its children's included,\n    // without a declaration too. Name it and why, since the fix is in the store, not the config.\n    const skippedKey = (declaration: string) => {\n      const key = declaration.split('/')[0]!;\n      return this.#resolved.skipped.has(key) ? key : undefined;\n    };\n    const undeclared = orphans.filter(({ declaration }) => !skippedKey(declaration));\n    const messages: string[] = [];\n    if (undeclared.length) {\n      messages.push(\n        `Knowledge storage has scopes created from declarations this config doesn't declare: ${list(undeclared)}. ` +\n          'Restore each key in scopes, rename it with knowledge.renameScopeDeclaration(from, to), ' +\n          'or keep the key with no access rules to retire it.',\n      );\n    }\n    for (const key of new Set(orphans.map(({ declaration }) => skippedKey(declaration)).filter(k => k !== undefined))) {\n      const stranded = orphans.filter(({ declaration }) => skippedKey(declaration) === key);\n      messages.push(\n        `Knowledge skipped the store's scope declaration \"${key}\", so its stored scopes have none: ${list(stranded)}. ` +\n          `${this.#resolved.skipped.get(key)} Fix that declaration in the store, or declare the key, with its children, in scopes to override it.`,\n      );\n    }\n    throw new KnowledgeDeclarationError(messages.join(' '));\n  }\n\n  /** Re-keys stored scopes from declaration `from` to `to`. See {@link Knowledge.renameScopeDeclaration}. */\n  async renameScopeDeclaration(from: string, to: string): Promise<number> {\n    if (this.compiled.declarations.has(from)) {\n      throw new KnowledgeDeclarationError(\n        `Can't rename scope declaration \"${from}\": it is still declared. Remove it from scopes first.`,\n      );\n    }\n    if (!this.compiled.declarations.has(to)) {\n      throw new KnowledgeDeclarationError(`Can't rename scope declaration to \"${to}\": it isn't declared in scopes.`);\n    }\n    const storage = await this.getStorage();\n    const renamed = await storage.renameScopeDeclaration({\n      from,\n      to,\n      check: scopes => {\n        const mismatched = scopes.filter(scope => this.compiled.match(scope.address)?.declaration !== scope.to);\n        if (mismatched.length === 0) return;\n        throw new KnowledgeDeclarationError(\n          `Can't rename scope declaration \"${from}\" to \"${to}\": ` +\n            mismatched\n              .slice(0, 5)\n              .map(scope => `\"${scope.address}\" doesn't match \"${scope.to}\"`)\n              .join(', ') +\n            (mismatched.length > 5 ? `, and ${mismatched.length - 5} more` : '') +\n            '. Nothing was renamed.',\n        );\n      },\n    });\n    this.#declarationsChecked = undefined;\n    this.invalidate();\n    return renamed;\n  }\n\n  /**\n   * Whether a stored scope row belongs to the declaration its address matches today. Rows written\n   * before scope params matched exactly one segment can carry another (`org:acme:viewer` stored\n   * under `org:$orgId`); they must not pick up the rules of the declaration that now matches them.\n   */\n  #isCurrent(scope: KnowledgePage): boolean {\n    return !scope.declaration || this.compiled.match(scope.address!)?.declaration === scope.declaration;\n  }\n\n  #assertCurrent(scope: KnowledgePage): void {\n    if (this.#isCurrent(scope)) return;\n    throw new KnowledgeDeclarationError(\n      `Knowledge scope \"${scope.address}\" was created from \"${scope.declaration}\", which no longer matches it ` +\n        `(scope params match one segment; encode colons in ids as %3A). It can't be used as a scope of ` +\n        `\"${this.compiled.match(scope.address!)?.declaration}\".`,\n    );\n  }\n\n  async readScopeFor(principals: readonly string[]): Promise<Exclude<KnowledgeReadScope, 'all'>> {\n    this.validatePrincipals(principals);\n    await this.checkDeclarations();\n    const storage = await this.getStorage();\n    // belongsTo parents resolve through current rows only, so a stale row can't parent new children.\n    const read = await knowledgeReadScopeFor(this.compiled, principals, async addresses =>\n      (await storage.getScopesByAddress(addresses)).filter(scope => this.#isCurrent(scope)),\n    );\n    if (read.addresses.length === 0) return read;\n    const stale = new Set(\n      (await storage.getScopesByAddress(read.addresses))\n        .filter(scope => !this.#isCurrent(scope))\n        .map(scope => scope.address!),\n    );\n    return stale.size ? { ...read, addresses: read.addresses.filter(address => !stale.has(address)) } : read;\n  }\n\n  async roleOn(principals: readonly string[], scope: KnowledgePage): Promise<KnowledgeRole | null> {\n    this.validatePrincipals(principals);\n    if (!scope.isScope || !scope.address) throw new Error('Knowledge roles require a scope page.');\n    if (!this.#isCurrent(scope)) return null;\n    const storage = await this.getStorage();\n    return knowledgeRoleOn(this.compiled, principals, {\n      address: scope.address,\n      parentAddress: await this.#currentParentAddress(storage, scope),\n    });\n  }\n\n  // A stale parent row (its address now matches another declaration) must not bind belongsTo rules.\n  async #currentParentAddress(storage: KnowledgeStorage, scope: KnowledgePage): Promise<string | undefined> {\n    if (!scope.parentId) return undefined;\n    const parent = await storage.getPage({ id: scope.parentId, read: 'all' });\n    return parent && this.#isCurrent(parent) ? (parent.address ?? undefined) : undefined;\n  }\n\n  async explainAccess(\n    runScopes: readonly string[],\n    target: { scope: string } | { page: string },\n  ): Promise<KnowledgeAccessExplanation> {\n    const principals = knowledgeRunScopes(this.compiled, runScopes);\n    this.validatePrincipals(principals);\n    const storage = await this.getStorage();\n\n    let scope: KnowledgePage | undefined;\n    let page: KnowledgePage | null = null;\n    if ('scope' in target) {\n      if (!this.compiled.match(target.scope)) {\n        throw new KnowledgeDeclarationError(`Knowledge scope \"${target.scope}\" does not match a declared scope type.`);\n      }\n      [scope] = await storage.getScopesByAddress([target.scope]);\n    } else {\n      if (target.page.indexOf('#') > 0) {\n        const parsed = parseKnowledgePageRef(target.page);\n        if (parsed) [scope] = await storage.getScopesByAddress([parsed.scope]);\n        page =\n          parsed && scope ? await storage.getPageByPath({ scopeId: scope.id, path: parsed.path, read: 'all' }) : null;\n      } else {\n        page = await storage.getPage({ id: target.page, read: 'all' });\n        if (page?.deletedAt) page = null;\n        scope = page\n          ? page.isScope\n            ? page\n            : ((await storage.getPage({ id: page.scopeId, read: 'all' })) ?? undefined)\n          : undefined;\n      }\n      if (!page || !scope?.address) return { role: null, reasons: [], reason: 'missing' };\n    }\n\n    const address = scope?.address ?? (target as { scope: string }).scope;\n    const reasons =\n      scope && !this.#isCurrent(scope)\n        ? []\n        : knowledgeAccessGrants(this.compiled, principals, {\n            address,\n            parentAddress: scope ? await this.#currentParentAddress(storage, scope) : undefined,\n          });\n    let role: KnowledgeRole | null = null;\n    for (const reason of reasons) role = strongerKnowledgeRole(role, reason.role);\n    return {\n      role,\n      reasons,\n      ...(page ? { page: { id: page.id, scope: address } } : {}),\n      ...(role ? {} : { reason: page ? ('hidden' as const) : ('no-rule' as const) }),\n    };\n  }\n\n  /**\n   * The `<scope>#<key path>` of a page its scope's declaration lists in `pages`, or undefined for an\n   * ordinary page. Template pages belong to config: tools can't move them or merge them away.\n   */\n  async templatePageRef(page: KnowledgePage): Promise<string | undefined> {\n    if (page.isScope || !page.key) return undefined;\n    const storage = await this.getStorage();\n    const path: string[] = [];\n    let current: KnowledgePage | null = page;\n    while (current && !current.isScope) {\n      if (!current.key) return undefined;\n      path.unshift(current.key);\n      current = current.parentId ? await storage.getPage({ id: current.parentId, read: 'all' }) : null;\n    }\n    if (!current?.address) return undefined;\n    let templates = this.compiled.match(current.address)?.compiled.declaration.pages;\n    for (const key of path) {\n      const template = templates?.find(entry => entry.key === key);\n      if (!template) return undefined;\n      templates = template.pages;\n    }\n    return `${current.address}#${path.join('/')}`;\n  }\n\n  async materializeScope(\n    address: string,\n    principals: readonly string[],\n    provenance: KnowledgeProvenance,\n  ): Promise<KnowledgePage> {\n    this.validatePrincipals(principals);\n    await this.checkDeclarations();\n    return this.#materialize(address, principals, provenance, [], { held: this.#held(principals) });\n  }\n\n  /**\n   * {@link materializeScope} for each address in turn (a write-run start's principals), reading\n   * scopes from one lookup. `#materialize` skips the store call for a scope that exists, needs no new\n   * `belongsTo` link, has its child scopes and declares no template pages; warnings fire as before.\n   */\n  async materializeScopes(\n    addresses: readonly string[],\n    principals: readonly string[],\n    provenance: KnowledgeProvenance,\n  ): Promise<void> {\n    this.validatePrincipals(principals);\n    await this.checkDeclarations();\n    const storage = await this.getStorage();\n    const wanted = new Set<string>();\n    for (const address of addresses) {\n      wanted.add(address);\n      const match = this.compiled.match(address);\n      if (match?.compiled.child) wanted.add(address.slice(0, address.lastIndexOf('/')));\n      else for (const child of match?.compiled.children ?? []) wanted.add(`${address}/${child.child!.name}`);\n    }\n    const known: KnownScopes = { looked: wanted, byAddress: new Map(), byId: new Map() };\n    for (const row of await storage.getScopesByAddress([...wanted])) {\n      known.byAddress.set(row.address!, row);\n      known.byId.set(row.id, row);\n    }\n    const run = { held: this.#held(principals), known };\n    for (const address of addresses) await this.#materialize(address, principals, provenance, [], run);\n  }\n\n  /** The run's distinct principals grouped by declaration key, matched once. */\n  #held(principals: readonly string[]): HeldPrincipals {\n    const held: HeldPrincipals = new Map();\n    for (const principal of new Set(principals)) {\n      const match = this.compiled.match(principal);\n      if (!match) continue;\n      const group = held.get(match.compiled.key) ?? [];\n      group.push({ principal, params: match.params });\n      held.set(match.compiled.key, group);\n    }\n    return held;\n  }\n\n  #belongsToCandidates(match: ScopeMatch, held: HeldPrincipals): string[] {\n    const belongsTo = match.compiled.belongsTo!;\n    return (held.get(belongsTo.key) ?? [])\n      .filter(candidate =>\n        belongsTo.params.every(\n          param => match.params[param] === undefined || candidate.params[param] === match.params[param],\n        ),\n      )\n      .map(candidate => candidate.principal);\n  }\n\n  async #materialize(\n    address: string,\n    principals: readonly string[],\n    provenance: KnowledgeProvenance,\n    ancestors: readonly string[],\n    run: MaterializeRun,\n  ): Promise<KnowledgePage> {\n    const match = this.compiled.match(address);\n    if (!match)\n      throw new KnowledgeDeclarationError(`Knowledge scope \"${address}\" does not match a declared scope type.`);\n    if (ancestors.includes(address))\n      throw new KnowledgeDeclarationError(`Knowledge scope placement cycle at \"${address}\".`);\n    const storage = await this.getStorage();\n    const known = run.known;\n    const lookUp = async (scope: string) =>\n      known?.looked.has(scope) || known?.byAddress.has(scope)\n        ? known.byAddress.get(scope)\n        : (await storage.getScopesByAddress([scope]))[0];\n    if (match.compiled.child) {\n      const parentAddress = address.slice(0, address.lastIndexOf('/'));\n      await this.#materialize(parentAddress, principals, provenance, [...ancestors, address], run);\n      const child = known?.byAddress.get(address) ?? (await storage.getScopesByAddress([address]))[0];\n      if (!child) throw new Error(`Knowledge template child \"${address}\" was not materialized.`);\n      return child;\n    }\n\n    const existing = await lookUp(address);\n    if (existing) this.#assertCurrent(existing);\n    let parentId = existing?.parentId;\n    const belongsTo = match.compiled.belongsTo;\n    if (belongsTo) {\n      const candidates = this.#belongsToCandidates(match, run.held);\n      if (candidates.length > 1) {\n        this.warn(\n          `Knowledge scope \"${address}\" has ambiguous belongsTo placement: ${candidates.join(', ')}. Keeping its existing placement.`,\n        );\n      } else if (candidates[0]) {\n        if (existing?.parentId) {\n          let parent = known?.byId.get(existing.parentId) ?? null;\n          if (!parent) {\n            parent = await storage.getPage({ id: existing.parentId, read: 'all' });\n            if (parent) known?.byId.set(parent.id, parent);\n          }\n          if (parent?.address !== candidates[0]) {\n            this.warn(\n              `Knowledge scope \"${address}\" already belongs to \"${parent?.address}\"; ignoring requested parent \"${candidates[0]}\".`,\n            );\n          }\n        } else if (!ancestors.includes(candidates[0]) && candidates[0] !== address) {\n          parentId = (await this.#materialize(candidates[0], principals, provenance, [...ancestors, address], run)).id;\n        } else {\n          this.warn(\n            `Knowledge scope \"${address}\" cannot be placed under \"${candidates[0]}\" because that would form a cycle.`,\n          );\n        }\n      }\n    }\n    const declaration = match.compiled.declaration;\n    // Placed already: nothing to link, and no template pages to restore or child scopes to create.\n    if (\n      known &&\n      existing &&\n      parentId === existing.parentId &&\n      !declaration.pages?.length &&\n      match.compiled.children.every(child => known.byAddress.has(`${address}/${child.child!.name}`))\n    ) {\n      return existing;\n    }\n    const result = await storage.materializeScope({\n      address,\n      declaration: match.declaration,\n      name: address,\n      description: match.concrete?.description ?? declaration.description,\n      parentId,\n      children: match.compiled.children.map(child => ({\n        address: `${address}/${child.child!.name}`,\n        declaration: child.key,\n        name: child.child!.name,\n        description: child.declaration.description,\n      })),\n      pages: declaration.pages,\n      provenance,\n    });\n    this.#assertCurrent(result.scope);\n    if (result.created) {\n      // A new scope (and its config pages) can resolve body links written before it existed.\n      await updateKnowledgeLinks(this.warn, () =>\n        refreshKnowledgeLinksTo(storage, [result.scope], { withDescendants: true }),\n      );\n    }\n    if (result.parentConflict) {\n      this.warn(`Knowledge scope \"${address}\" was already linked by another run; keeping its persisted parent.`);\n    }\n    if (run.known) {\n      run.known.byAddress.set(address, result.scope);\n      run.known.byId.set(result.scope.id, result.scope);\n    }\n    return result.scope;\n  }\n}\n","import type {\n  KnowledgeNote,\n  KnowledgePage,\n  KnowledgePageActivityEvent,\n  KnowledgePageLinkCounts,\n  KnowledgePageLinkEdge,\n  KnowledgePageSearchHit,\n  KnowledgePageStore,\n  KnowledgePin,\n  KnowledgeReadScope,\n} from '../storage';\nimport {\n  KnowledgeUnsupportedCapabilityError,\n  knowledgeScopeReadable,\n  MAX_KNOWLEDGE_PAGE_LIST_LIMIT,\n  parseKnowledgePageRef,\n} from '../storage';\nimport type { KnowledgeRole } from './declarations';\n\n/**\n * Read-only views over the schema-4 page store for browsing UIs (Mastra Studio, Factory).\n *\n * Every reader takes the caller's `read` scope and passes it to each store call, so a page or note the\n * caller can't read behaves like a missing id. `'all'` is for host surfaces behind their own auth.\n * Scope pages are structure the store lists without a read filter; these readers only return the\n * scope pages `read` allows, and hoist readable scopes found below an unreadable one so a bound\n * viewer still reaches them. These functions never write.\n *\n * @experimental Knowledge APIs are experimental and may change without notice.\n */\n\n/** Most scope pages one tree or ancestor walk looks at before it stops and reports truncation. */\nexport const MAX_KNOWLEDGE_EXPLORER_SCOPE_SCAN = 1_000;\n\nfunction scopeVisible(page: KnowledgePage, read: KnowledgeReadScope): boolean {\n  return page.isScope && knowledgeScopeReadable(page, read);\n}\n\nasync function allChildScopes(\n  store: KnowledgePageStore,\n  parentId: string | null,\n  budget: { remaining: number },\n): Promise<{ scopes: KnowledgePage[]; truncated: boolean }> {\n  const scopes: KnowledgePage[] = [];\n  let cursor: string | undefined;\n  do {\n    if (budget.remaining <= 0) return { scopes, truncated: true };\n    const limit = Math.min(MAX_KNOWLEDGE_PAGE_LIST_LIMIT, budget.remaining);\n    const result = await store.listChildScopes({ parentId, cursor, limit });\n    budget.remaining -= result.pages.length;\n    scopes.push(...result.pages);\n    cursor = result.nextCursor;\n  } while (cursor);\n  return { scopes, truncated: false };\n}\n\n/**\n * Child scopes of `parentId` that `read` allows. An unreadable child scope is not returned, but its\n * own readable descendant scopes are, in its place.\n */\nasync function visibleChildScopes(\n  store: KnowledgePageStore,\n  parentId: string | null,\n  read: KnowledgeReadScope,\n  budget: { remaining: number },\n): Promise<{ scopes: KnowledgePage[]; truncated: boolean }> {\n  const direct = await allChildScopes(store, parentId, budget);\n  let truncated = direct.truncated;\n  const scopes: KnowledgePage[] = [];\n  for (const scope of direct.scopes) {\n    if (scopeVisible(scope, read)) {\n      scopes.push(scope);\n      continue;\n    }\n    if (read === 'all') continue;\n    const hoisted = await visibleChildScopes(store, scope.id, read, budget);\n    scopes.push(...hoisted.scopes);\n    truncated ||= hoisted.truncated;\n  }\n  return { scopes, truncated };\n}\n\n/** A page in one tree level, with how many readable children sit directly under it. */\nexport type KnowledgeTreePage = KnowledgePage & {\n  /**\n   * Readable child pages, plus readable child scopes for a scope. Left out when the store can't count\n   * (an adapter older than `countChildPages`), so a UI can tell \"none\" from \"unknown\".\n   */\n  childCount?: number;\n  /**\n   * Set when the child-scope walk for this page hit {@link MAX_KNOWLEDGE_EXPLORER_SCOPE_SCAN}, so\n   * `childCount` is a lower bound: show it as \"at least\" (e.g. `1000+`), not as the exact number.\n   */\n  childCountCapped?: true;\n};\n\nexport interface KnowledgeTreeChildren {\n  /** Readable child scopes (all of them, on the first page only), then readable child pages in order. */\n  pages: KnowledgeTreePage[];\n  /** Cursor for more child pages; child scopes are never paged. */\n  nextCursor?: string;\n  /** True when the scope walk hit {@link MAX_KNOWLEDGE_EXPLORER_SCOPE_SCAN}. */\n  truncated: boolean;\n}\n\n/**\n * One level of the page tree. `parentId: null` lists the root scopes `read` reaches. Child scopes come\n * first (they're structure), then the parent's ordinary child pages, paged with `cursor`/`limit`.\n */\nexport async function listKnowledgeTreeChildren(\n  store: KnowledgePageStore,\n  input: { parentId: string | null; read: KnowledgeReadScope; cursor?: string; limit?: number },\n): Promise<KnowledgeTreeChildren> {\n  const { parentId, read, cursor, limit } = input;\n  if (parentId !== null && !(await store.getPage({ id: parentId, read }))) {\n    return { pages: [], truncated: false };\n  }\n  const scopes =\n    cursor === undefined\n      ? await visibleChildScopes(store, parentId, read, { remaining: MAX_KNOWLEDGE_EXPLORER_SCOPE_SCAN })\n      : { scopes: [], truncated: false };\n  if (parentId === null) {\n    const counted = await withChildCounts(store, scopes.scopes, read);\n    return { pages: counted.pages, truncated: scopes.truncated || counted.truncated };\n  }\n  const children = await store.listChildPages({ parentId, read, cursor, limit });\n  const counted = await withChildCounts(store, [...scopes.scopes, ...children.pages], read);\n  return {\n    pages: counted.pages,\n    ...(children.nextCursor ? { nextCursor: children.nextCursor } : {}),\n    truncated: scopes.truncated || counted.truncated,\n  };\n}\n\n/** Child counts for one level: one `countChildPages` call, plus a child-scope walk per scope page. */\nasync function withChildCounts(\n  store: KnowledgePageStore,\n  pages: KnowledgePage[],\n  read: KnowledgeReadScope,\n): Promise<{ pages: KnowledgeTreePage[]; truncated: boolean }> {\n  if (pages.length === 0 || typeof store.countChildPages !== 'function') return { pages, truncated: false };\n  let counts: Record<string, number>;\n  try {\n    counts = await store.countChildPages({ parentIds: pages.map(page => page.id), read });\n  } catch (error) {\n    if (error instanceof KnowledgeUnsupportedCapabilityError) return { pages, truncated: false };\n    throw error;\n  }\n  const budget = { remaining: MAX_KNOWLEDGE_EXPLORER_SCOPE_SCAN };\n  let truncated = false;\n  const counted: KnowledgeTreePage[] = [];\n  for (const page of pages) {\n    let childCount = Object.hasOwn(counts, page.id) ? (counts[page.id] ?? 0) : 0;\n    let capped = false;\n    if (page.isScope) {\n      const childScopes = await visibleChildScopes(store, page.id, read, budget);\n      childCount += childScopes.scopes.length;\n      capped = childScopes.truncated;\n      truncated ||= capped;\n    }\n    counted.push(capped ? { ...page, childCount, childCountCapped: true } : { ...page, childCount });\n  }\n  return { pages: counted, truncated };\n}\n\n/**\n * Readable ancestors of a readable page, root first, so a UI can open the tree down to it. Unreadable\n * ancestors are skipped, matching how {@link listKnowledgeTreeChildren} hoists readable scopes.\n */\nasync function readableAncestors(\n  store: KnowledgePageStore,\n  page: KnowledgePage,\n  read: KnowledgeReadScope,\n): Promise<KnowledgePage[]> {\n  const path: KnowledgePage[] = [];\n  const seen = new Set([page.id]);\n  let parentId = page.parentId;\n  while (parentId && !seen.has(parentId) && seen.size <= MAX_KNOWLEDGE_EXPLORER_SCOPE_SCAN) {\n    seen.add(parentId);\n    // Structure lookup only: the page is returned only when `read` allows it.\n    const parent = await store.getPage({ id: parentId, read: 'all' });\n    if (!parent) break;\n    const visible = parent.isScope ? scopeVisible(parent, read) : !!(await store.getPage({ id: parent.id, read }));\n    if (visible) path.unshift(parent);\n    parentId = parent.parentId;\n  }\n  return path;\n}\n\nexport const DEFAULT_KNOWLEDGE_PAGE_NOTE_LIMIT = 50;\n\nexport interface KnowledgePageView {\n  page: KnowledgePage;\n  /** Readable ancestors, root first. */\n  ancestors: KnowledgePage[];\n  notes: KnowledgeNote[];\n  notesNextCursor?: string;\n  pin: KnowledgePin | null;\n  /** Readable pages the notes mention or are stamped to, for names and links. Unreadable ids are left out. */\n  related: KnowledgePage[];\n  /** Readable notes on other pages that mention this page (first page). */\n  mentionedBy: KnowledgeNote[];\n}\n\n/**\n * A page by id, or by the reference a tool result names it with: a scope address (`site:mastra`) or\n * `<scope>#<key>[/<key>…]`. Read-gated like the id lookup: an unreadable scope or page is not found.\n * Scope addresses and refs always hold a `:`, which page ids never do, so an id never takes the ref path.\n */\nasync function pageByIdOrRef(store: KnowledgePageStore, ref: string, read: KnowledgeReadScope) {\n  const byId = await store.getPage({ id: ref, read });\n  if (byId || !ref.includes(':')) return byId;\n  const parsed = ref.includes('#') ? parseKnowledgePageRef(ref) : { scope: ref, path: [] };\n  if (!parsed) return null;\n  const [scope] = await store.getScopesByAddress([parsed.scope]);\n  if (!scope || !knowledgeScopeReadable(scope, read)) return null;\n  if (parsed.path.length === 0) return store.getPage({ id: scope.id, read });\n  return store.getPageByPath({ scopeId: scope.id, path: parsed.path, read });\n}\n\n/** One page with its notes, pin and the pages they reference. Null when `read` can't see the page. */\nexport async function readKnowledgePage(\n  store: KnowledgePageStore,\n  input: { pageId: string; read: KnowledgeReadScope; noteCursor?: string; noteLimit?: number },\n): Promise<KnowledgePageView | null> {\n  const { read } = input;\n  const page = await pageByIdOrRef(store, input.pageId, read);\n  if (!page) return null;\n  const pageId = page.id;\n  const [notes, pins, mentionedBy, ancestors] = await Promise.all([\n    store.listNotes({\n      pageId,\n      read,\n      cursor: input.noteCursor,\n      limit: input.noteLimit ?? DEFAULT_KNOWLEDGE_PAGE_NOTE_LIMIT,\n    }),\n    store.listPins({ audience: 'all', read, kind: 'page', pageIds: [pageId], limit: 1 }),\n    store.listNotesMentioning({ pageId, read, limit: DEFAULT_KNOWLEDGE_PAGE_NOTE_LIMIT }),\n    readableAncestors(store, page, read),\n  ]);\n  const known = new Set([page.id, ...ancestors.map(ancestor => ancestor.id)]);\n  const wanted = new Set<string>();\n  for (const note of [...notes.notes, ...mentionedBy.notes]) {\n    for (const id of [...note.mentions, ...note.stampScopeIds, note.pageId]) if (!known.has(id)) wanted.add(id);\n  }\n  if (!known.has(page.scopeId)) wanted.add(page.scopeId);\n  const related = (await Promise.all([...wanted].map(id => store.getPage({ id, read })))).filter(\n    (candidate): candidate is KnowledgePage => candidate !== null,\n  );\n  return {\n    page,\n    ancestors,\n    notes: notes.notes,\n    ...(notes.nextCursor ? { notesNextCursor: notes.nextCursor } : {}),\n    pin: pins.pins[0] ?? null,\n    related,\n    mentionedBy: mentionedBy.notes.filter(note => note.pageId !== pageId),\n  };\n}\n\nexport interface KnowledgePageGraphLimits {\n  /** Most pages walked from the root. */\n  maxPages: number;\n  /** Most notes read across the graph when collecting mentions; each page's notes are read in full until then. */\n  maxNotes: number;\n  /** Most mentioned pages outside the walk added as endpoints. */\n  maxOutsidePages: number;\n}\n\nconst NOTE_BATCH = 100;\n\nexport const DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS: KnowledgePageGraphLimits = {\n  maxPages: 200,\n  maxNotes: 5000,\n  maxOutsidePages: 50,\n};\n\nexport interface KnowledgePageGraphEdge {\n  source: string;\n  target: string;\n  kind: 'parent' | 'mention';\n  /** Mention edges: how many readable notes on `source` mention `target`. */\n  count?: number;\n}\n\nexport interface KnowledgePageGraph {\n  /** Pages in the walk, then readable mentioned pages outside it. */\n  pages: KnowledgePage[];\n  /** Ids of `pages` that are outside the walk (mention endpoints only). */\n  outsideIds: string[];\n  edges: KnowledgePageGraphEdge[];\n  /** Page ids that have pins. */\n  pinnedIds: string[];\n  /** True when a limit stopped the walk or the endpoint list. */\n  truncated: boolean;\n}\n\n/** Runs a per-id count over `pages` in list-limit batches; null when the store can't count. */\nasync function countInBatches(\n  pages: KnowledgePage[],\n  count: (ids: string[]) => Promise<Record<string, number>>,\n): Promise<Record<string, number> | null> {\n  const counts: Record<string, number> = {};\n  try {\n    for (let start = 0; start < pages.length; start += MAX_KNOWLEDGE_PAGE_LIST_LIMIT) {\n      Object.assign(\n        counts,\n        await count(pages.slice(start, start + MAX_KNOWLEDGE_PAGE_LIST_LIMIT).map(page => page.id)),\n      );\n    }\n  } catch (error) {\n    if (error instanceof KnowledgeUnsupportedCapabilityError) return null;\n    throw error;\n  }\n  return counts;\n}\n\n/**\n * Children of every parent in one graph level, in the tree's order: readable child scopes of scope\n * parents (scope pages only sit under scopes), then child pages, listed only for parents the level's\n * one count says have some. `null` lists the root scopes.\n */\nasync function graphLevelChildren(\n  store: KnowledgePageStore,\n  level: Array<string | null>,\n  read: KnowledgeReadScope,\n  byId: Map<string, KnowledgePage>,\n): Promise<{ byParent: KnowledgePage[][]; truncated: boolean }> {\n  let truncated = false;\n  const parents = level.flatMap(id => (id === null ? [] : [byId.get(id)!]));\n  const pageCounts = await countInBatches(parents, ids => store.countChildPages({ parentIds: ids, read }));\n  const byParent: KnowledgePage[][] = [];\n  for (const parentId of level) {\n    const parent = parentId === null ? null : byId.get(parentId)!;\n    const children: KnowledgePage[] = [];\n    if (!parent || parent.isScope) {\n      const scopes = await visibleChildScopes(store, parentId, read, { remaining: MAX_KNOWLEDGE_EXPLORER_SCOPE_SCAN });\n      truncated ||= scopes.truncated;\n      children.push(...scopes.scopes);\n    }\n    if (parent && (!pageCounts || pageCounts[parent.id])) {\n      let cursor: string | undefined;\n      do {\n        const result = await store.listChildPages({ parentId: parent.id, read, cursor });\n        children.push(...result.pages);\n        cursor = result.nextCursor;\n      } while (cursor);\n    }\n    byParent.push(children);\n  }\n  return { byParent, truncated };\n}\n\n/**\n * A bounded graph: pages breadth-first under `rootId` (or every root scope `read` reaches), parent\n * edges between them, and mention edges from their readable notes. A hidden note never contributes\n * an edge, so the graph shows only links the caller could read.\n */\nexport async function readKnowledgePageGraph(\n  store: KnowledgePageStore,\n  input: { read: KnowledgeReadScope; rootId?: string | null; limits?: Partial<KnowledgePageGraphLimits> },\n): Promise<KnowledgePageGraph | null> {\n  const { read } = input;\n  const limits = { ...DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS, ...input.limits };\n  const rootId = input.rootId ?? null;\n  const pages: KnowledgePage[] = [];\n  const byId = new Map<string, KnowledgePage>();\n  const add = (page: KnowledgePage) => {\n    if (byId.has(page.id)) return;\n    byId.set(page.id, page);\n    pages.push(page);\n  };\n  let truncated = false;\n  let queue: Array<string | null>;\n  if (rootId === null) {\n    queue = [null];\n  } else {\n    const root = await store.getPage({ id: rootId, read });\n    if (!root) return null;\n    add(root);\n    queue = [root.id];\n  }\n  // Tree parent of each walked page as the tree shows it (hoisted scopes attach to their visible parent).\n  // The walk goes a level at a time: one child-page count for the whole level, then a listing only for\n  // the parents that have children, so a tree of mostly leaf pages costs a few calls per level.\n  const treeParent = new Map<string, string>();\n  walk: while (queue.length) {\n    const level = queue;\n    queue = [];\n    const children = await graphLevelChildren(store, level, read, byId);\n    truncated ||= children.truncated;\n    for (const [i, parentId] of level.entries()) {\n      for (const child of children.byParent[i]!) {\n        if (byId.has(child.id)) continue;\n        if (pages.length >= limits.maxPages) {\n          truncated = true;\n          break walk;\n        }\n        add(child);\n        if (parentId !== null) treeParent.set(child.id, parentId);\n        queue.push(child.id);\n      }\n    }\n  }\n\n  const edges: KnowledgePageGraphEdge[] = [];\n  for (const [child, parent] of treeParent) edges.push({ source: parent, target: child, kind: 'parent' });\n\n  const walked = [...pages];\n  const noteCounts = await countInBatches(walked, ids => store.countNotes({ pageIds: ids, read }));\n  const mentionCounts = new Map<string, Map<string, number>>();\n  const outsideWanted = new Set<string>();\n  let notesLeft = limits.maxNotes;\n  notes: for (const page of walked) {\n    if (noteCounts && !noteCounts[page.id]) continue;\n    let cursor: string | undefined;\n    do {\n      if (notesLeft <= 0) {\n        truncated = true;\n        break notes;\n      }\n      const batch = await store.listNotes({ pageId: page.id, read, cursor, limit: Math.min(NOTE_BATCH, notesLeft) });\n      notesLeft -= batch.notes.length;\n      for (const note of batch.notes) {\n        for (const target of new Set(note.mentions)) {\n          if (target === page.id) continue;\n          let counts = mentionCounts.get(page.id);\n          if (!counts) mentionCounts.set(page.id, (counts = new Map()));\n          counts.set(target, (counts.get(target) ?? 0) + 1);\n          if (!byId.has(target)) outsideWanted.add(target);\n        }\n      }\n      cursor = batch.nextCursor;\n    } while (cursor);\n  }\n\n  const outsideIds: string[] = [];\n  const wanted = [...outsideWanted];\n  outside: for (let start = 0; start < wanted.length; start += MAX_KNOWLEDGE_PAGE_LIST_LIMIT) {\n    const ids = wanted.slice(start, start + MAX_KNOWLEDGE_PAGE_LIST_LIMIT);\n    const found = new Map((await store.getPages({ ids, read })).map(page => [page.id, page]));\n    for (const id of ids) {\n      const page = found.get(id);\n      if (!page || page.deletedAt || page.mergedInto) continue;\n      if (outsideIds.length >= limits.maxOutsidePages) {\n        truncated = true;\n        break outside;\n      }\n      add(page);\n      outsideIds.push(page.id);\n    }\n  }\n\n  for (const [source, counts] of mentionCounts) {\n    for (const [target, count] of counts) {\n      if (byId.has(target)) edges.push({ source, target, kind: 'mention', count });\n    }\n  }\n\n  const pinnedIds: string[] = [];\n  const ids = pages.map(page => page.id);\n  for (let start = 0; start < ids.length; start += MAX_KNOWLEDGE_PAGE_LIST_LIMIT) {\n    let cursor: string | undefined;\n    do {\n      const result = await store.listPins({\n        audience: 'all',\n        read,\n        kind: 'page',\n        pageIds: ids.slice(start, start + MAX_KNOWLEDGE_PAGE_LIST_LIMIT),\n        cursor,\n      });\n      pinnedIds.push(...result.pins.map(pin => pin.pageId));\n      cursor = result.nextCursor;\n    } while (cursor);\n  }\n\n  return { pages, outsideIds, edges, pinnedIds, truncated };\n}\n\nexport const DEFAULT_KNOWLEDGE_PAGE_SEARCH_LIMIT = 20;\n\n/** Pages (name, synopsis, body) and notes matching `query` that `read` allows, optionally within scopes. */\nexport function searchKnowledgeExplorerPages(\n  store: KnowledgePageStore,\n  input: { query: string; read: KnowledgeReadScope; scopeIds?: string[]; limit?: number },\n): Promise<KnowledgePageSearchHit[]> {\n  return store.searchPages({ ...input, limit: input.limit ?? DEFAULT_KNOWLEDGE_PAGE_SEARCH_LIMIT });\n}\n\nexport const DEFAULT_KNOWLEDGE_PAGE_ACTIVITY_LIMIT = 25;\n\n/** Activity newest first, filtered by what `read` can see now. */\nexport function readKnowledgePageActivity(\n  store: KnowledgePageStore,\n  input: { read: KnowledgeReadScope; scopeId?: string; pageId?: string; cursor?: string; limit?: number },\n): Promise<{ events: KnowledgePageActivityEvent[]; nextCursor?: string }> {\n  return store.listPageActivity({ ...input, limit: input.limit ?? DEFAULT_KNOWLEDGE_PAGE_ACTIVITY_LIMIT });\n}\n\n/** An access grant drawn between scopes in a browsing graph. @experimental */\nexport interface KnowledgeGraphScopeGrant {\n  /** The principal scope address, e.g. `role:acme:support`. */\n  principal: string;\n  /** Its scope page id, when it has one; absent for a declared principal nothing was written to yet. */\n  principalId?: string;\n  /** The granted scope's page id. */\n  target: string;\n  role: KnowledgeRole;\n}\n\n/**\n * The declared grants onto the scope pages in `pages`, for drawing who can reach what. `grantsFor` is\n * `knowledge.scopeGrants`. A principal is kept only when `read` can read its scope page; with `'all'`,\n * a declared principal with no scope page yet comes back without `principalId`.\n */\nexport async function readKnowledgeScopeGrants(\n  store: KnowledgePageStore,\n  input: {\n    pages: readonly KnowledgePage[];\n    read: KnowledgeReadScope;\n    grantsFor: (scope: { address: string; parentAddress?: string | null }) => Array<{\n      principal: string;\n      role: KnowledgeRole;\n    }>;\n  },\n): Promise<KnowledgeGraphScopeGrant[]> {\n  const { pages, read } = input;\n  const byId = new Map(pages.map(page => [page.id, page]));\n  const wanted: Array<{ principal: string; target: string; role: KnowledgeRole }> = [];\n  for (const page of pages) {\n    if (!page.isScope || !page.address || page.deletedAt || page.mergedInto) continue;\n    const parentAddress = page.parentId ? (byId.get(page.parentId)?.address ?? null) : null;\n    for (const grant of input.grantsFor({ address: page.address, parentAddress })) {\n      if (grant.principal !== page.address) wanted.push({ ...grant, target: page.id });\n    }\n  }\n  if (!wanted.length) return [];\n\n  const principals = [...new Set(wanted.map(grant => grant.principal))];\n  const scopes = new Map<string, KnowledgePage>();\n  for (let start = 0; start < principals.length; start += MAX_KNOWLEDGE_PAGE_LIST_LIMIT) {\n    for (const scope of await store.getScopesByAddress(\n      principals.slice(start, start + MAX_KNOWLEDGE_PAGE_LIST_LIMIT),\n    )) {\n      if (scope.address) scopes.set(scope.address, scope);\n    }\n  }\n  const grants: KnowledgeGraphScopeGrant[] = [];\n  for (const grant of wanted) {\n    const scope = scopes.get(grant.principal);\n    if (scope) {\n      if (knowledgeScopeReadable(scope, read)) grants.push({ ...grant, principalId: scope.id });\n    } else if (read === 'all') {\n      grants.push(grant);\n    }\n  }\n  return grants;\n}\n\n/** Most pages one {@link readKnowledgePageLinkCounts} call counts. */\nexport const MAX_KNOWLEDGE_LINK_COUNT_PAGES = 200;\n/** Most links one {@link readKnowledgePageLinks} call returns. */\nexport const MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS = 200;\n\n/**\n * How many distinct other pages link to each page (`in`) and are linked from it (`out`), by body `[[ref]]`\n * or note mention, counted by the store over every page it holds rather than only the ones a UI has\n * loaded. Pages `read` can't reach count as zero, the same as pages that don't exist. Returns `null`\n * when the store has no link index.\n */\nexport async function readKnowledgePageLinkCounts(\n  store: KnowledgePageStore,\n  input: { pageIds: string[]; read: KnowledgeReadScope },\n): Promise<Record<string, KnowledgePageLinkCounts> | null> {\n  const pageIds = [...new Set(input.pageIds)].slice(0, MAX_KNOWLEDGE_LINK_COUNT_PAGES);\n  if (pageIds.length === 0) return {};\n  try {\n    return await store.countPageLinks({ pageIds, read: input.read });\n  } catch (error) {\n    if (error instanceof KnowledgeUnsupportedCapabilityError) return null;\n    throw error;\n  }\n}\n\n/** One page's links, with the pages at their other ends so a UI can name and place them. */\nexport interface KnowledgePageLinks {\n  edges: KnowledgePageLinkEdge[];\n  /** The pages at the other end of `edges` that `read` can reach. */\n  pages: KnowledgePage[];\n  /** True when the page has more links than {@link MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS}. */\n  truncated: boolean;\n}\n\n/**\n * The links into and out of one readable page, by body `[[ref]]` or note mention. A page `read` can't\n * reach has none. Returns `null` when the store has no link index.\n */\nexport async function readKnowledgePageLinks(\n  store: KnowledgePageStore,\n  input: { pageId: string; read: KnowledgeReadScope; direction?: 'in' | 'out' | 'both' },\n): Promise<KnowledgePageLinks | null> {\n  if (!(await store.getPage({ id: input.pageId, read: input.read }))) return { edges: [], pages: [], truncated: false };\n  let listed: KnowledgePageLinkEdge[];\n  try {\n    listed = await store.listPageLinks({\n      pageIds: [input.pageId],\n      read: input.read,\n      direction: input.direction ?? 'both',\n      limit: MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS + 1,\n    });\n  } catch (error) {\n    if (error instanceof KnowledgeUnsupportedCapabilityError) return null;\n    throw error;\n  }\n  const truncated = listed.length > MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS;\n  const edges = listed.slice(0, MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS);\n  const others = [\n    ...new Set(edges.flatMap(edge => [edge.fromPageId, edge.toPageId]).filter(id => id !== input.pageId)),\n  ];\n  const pages: KnowledgePage[] = [];\n  for (let start = 0; start < others.length; start += MAX_KNOWLEDGE_PAGE_LIST_LIMIT) {\n    pages.push(\n      ...(await store.getPages({ ids: others.slice(start, start + MAX_KNOWLEDGE_PAGE_LIST_LIMIT), read: input.read })),\n    );\n  }\n  return { edges, pages, truncated };\n}\n","import { randomUUID } from 'node:crypto';\nimport { MastraBase } from '../base';\nimport type { Mastra } from '../mastra';\nimport type { MastraCompositeStore } from '../storage';\nimport type { KnowledgeReadScope, KnowledgeStorage } from '../storage/domains/knowledge';\nimport type { KnowledgeNote, KnowledgePage } from '../storage/domains/knowledge/pages';\nimport { augmentWithInit, getStorageSource } from '../storage/storageWithInit';\nimport type { ToolAction } from '../tools';\nimport { knowledgeAccessGrants } from './access';\nimport { emitKnowledgeChanges } from './changes';\nimport type { KnowledgeChangeEvent, KnowledgeChangeListener } from './changes';\nimport type { KnowledgeConfig } from './config';\nimport { KnowledgeDeclarationError, strongerKnowledgeRole } from './declarations';\nimport type {\n  KnowledgeRole,\n  KnowledgeScopeDeclaration as ScopeDeclaration,\n  KnowledgeScopeDeclarationInfo,\n} from './declarations';\nimport {\n  addKnowledgeNote,\n  moveKnowledgePage,\n  removeKnowledgeNote,\n  removeKnowledgePage,\n  updateKnowledgeNote,\n  upsertKnowledgePage,\n} from './host-writes';\nimport type {\n  KnowledgeAddNoteInput,\n  KnowledgeMovePageInput,\n  KnowledgeRemovePageInput,\n  KnowledgeUpdateNoteInput,\n  KnowledgeUpsertPageInput,\n  KnowledgeUpsertPageResult,\n} from './host-writes';\nimport { buildKnowledgeInstructions } from './instructions';\nimport type { KnowledgeInstructionsOption } from './instructions';\nimport { reindexKnowledgeLinks } from './links';\nimport { buildKnowledgePageTools } from './page-tools';\nimport { DEFAULT_MAX_PINS, DEFAULT_PINNED_MAX_TOKENS, knowledgeDeliveredPins } from './pinned';\nimport type { PinBudget, PinEntry } from './pinned';\nimport { PINNED_READ_MEMO_KEY } from './pinned-state-processor';\nimport { reembedKnowledge } from './reembed';\nimport type { KnowledgeReembedOptions, KnowledgeReembedResult } from './reembed';\nimport { KnowledgeRun, knowledgeRunPrincipals } from './run';\nimport type { KnowledgeRunContext } from './run';\nimport { KnowledgeScopeRuntime } from './scope-runtime';\nimport type { KnowledgeAccessExplanation } from './scope-runtime';\n\nfunction resolvePins(pins: KnowledgeConfig['pinnedContext']): false | PinBudget {\n  if (!pins) return false;\n  const options = pins === true ? {} : pins;\n  return {\n    maxPins: options.maxPins ?? DEFAULT_MAX_PINS,\n    maxTokens: options.maxTokens ?? DEFAULT_PINNED_MAX_TOKENS,\n  };\n}\n\n/** Below this share of the pin budget each, config pins are too cut down to be useful. */\nconst MIN_TOKENS_PER_CONFIG_PIN = 50;\n\n/** Overrides which tool groups `createTools` and `getInstructions` cover. */\ntype KnowledgeToolSelection = { read?: boolean; write?: boolean; pinnedContext?: boolean };\n\n/** @experimental Knowledge APIs are experimental and may change without notice. */\nexport class Knowledge extends MastraBase {\n  readonly id: string;\n  readonly hasOwnStorage: boolean;\n\n  readonly description?: string;\n\n  #storage?: MastraCompositeStore;\n  #storageSource?: MastraCompositeStore;\n  #storagePromise?: Promise<KnowledgeStorage>;\n  #runtime: KnowledgeScopeRuntime;\n  #tools: { read: boolean; write: boolean; maxTokens?: number };\n  #pins: false | PinBudget;\n  #instructions?: KnowledgeInstructionsOption;\n  #semantic?: KnowledgeSemanticIndex;\n  #listeners = new Set<KnowledgeChangeListener>();\n\n  /** Config pins are never dropped, so a scope with more of them than the budget holds is a setup mistake. */\n  #warnOnPinOvercommit(budget: PinBudget) {\n    const { declarations, concrete } = this.#runtime.compiled;\n    const entries: Array<[string, ScopeDeclaration['pinnedContext']]> = [\n      ...[...declarations.values()].map(\n        compiled => [compiled.key, compiled.declaration.pinnedContext] as [string, ScopeDeclaration['pinnedContext']],\n      ),\n      ...[...concrete].map(\n        ([address, entry]) => [address, entry.declaration.pinnedContext] as [string, ScopeDeclaration['pinnedContext']],\n      ),\n    ];\n    for (const [key, pins] of entries) {\n      const count = pins?.length ?? 0;\n      if (count === 0) continue;\n      if (count > budget.maxPins || budget.maxTokens / count < MIN_TOKENS_PER_CONFIG_PIN) {\n        this.logger.warn(\n          `Knowledge scope \"${key}\" has ${count} pinnedContext pages for a budget of ${budget.maxPins} pins / ${budget.maxTokens} tokens; pinnedContext pages are never dropped, so each will be cut to about ${Math.floor(budget.maxTokens / count)} tokens and stored pins won't fit. Pin fewer pages or raise pinnedContext.maxTokens.`,\n        );\n      }\n    }\n  }\n\n  constructor(config: KnowledgeConfig) {\n    super({ component: 'STORAGE', name: config?.name ?? config?.id ?? 'Knowledge' });\n    if (!config?.scopes || typeof config.scopes !== 'object') {\n      throw new KnowledgeDeclarationError(\n        'Knowledge needs `scopes`: declare the scopes its runs hold, e.g. `scopes: { ...knowledgeMemoryScopes() }`, or `{}` for none.',\n      );\n    }\n    this.id = config.id ?? randomUUID();\n    this.description = config.description;\n    const tools = config.tools;\n    this.#tools =\n      typeof tools === 'object'\n        ? {\n            read: Boolean(tools.read),\n            write: Boolean(tools.write),\n            maxTokens: typeof tools.read === 'object' ? tools.read.maxTokens : undefined,\n          }\n        : { read: Boolean(tools), write: Boolean(tools) };\n    const maxTokens = this.#tools.maxTokens;\n    if (maxTokens !== undefined && (!Number.isInteger(maxTokens) || maxTokens < 100)) {\n      throw new Error(`Knowledge \\`tools.read.maxTokens\\` must be a whole number of at least 100; got ${maxTokens}.`);\n    }\n    this.#pins = resolvePins(config.pinnedContext);\n    this.#instructions = config.instructions;\n    if (Boolean(config.vector) !== Boolean(config.embedder)) {\n      throw new Error('Knowledge semantic search needs both `vector` and `embedder`; pass both or neither.');\n    }\n    if (config.vector && config.embedder) {\n      this.#semantic = new KnowledgeSemanticIndex(config.vector, config.embedder, config.embedderOptions);\n    }\n    this.#runtime = new KnowledgeScopeRuntime(\n      config.scopes,\n      () => this.getStorage(),\n      message => this.logger.warn(message),\n    );\n    if (this.#pins) this.#warnOnPinOvercommit(this.#pins);\n    this.hasOwnStorage = config.storage !== undefined;\n    if (config.storage) {\n      this.#storageSource = getStorageSource(config.storage);\n      this.#storage = augmentWithInit(config.storage);\n    }\n  }\n\n  /**\n   * What a holder of `principals` reads: the principals themselves plus every scope their declared\n   * rules reach in one hop. Undeclared principals throw; an empty list reads nothing. Never `'all'`.\n   * Pass the result as `read` to the store's read methods.\n   */\n  async readScopeFor(principals: readonly string[]): Promise<KnowledgeReadScope> {\n    await this.#runtime.resolve();\n    return this.#runtime.readScopeFor(principals);\n  }\n\n  /**\n   * Why a run holding `runScopes` can or can't reach a scope or page: its role there and the rules\n   * that give it. `runScopes` are canonical run scopes, as passed to an agent run; undeclared ones throw\n   * like they do at run start. `target` is a scope address, or a page id or `<scope>#<key>[/<key>…]`.\n   *\n   * **Host-only.** It tells a missing page from a hidden one, which runs must never learn. Never\n   * expose it through an agent tool, or through a server route without admin-level auth.\n   *\n   * @experimental\n   */\n  async explainAccess(\n    runScopes: readonly string[],\n    target: { scope: string } | { page: string },\n  ): Promise<KnowledgeAccessExplanation> {\n    await this.#runtime.resolve();\n    return this.#runtime.explainAccess(runScopes, target);\n  }\n\n  /**\n   * Who the declared rules give a role on one scope: each principal scope address (bound for this\n   * scope's params) with its strongest role, `self` rules left out. `parentAddress` is the\n   * address of the scope page's tree parent, needed for rules that bind through `belongsTo`. Reads the\n   * declarations as last resolved, not storage. For browsing UIs that draw access between scopes.\n   *\n   * @experimental\n   */\n  scopeGrants(scope: { address: string; parentAddress?: string | null }): KnowledgeScopeGrant[] {\n    const strongest = new Map<string, KnowledgeRole>();\n    for (const grant of knowledgeAccessGrants(this.#runtime.compiled, 'any', scope)) {\n      if (grant.via === 'self') continue;\n      strongest.set(grant.principal, strongerKnowledgeRole(strongest.get(grant.principal) ?? null, grant.role));\n    }\n    return [...strongest].map(([principal, role]) => ({ principal, role }));\n  }\n\n  /**\n   * After renaming a scope declaration key in `scopes`, moves the scopes stored under the old key\n   * (and its template children, `from/<name>`) to the new one, in one atomic step. Until then this\n   * instance refuses to run: stored scopes under an undeclared key would otherwise silently lose\n   * prefix and `belongsTo` reach. Refuses when `from` is still declared, `to` isn't, or any stored\n   * address doesn't match the `to` pattern; nothing changes then. Returns how many scopes moved.\n   *\n   * In a rolling deploy, instances with the new config fail until the rename runs, and instances\n   * still on the old config lose reach to those scopes after it; deploy, then rename right away.\n   *\n   * @experimental\n   */\n  async renameScopeDeclaration(from: string, to: string): Promise<number> {\n    await this.#runtime.resolve();\n    return this.#runtime.renameScopeDeclaration(from, to);\n  }\n\n  #groups(override?: KnowledgeToolSelection): { read: boolean; write: boolean; pins: boolean } {\n    const pinnedContext = override?.pinnedContext;\n    return {\n      read: override?.read ?? this.#tools.read,\n      write: override?.write ?? this.#tools.write,\n      pins: pinnedContext ?? this.#pins !== false,\n    };\n  }\n\n  /** Tools for explicit wiring; defaults to the groups configured on this Knowledge. */\n  createTools(options?: KnowledgeToolSelection): Record<string, ToolAction<any, any, any>> {\n    return buildKnowledgePageTools(\n      {\n        runtime: this.#runtime,\n        getStorage: () => this.getStorage(),\n        semantic: this.#semantic,\n        warn: message => this.logger.warn(message),\n        maxTokens: this.#tools.maxTokens,\n      },\n      this.#groups(options),\n      // A pin write changes what the pins lane shows; drop the turn's memoized read.\n      context =>\n        (\n          context as KnowledgeRunContext & { requestContext?: { delete?(key: string): void } }\n        )?.requestContext?.delete?.(PINNED_READ_MEMO_KEY),\n    );\n  }\n\n  /**\n   * Creates or updates the page at `scope#path`, for apps that sync content in from outside an agent\n   * run (a docs site, a CMS). The path is the page's identity, so running a sync again updates the\n   * same pages; an unchanged page is not written. Notes on the page are kept. The page is embedded\n   * when Knowledge has `vector` and `embedder`, and change listeners are told.\n   *\n   * **Host-only.** No run scopes and no access rules are checked; who reads the page is decided by\n   * the scope's access rules as usual (`explainAccess` explains run access, not host writes). Never\n   * expose it through an agent tool, or through a server route without admin-level auth. A scope\n   * first created here gets its `belongsTo` parent when a run holding that parent first uses it.\n   *\n   * @experimental\n   */\n  upsertPage(input: KnowledgeUpsertPageInput): Promise<KnowledgeUpsertPageResult> {\n    return upsertKnowledgePage(this.#hostWriter(), input);\n  }\n\n  /**\n   * Deletes the page at `scope#path`; `null` when there is none. Refuses a page with child pages\n   * and a page declared in config. Host-only, like {@link Knowledge.upsertPage}. Not retried: a\n   * concurrent write to the same page between the read and the delete throws, so remove from one\n   * sync worker or retry the call.\n   *\n   * @experimental\n   */\n  removePage(input: KnowledgeRemovePageInput): Promise<KnowledgePage | null> {\n    return removeKnowledgePage(this.#hostWriter(), input);\n  }\n\n  /**\n   * Moves the page at `scope#path`, with its subtree, under the page at `parent` (a key path; left\n   * out, the top of the scope), in `toScope` when given. The page keeps its id, notes, pins and\n   * vectors; paths below it change, and links by path are re-resolved. Throws\n   * `KnowledgeNotFoundError` for a missing page or parent, and refuses a page declared in config, a\n   * move into its own subtree, a key the new parent already has, and a move past the depth limit.\n   * Host-only, like {@link Knowledge.upsertPage}. Not retried: a concurrent write to the page\n   * between the read and the move throws.\n   *\n   * @experimental\n   */\n  movePage(input: KnowledgeMovePageInput): Promise<KnowledgePage> {\n    return moveKnowledgePage(this.#hostWriter(), input);\n  }\n\n  /**\n   * Adds a note to the page at `scope#path`; throws when there is no page there. Readers of the\n   * `stamps` scopes (default: the page's scope) see it. Keep the returned id to edit or remove it.\n   * Host-only, like {@link Knowledge.upsertPage}.\n   *\n   * @experimental\n   */\n  addNote(input: KnowledgeAddNoteInput): Promise<KnowledgeNote> {\n    return addKnowledgeNote(this.#hostWriter(), input);\n  }\n\n  /**\n   * Replaces a note's text. Notes are immutable, so this adds the new note and then removes the old\n   * one: the result has a **new id**. If removing the old note fails after the add, both exist;\n   * call `removeNote` with the old id. Host-only, like {@link Knowledge.upsertPage}.\n   *\n   * @experimental\n   */\n  updateNote(input: KnowledgeUpdateNoteInput): Promise<KnowledgeNote> {\n    return updateKnowledgeNote(this.#hostWriter(), input);\n  }\n\n  /**\n   * Removes a note; `null` when it is already gone. Host-only, like {@link Knowledge.upsertPage}.\n   *\n   * @experimental\n   */\n  removeNote(input: { id: string; author?: string }): Promise<KnowledgeNote | null> {\n    return removeKnowledgeNote(this.#hostWriter(), input);\n  }\n\n  #hostWriter() {\n    return {\n      runtime: this.#runtime,\n      getStorage: () => this.getStorage(),\n      semantic: this.#semantic,\n      warn: (message: string) => this.logger.warn(message),\n    };\n  }\n\n  /**\n   * Rebuilds the page link index from every page body, for pages written before the index existed\n   * or straight to the store. Needs no vector store. Returns how many pages were indexed.\n   *\n   * @experimental\n   */\n  async reindexLinks(): Promise<number> {\n    return reindexKnowledgeLinks(await this.getStorage());\n  }\n\n  /**\n   * Embeds pages and notes that already exist, without changing them: content written before a\n   * `vector` and `embedder` were configured, or before switching embedders. Each call handles up to\n   * `limit` pages (default 50, at most 500) with their notes and returns `nextCursor`; pass it to the\n   * next call until it's absent. Handling a page again overwrites its vectors, so a run can stop and\n   * resume. Failures are listed, not thrown; if the embedder keeps rate limiting, the call stops\n   * early with `rateLimited: true` and a cursor that resumes where it stopped, mid-page if need be; wait before resuming. The\n   * cursor is not a snapshot: pages added or removed during a run can be missed or handled twice, and\n   * a page read before a concurrent edit can overwrite the vectors that edit wrote, so rerun after\n   * concurrent writes finish. Throws without `vector` and `embedder`.\n   *\n   * @experimental\n   */\n  async reembed(options?: KnowledgeReembedOptions): Promise<KnowledgeReembedResult> {\n    if (!this.#semantic) throw new Error('Knowledge has no `vector` and `embedder` to embed into.');\n    return reembedKnowledge(await this.getStorage(), this.#semantic, options);\n  }\n\n  /** The usage block that goes with `createTools(options)`. */\n  getInstructions(options?: KnowledgeToolSelection): string {\n    return buildKnowledgeInstructions(this.#groups(options), this.#instructions);\n  }\n\n  /** Whether attached agents get pinned context delivered every turn. */\n  get pinnedContextEnabled(): boolean {\n    return this.#pins !== false;\n  }\n\n  /** The run's principals as a stable key; throws when the run has none or holds an undeclared scope. @internal */\n  __principalsKey(context: KnowledgeRunContext): string {\n    return knowledgeRunPrincipals(this.#runtime, context).sort().join('\\n');\n  }\n\n  /** The pinned pages a run receives this turn. @internal */\n  async __deliveredPins(context: KnowledgeRunContext): Promise<PinEntry[]> {\n    const budget = this.#pins || resolvePins(true);\n    if (!budget) return [];\n    const run = await KnowledgeRun.start(this.#runtime, await this.getStorage(), context);\n    return knowledgeDeliveredPins(run, budget);\n  }\n\n  /** @internal */\n  __registerMastra(_mastra: Mastra): void {}\n\n  /** @internal */\n  __sharesStorageWith(other: Knowledge): boolean {\n    if (!this.#storageSource || !other.#storageSource) return false;\n    if (this.#storageSource === other.#storageSource) return true;\n\n    const domain = this.#storageSource.stores?.knowledge;\n    const otherDomain = other.#storageSource.stores?.knowledge;\n    return (\n      domain !== undefined &&\n      otherDomain !== undefined &&\n      domain.getStorageIsolationKey() === otherDomain.getStorageIsolationKey()\n    );\n  }\n\n  /** @internal */\n  __usesStorage(storage: MastraCompositeStore): boolean {\n    const source = getStorageSource(storage);\n    if (this.#storageSource === source) return true;\n\n    const domain = this.#storageSource?.stores?.knowledge;\n    const sourceDomain = source.stores?.knowledge;\n    return (\n      domain !== undefined &&\n      sourceDomain !== undefined &&\n      domain.getStorageIsolationKey() === sourceDomain.getStorageIsolationKey()\n    );\n  }\n\n  /** @internal */\n  setStorage(storage: MastraCompositeStore, source: MastraCompositeStore = storage): void {\n    if (this.hasOwnStorage) return;\n    this.#storageSource = getStorageSource(source);\n    this.#storage = augmentWithInit(storage);\n    this.#storagePromise = undefined;\n  }\n\n  async getStorage(): Promise<KnowledgeStorage> {\n    if (!this.#storagePromise) {\n      const promise = this.#resolveStorage().catch(error => {\n        if (this.#storagePromise === promise) {\n          this.#storagePromise = undefined;\n        }\n        throw error;\n      });\n      this.#storagePromise = promise;\n    }\n    return this.#storagePromise;\n  }\n\n  async #resolveStorage(): Promise<KnowledgeStorage> {\n    if (!this.#storage) {\n      throw new Error(\n        'Knowledge requires a storage provider. Configure storage on the Knowledge instance or on the owning Mastra instance.',\n      );\n    }\n    const storage = await this.#storage.getStore('knowledge');\n    if (!storage) {\n      throw new Error('The configured storage provider does not provide a Knowledge storage domain.');\n    }\n    return emitKnowledgeChanges(\n      storage,\n      change => this.#emit(change),\n      () => this.#listeners.size > 0,\n      error => this.logger.error('Knowledge change event failed after a committed write', { error }),\n    );\n  }\n\n  #emit(change: Omit<KnowledgeChangeEvent, 'knowledgeId' | 'at'>) {\n    if (this.#listeners.size === 0) return;\n    const event = { ...change, knowledgeId: this.id, at: new Date() } as KnowledgeChangeEvent;\n    for (const listener of this.#listeners) {\n      try {\n        listener(event);\n      } catch (error) {\n        this.logger.error('Knowledge change listener threw', { error });\n      }\n    }\n  }\n\n  /**\n   * Calls `listener` after each committed write made through this instance's store\n   * (`getStorage()`): tool writes, host writes and scope creation. Writes made on a store obtained\n   * some other way aren't seen. Events carry ids, not content and not access: anything that relays\n   * them to people must re-read each page under that person's read scope. Returns an unsubscribe.\n   */\n  onChange(listener: KnowledgeChangeListener): () => void {\n    this.#listeners.add(listener);\n    return () => {\n      this.#listeners.delete(listener);\n    };\n  }\n\n  /**\n   * The declaration a scope page was created from, by its `declaration` key (template children\n   * included, e.g. `account:$orgId:$accountId/internal`), for display. Access rules are left out;\n   * use `explainAccess` for those. `undefined` for an unknown key.\n   */\n  scopeDeclaration(key: string): KnowledgeScopeDeclarationInfo | undefined {\n    const compiled = this.#runtime.compiled.declarations.get(key);\n    if (!compiled) return undefined;\n    const { description, displayLabel, belongsTo } = compiled.declaration;\n    return {\n      key,\n      ...(description !== undefined && { description }),\n      ...(displayLabel !== undefined && { displayLabel }),\n      ...(belongsTo !== undefined && { belongsTo }),\n      children: compiled.children.map(child => ({\n        key: child.key,\n        name: child.child!.name,\n        ...(child.declaration.description !== undefined && { description: child.declaration.description }),\n        ...(child.declaration.displayLabel !== undefined && { displayLabel: child.declaration.displayLabel }),\n      })),\n    };\n  }\n\n  /**\n   * The display label for a canonical scope address (template children included), with the\n   * declaration's `$params` filled in from the address's decoded values: `'$orgId policy'` on\n   * `policy:$orgId` gives `'acme policy'` for `policy:acme`. A concrete address's own `displayLabel`\n   * wins over its pattern's. `undefined` when the address matches no declaration or has no label.\n   */\n  scopeLabel(address: string): string | undefined {\n    const match = this.#runtime.compiled.match(address);\n    const label = match?.concrete?.displayLabel ?? match?.compiled.declaration.displayLabel;\n    if (label === undefined) return undefined;\n    return label.replace(/\\$([A-Za-z_][A-Za-z0-9_]*)/g, (token, name: string) =>\n      Object.hasOwn(match!.params, name) ? match!.params[name]! : token,\n    );\n  }\n}\n\nexport * from '../storage/domains/knowledge';\nexport type { KnowledgeInstructionParts, KnowledgeInstructionsOption } from './instructions';\n/** Read-only readers over the schema-4 page store, for browsing UIs. */\nexport {\n  DEFAULT_KNOWLEDGE_PAGE_GRAPH_LIMITS,\n  listKnowledgeTreeChildren,\n  MAX_KNOWLEDGE_EXPLORER_PAGE_LINKS,\n  MAX_KNOWLEDGE_LINK_COUNT_PAGES,\n  readKnowledgePage,\n  readKnowledgePageLinkCounts,\n  readKnowledgePageLinks,\n  readKnowledgePageActivity,\n  readKnowledgePageGraph,\n  readKnowledgeScopeGrants,\n  searchKnowledgeExplorerPages,\n} from './explorer-pages';\nexport type {\n  KnowledgeGraphScopeGrant,\n  KnowledgePageGraph,\n  KnowledgePageGraphEdge,\n  KnowledgePageGraphLimits,\n  KnowledgePageLinks,\n  KnowledgePageView,\n  KnowledgeTreeChildren,\n  KnowledgeTreePage,\n} from './explorer-pages';\nexport type { KnowledgeConfig } from './config';\nexport { knowledgeScopeAddress, knowledgeMemoryScopes, KnowledgeDeclarationError } from './declarations';\nexport { decodeKnowledgeScopeId, encodeKnowledgeScopeId } from './scope-address';\nexport type {\n  KnowledgePageTemplate,\n  KnowledgePinnedList,\n  KnowledgeScopeDeclaration,\n  KnowledgeScopeDeclarationInfo,\n  KnowledgeScopeDeclarations,\n  KnowledgeAccessRule,\n  KnowledgeRole,\n} from './declarations';\nimport { KnowledgeSemanticIndex } from './semantic';\nexport type { KnowledgeAccessExplanation } from './scope-runtime';\nexport type { KnowledgeAccessGrant } from './access';\n\n/** One principal scope's strongest declared role on a scope. See {@link Knowledge.scopeGrants}. @experimental */\nexport interface KnowledgeScopeGrant {\n  /** The principal scope address, e.g. `role:acme:support`. */\n  principal: string;\n  role: KnowledgeRole;\n}\nexport type { KnowledgeChangeEvent, KnowledgeChangeListener } from './changes';\nexport type { KnowledgeReembedOptions, KnowledgeReembedResult } from './reembed';\nexport type {\n  KnowledgeAddNoteInput,\n  KnowledgeMovePageInput,\n  KnowledgeRemovePageInput,\n  KnowledgeUpdateNoteInput,\n  KnowledgeUpsertPageInput,\n  KnowledgeUpsertPageResult,\n} from './host-writes';\n"],"mappings":";;;;;AAuCA,MAAM,QAAQ,QAAwC,WAAoB;CACxE,MAAM,EAAE,IAAI,YAAY;CACxB,OAAO;EAAE,MAAM;EAAQ;EAAI,QAAQ;EAAI;CAAQ;AACjD;AACA,MAAM,QAAQ,QAAkD,WAAoB;CAClF,MAAM,EAAE,IAAI,WAAW;CACvB,OAAO;EAAE,MAAM;EAAQ;EAAI;EAAQ,QAAQ;CAAG;AAChD;;AAKA,MAAM,SAAmC;CACvC,mBAAkB,WAAU;EAC1B,MAAM,EAAE,OAAO,YAAY;EAC3B,OAAO,UAAU;GAAE,MAAM;GAAS,IAAI;GAAU,QAAQ,MAAM;GAAI,SAAS,MAAM;EAAG,IAAI;CAC1F;CACA,YAAY,KAAK,QAAQ;CACzB,YAAY,KAAK,QAAQ;CACzB,WAAW,QAAQ,QAAQ,gBAAgB;EACzC,MAAM,EAAE,IAAI,YAAY;EACxB,OAAO;GAAE,MAAM;GAAQ,IAAI;GAAQ,QAAQ;GAAI;GAAS;EAAY;CACtE;CACA,YAAY,KAAK,QAAQ;CACzB,aAAa,QAAQ,OAA6B,gBAAgB;EAChE,MAAM,EAAE,IAAI,YAAY;EACxB,OAAO;GAAE,MAAM;GAAQ,IAAI;GAAS,QAAQ;GAAI;GAAS,UAAU,MAAM;GAAU;EAAY;CACjG;CACA,SAAS,KAAK,KAAK;CACnB,aAAa,KAAK,SAAS;CAC3B,YAAY,KAAK,QAAQ;CACzB,aAAa,KAAK,SAAS;CAC3B,iBAAgB,YAAW;EAAE,MAAM;EAAO,IAAI;EAAO,QAAS,OAAwB;CAAO;CAC7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