@mastra/pg 1.34.0-alpha.1 → 1.35.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
2
2
  import * as coreStorage from "@mastra/core/storage";
3
- import { AgentsStorage, BRANCH_SPAN_TYPES, BackgroundTasksStorage, BlobStore, ChannelsStorage, DATASETS_SCHEMA, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, DatasetsStorage, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, EntityType, ExperimentsStorage, FactoryStorage, FavoritesStorage, KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA, KnowledgeConflictError, KnowledgeNotFoundError, KnowledgeStorage, MCPClientsStorage, MCPServersStorage, METRIC_DISTINCT_COLUMNS, MastraCompositeStore, MemoryStorage, NotificationsStorage, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, ObservabilityStorage, PromptBlocksStorage, RUN_FENCING_TABLE_SCHEMAS, RunFenceConflictError, SchedulesStorage, ScorerDefinitionsStorage, ScoresStorage, SkillsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_BACKGROUND_TASKS, TABLE_CHANNEL_CONFIG, TABLE_CHANNEL_INSTALLATIONS, TABLE_CONFIGS, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, TABLE_FAVORITES, TABLE_KNOWLEDGE_ACTIVITY, TABLE_KNOWLEDGE_MENTIONS, TABLE_KNOWLEDGE_NODES, TABLE_KNOWLEDGE_RECORDS, TABLE_KNOWLEDGE_SEMANTIC_OUTBOX, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, TABLE_MEMORY_RUN_FENCES, TABLE_MESSAGES, TABLE_NOTIFICATIONS, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, TABLE_RESOURCES, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, TABLE_SKILLS, TABLE_SKILL_BLOBS, TABLE_SKILL_VERSIONS, TABLE_SPANS, TABLE_THREADS, TABLE_THREAD_STATE, TABLE_TOOL_PROVIDER_CONNECTIONS, TABLE_WORKFLOW_DEFINITIONS, TABLE_WORKFLOW_RUN_OWNERS, TABLE_WORKFLOW_SNAPSHOT, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, ThreadStateStorage, ToolProviderConnectionsStorage, TraceStatus, UniqueViolationError, WorkflowDefinitionsStorage, WorkflowsStorage, WorkspacesStorage, assertWorkflowStepGuard, calculatePagination, canonicalizeKnowledgeScope, computeTraceStatus, createKnowledgeUlid, createStorageErrorId, createVectorErrorId, ensureDate, executeRetentionPrune, getDefaultValue, getSqlType, getStringAttribute, hasErrorCode, isKnowledgeScopeVisible, isRunFenceConflictError, isWorkflowStepConflictError, knowledgeScopeKey, knowledgeSemanticDocumentId, knowledgeSemanticIdempotencyKey, listBranchesArgsSchema, listFeedbackArgsSchema, listLogsArgsSchema, listMetricsArgsSchema, listScoresArgsSchema, listTracesArgsSchema, matchesExpectedWorkflowStatus, matchesRunFence, mergeWorkflowStepResult, normalizePerPage, normalizeScheduleTarget, parseDuration, parseKnowledgeNodeCursor, parseKnowledgeWikilinks, resolveListOrderBy, resolveRetentionTargets, resolveRunFence, retentionCutoffMs, runRetentionBatches, safelyParseJSON, storageMessageMatchesMetadataFilter, toTraceSpans, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
3
+ import { AgentsStorage, BRANCH_SPAN_TYPES, BackgroundTasksStorage, BlobStore, ChannelsStorage, DATASETS_SCHEMA, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, DatasetsStorage, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, EntityType, ExperimentsStorage, FactoryStorage, FavoritesStorage, KnowledgeConflictError, KnowledgeNotFoundError, KnowledgeStorage, MCPClientsStorage, MCPServersStorage, METRIC_DISTINCT_COLUMNS, MastraCompositeStore, MemoryStorage, NotificationsStorage, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, ObservabilityStorage, PromptBlocksStorage, RUN_FENCING_TABLE_SCHEMAS, RunFenceConflictError, SchedulesStorage, ScorerDefinitionsStorage, ScoresStorage, SkillsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_BACKGROUND_TASKS, TABLE_CHANNEL_CONFIG, TABLE_CHANNEL_INSTALLATIONS, TABLE_CONFIGS, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, TABLE_FAVORITES, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, TABLE_MEMORY_RUN_FENCES, TABLE_MESSAGES, TABLE_NOTIFICATIONS, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, TABLE_RESOURCES, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, TABLE_SCHEMAS, TABLE_SCORERS, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, TABLE_SKILLS, TABLE_SKILL_BLOBS, TABLE_SKILL_VERSIONS, TABLE_SPANS, TABLE_THREADS, TABLE_THREAD_STATE, TABLE_TOOL_PROVIDER_CONNECTIONS, TABLE_WORKFLOW_DEFINITIONS, TABLE_WORKFLOW_RUN_OWNERS, TABLE_WORKFLOW_SNAPSHOT, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, ThreadStateStorage, ToolProviderConnectionsStorage, TraceStatus, UniqueViolationError, WorkflowDefinitionsStorage, WorkflowsStorage, WorkspacesStorage, assertWorkflowStepGuard, calculatePagination, computeTraceStatus, createKnowledgeUlid, createStorageErrorId, createVectorErrorId, ensureDate, executeRetentionPrune, getDefaultValue, getSqlType, getStringAttribute, hasErrorCode, isRunFenceConflictError, isWorkflowStepConflictError, listBranchesArgsSchema, listFeedbackArgsSchema, listLogsArgsSchema, listMetricsArgsSchema, listScoresArgsSchema, listTracesArgsSchema, matchesExpectedWorkflowStatus, matchesRunFence, mergeWorkflowStepResult, normalizePerPage, normalizeScheduleTarget, parseDuration, resolveListOrderBy, resolveRetentionTargets, resolveRunFence, retentionCutoffMs, runRetentionBatches, safelyParseJSON, storageMessageMatchesMetadataFilter, toTraceSpans, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
4
4
  import { parseFieldKey, parseSqlIdentifier } from "@mastra/core/utils";
5
5
  import { MastraVector, validateTopK, validateUpsertInput } from "@mastra/core/vector";
6
6
  import { Mutex } from "async-mutex";
@@ -10,7 +10,7 @@ import xxhash from "xxhash-wasm";
10
10
  import { parse } from "pg-connection-string";
11
11
  import { BaseFilterTranslator } from "@mastra/core/vector/filter";
12
12
  import { MastraBase } from "@mastra/core/base";
13
- import { createHash, randomUUID } from "crypto";
13
+ import { createHash } from "crypto";
14
14
  import { setTimeout as setTimeout$1 } from "timers/promises";
15
15
  import { coreFeatures } from "@mastra/core/features";
16
16
  import { MessageList } from "@mastra/core/agent";
@@ -387,7 +387,7 @@ const FILTER_OPERATORS = {
387
387
  return {
388
388
  sql,
389
389
  needsValue: true,
390
- transformValue: () => Array.isArray(value) ? value.map(String) : typeof value === "string" ? escapeLikePattern$1(value) : value
390
+ transformValue: () => Array.isArray(value) ? value.map(String) : typeof value === "string" ? escapeLikePattern(value) : value
391
391
  };
392
392
  },
393
393
  /**
@@ -411,7 +411,7 @@ const FILTER_OPERATORS = {
411
411
  const parseJsonPathKey = (key) => {
412
412
  return (key !== "" ? parseFieldKey(key) : "").replace(/\./g, ",");
413
413
  };
414
- function escapeLikePattern$1(str) {
414
+ function escapeLikePattern(str) {
415
415
  return str.replace(/([%_\\])/g, "\\$1");
416
416
  }
417
417
  /**
@@ -1080,42 +1080,43 @@ var PgVector = class extends MastraVector {
1080
1080
  const scoreExpr = ops.scoreExpr(distanceExpr);
1081
1081
  const filterClause = filterQuery.trim().replace(/^WHERE\s+/i, "");
1082
1082
  const hasFilter = filterClause.length > 0;
1083
- const useIndexedOrder = indexInfo.type === "hnsw" && !hasFilter && minScore <= 0;
1084
1083
  const namespaceParam = filterValues.length + 1;
1085
- const query = useIndexedOrder ? `
1084
+ const queryValues = [...filterValues, namespace];
1085
+ const selectColumns = `vector_id as id, ${scoreExpr} as score, metadata${includeVector ? ", embedding" : ""}`;
1086
+ const whereClause = `WHERE namespace = $${namespaceParam}${filterClause ? ` AND (${filterClause})` : ""}`;
1087
+ const useIndexedOrder = indexInfo.type === "hnsw" && (!hasFilter || this.supportsIterativeScan());
1088
+ let rows;
1089
+ if (useIndexedOrder) {
1090
+ const indexedQuery = `
1086
1091
  WITH vector_scores AS (
1087
- SELECT
1088
- vector_id as id,
1089
- ${scoreExpr} as score,
1090
- metadata
1091
- ${includeVector ? ", embedding" : ""}
1092
+ SELECT ${selectColumns}
1092
1093
  FROM ${tableName}
1093
- WHERE namespace = $${namespaceParam}
1094
+ ${whereClause}
1094
1095
  ORDER BY ${distanceExpr}
1095
1096
  LIMIT $2
1096
1097
  )
1097
- SELECT *
1098
+ SELECT *, score > $1 AS above_min_score
1098
1099
  FROM vector_scores
1099
- WHERE score > $1
1100
- ORDER BY score DESC` : `
1100
+ ORDER BY score DESC`;
1101
+ const candidates = (await client.query(indexedQuery, queryValues)).rows;
1102
+ if (candidates.length >= topK) rows = candidates.filter((row) => row.above_min_score);
1103
+ }
1104
+ if (!rows) {
1105
+ const exactQuery = `
1101
1106
  WITH vector_scores AS (
1102
- SELECT
1103
- vector_id as id,
1104
- ${scoreExpr} as score,
1105
- metadata
1106
- ${includeVector ? ", embedding" : ""}
1107
+ SELECT ${selectColumns}
1107
1108
  FROM ${tableName}
1108
- WHERE namespace = $${namespaceParam}
1109
- ${filterClause ? `AND (${filterClause})` : ""}
1109
+ ${whereClause}
1110
1110
  )
1111
1111
  SELECT *
1112
1112
  FROM vector_scores
1113
1113
  WHERE score > $1
1114
1114
  ORDER BY score DESC
1115
1115
  LIMIT $2`;
1116
- const result = await client.query(query, [...filterValues, namespace]);
1116
+ rows = (await client.query(exactQuery, queryValues)).rows;
1117
+ }
1117
1118
  await client.query("COMMIT");
1118
- return result.rows.map(({ id, score, metadata, embedding }) => ({
1119
+ return rows.map(({ id, score, metadata, embedding }) => ({
1119
1120
  id,
1120
1121
  score,
1121
1122
  metadata,
@@ -1382,7 +1383,7 @@ var PgVector = class extends MastraVector {
1382
1383
  indexConfig,
1383
1384
  vectorType
1384
1385
  }, client);
1385
- if (metadataIndexes?.length) await this.createMetadataIndexes(tableName, indexName, metadataIndexes);
1386
+ if (metadataIndexes?.length) await this.createMetadataIndexes(client, tableName, indexName, metadataIndexes);
1386
1387
  } catch (error) {
1387
1388
  this.createdIndexes.delete(indexName);
1388
1389
  this.namespaceReadyIndexes.delete(indexName);
@@ -1532,13 +1533,13 @@ var PgVector = class extends MastraVector {
1532
1533
  await client.query(indexSQL);
1533
1534
  });
1534
1535
  }
1535
- async createMetadataIndexes(tableName, indexName, metadataFields) {
1536
+ async createMetadataIndexes(client, tableName, indexName, metadataFields) {
1536
1537
  const hasher = await this.hasher;
1537
1538
  for (const field of metadataFields) {
1538
1539
  const fieldHash = hasher.h32(field).toString(16);
1539
1540
  const metadataIdxName = `"${indexName.slice(0, 55 - fieldHash.length)}_md_${fieldHash}_idx"`;
1540
1541
  const escapedField = field.replace(/'/g, "''");
1541
- await this.pool.query(`
1542
+ await client.query(`
1542
1543
  CREATE INDEX CONCURRENTLY IF NOT EXISTS ${metadataIdxName}
1543
1544
  ON ${tableName} ((metadata->>'${escapedField}'))
1544
1545
  `);
@@ -8517,976 +8518,1403 @@ var FavoritesPG = class FavoritesPG extends FavoritesStorage {
8517
8518
  }
8518
8519
  }
8519
8520
  };
8520
- // ../../packages/_internal-core/dist/knowledge-compat/index.js
8521
- const KNOWLEDGE_V2_CORE_FEATURE = "knowledge-v2";
8522
- /** Hard cap on scope nodes returned by one `listScopeNodes` read. */
8523
- const MAX_KNOWLEDGE_SCOPE_NODES = 1e3;
8524
- function knowledgeScopeNodeFilterKey(input) {
8525
- return JSON.stringify([
8526
- input.withinAddress ?? null,
8527
- input.addresses ? [...input.addresses].sort() : null,
8528
- input.ids ? [...input.ids].sort() : null
8529
- ]);
8530
- }
8531
- function createKnowledgeScopeNodeCursor(scope, input) {
8532
- return encodeURIComponent(JSON.stringify({
8533
- version: 1,
8534
- type: "scope",
8535
- name: scope.name,
8536
- id: scope.id,
8537
- filter: knowledgeScopeNodeFilterKey(input)
8538
- }));
8539
- }
8540
- /** Validates the page size and cursor of a `listScopeNodes` query; throws on a cursor from a different query. */
8541
- function parseListKnowledgeScopeNodesInput(input = {}) {
8542
- const requested = Number.isFinite(input.limit) ? Math.trunc(input.limit) : MAX_KNOWLEDGE_SCOPE_NODES;
8543
- const limit = Math.min(Math.max(requested, 1), MAX_KNOWLEDGE_SCOPE_NODES);
8544
- if (!input.cursor) return {
8545
- limit,
8546
- after: null
8521
+ const KNOWLEDGE_TABLE_NAMES = [
8522
+ "mastra_knowledge_nodes",
8523
+ "mastra_knowledge_records",
8524
+ "mastra_knowledge_mentions",
8525
+ "mastra_knowledge_activity",
8526
+ "mastra_knowledge_semantic_outbox",
8527
+ "mastra_knowledge_node_scopes",
8528
+ "mastra_knowledge_record_scopes",
8529
+ "mastra_knowledge_scope_grants",
8530
+ "mastra_knowledge_access_state",
8531
+ "mastra_knowledge_scope_addresses",
8532
+ "mastra_knowledge_node_addresses",
8533
+ "mastra_knowledge_import_state",
8534
+ "mastra_knowledge_import_runs",
8535
+ "mastra_knowledge_proposals"
8536
+ ];
8537
+ /** Knowledge v1 tables with no v2 equivalent; an explicit schema reset drops them. */
8538
+ const RETIRED_KNOWLEDGE_TABLE_NAMES = ["mastra_knowledge_cursors"];
8539
+ const KNOWLEDGE_PAGES_CORE_FEATURE = "knowledge-pages";
8540
+ const KNOWLEDGE_PAGES_TABLE_NAMES = [
8541
+ "mastra_knowledge_pages",
8542
+ "mastra_knowledge_notes",
8543
+ "mastra_knowledge_note_stamps",
8544
+ "mastra_knowledge_mentions",
8545
+ "mastra_knowledge_pins",
8546
+ "mastra_knowledge_activity",
8547
+ "mastra_knowledge_access_state"
8548
+ ];
8549
+ /** Every Knowledge table any schema version created. Reset drops these and nothing else. */
8550
+ const KNOWLEDGE_RESETTABLE_TABLE_NAMES = [.../* @__PURE__ */ new Set([
8551
+ ...KNOWLEDGE_PAGES_TABLE_NAMES,
8552
+ ...KNOWLEDGE_TABLE_NAMES,
8553
+ ...RETIRED_KNOWLEDGE_TABLE_NAMES
8554
+ ])];
8555
+ /** Schema-1/2 tables whose presence means the store needs a reset before schema 4 can run. */
8556
+ const LEGACY_KNOWLEDGE_TABLE_NAMES = new Set([...KNOWLEDGE_TABLE_NAMES, ...RETIRED_KNOWLEDGE_TABLE_NAMES].filter((name) => !KNOWLEDGE_PAGES_TABLE_NAMES.includes(name)));
8557
+ /**
8558
+ * Classifies what an adapter found before creating schema-4 tables. `tableNames` is every
8559
+ * `mastra_knowledge_*` table present; `schemaVersion` is the state row's version, if any.
8560
+ */
8561
+ function inspectKnowledgePagesSchema(snapshot) {
8562
+ const legacy = snapshot.tableNames.filter((name) => LEGACY_KNOWLEDGE_TABLE_NAMES.has(name));
8563
+ if (legacy.length > 0) return {
8564
+ status: "incompatible-reset-required",
8565
+ schemaVersion: snapshot.schemaVersion ?? null,
8566
+ reason: `found Knowledge tables from an earlier schema (${legacy.join(", ")})`
8547
8567
  };
8548
- let value;
8549
- try {
8550
- value = JSON.parse(decodeURIComponent(input.cursor));
8551
- } catch {
8552
- throw new Error("Invalid Knowledge scope node cursor.");
8568
+ if (snapshot.schemaVersion === 4) return {
8569
+ status: "compatible",
8570
+ schemaVersion: 4
8571
+ };
8572
+ if (snapshot.schemaVersion === void 0) {
8573
+ const present = snapshot.tableNames.filter((name) => KNOWLEDGE_PAGES_TABLE_NAMES.includes(name));
8574
+ if (present.length === 0) return {
8575
+ status: "uninitialized",
8576
+ schemaVersion: null
8577
+ };
8578
+ return {
8579
+ status: "incompatible-reset-required",
8580
+ schemaVersion: null,
8581
+ reason: `found Knowledge tables (${present.join(", ")}) without a schema version`
8582
+ };
8553
8583
  }
8554
- const parsed = value && typeof value === "object" ? value : {};
8555
- if (parsed.version !== 1 || parsed.type !== "scope" || typeof parsed.name !== "string" || typeof parsed.id !== "string" || parsed.filter !== knowledgeScopeNodeFilterKey(input)) throw new Error("Knowledge scope node cursor does not match this query.");
8556
8584
  return {
8557
- limit,
8558
- after: {
8559
- name: parsed.name,
8560
- id: parsed.id
8561
- }
8585
+ status: "incompatible-reset-required",
8586
+ schemaVersion: snapshot.schemaVersion,
8587
+ reason: `Knowledge schema version ${snapshot.schemaVersion} is not 4`
8562
8588
  };
8563
8589
  }
8564
- /** Builds a page from up to `limit + 1` name/id-ordered scope nodes. */
8565
- function pageKnowledgeScopeNodes(rows, limit, input) {
8566
- const scopes = rows.slice(0, limit);
8567
- const last = scopes.at(-1);
8568
- return {
8569
- scopes,
8570
- nextCursor: rows.length > limit && last ? createKnowledgeScopeNodeCursor(last, input) : null
8590
+ /** Schema-2 table names schema 4 reuses with a different shape. */
8591
+ const REUSED_KNOWLEDGE_TABLE_NAMES = KNOWLEDGE_TABLE_NAMES.filter((name) => KNOWLEDGE_PAGES_TABLE_NAMES.includes(name));
8592
+ /**
8593
+ * The old Knowledge tables an adapter drops on init, rows included: Knowledge before schema 4 was an
8594
+ * experimental store with no migration. Every schema-1/2-only table present is dropped. The table
8595
+ * names schema 4 reuses (mentions, activity, the state table) are dropped too, but only when an old
8596
+ * table is present and no schema-4 state row exists, so they are old-shaped. Schema-4-only tables
8597
+ * are never listed. On a schema-4 store this lists only tables an older process recreated during a
8598
+ * rolling deploy. Drop order is safe for adapters that enforce references.
8599
+ */
8600
+ function legacyKnowledgeTablesToDrop(snapshot) {
8601
+ const present = new Set(snapshot.tableNames);
8602
+ const legacy = [...LEGACY_KNOWLEDGE_TABLE_NAMES].filter((name) => present.has(name));
8603
+ if (legacy.length === 0) return [];
8604
+ const reused = snapshot.schemaVersion === 4 ? [] : REUSED_KNOWLEDGE_TABLE_NAMES.filter((name) => present.has(name));
8605
+ const drop = /* @__PURE__ */ new Set([...legacy, ...reused]);
8606
+ return [...RETIRED_KNOWLEDGE_TABLE_NAMES, ...[...KNOWLEDGE_TABLE_NAMES].reverse()].filter((name) => drop.has(name));
8607
+ }
8608
+ /** Message for the error an adapter throws on `incompatible-reset-required`. */
8609
+ function knowledgePagesResetMessage(reason) {
8610
+ return `Knowledge storage needs a reset before this version can use it: ${reason}. Knowledge data has no migration; run \`await storage.stores?.knowledge?.dangerouslyReset()\` to drop the Knowledge tables (Memory tables are untouched).`;
8611
+ }
8612
+ const KNOWLEDGE_PAGES_CORE_FUNCTIONS = [
8613
+ "assertKnowledgePageDescriptionWithinBound",
8614
+ "assertKnowledgeNoteTextWithinBound",
8615
+ "canonicalKnowledgeName",
8616
+ "knowledgePositionBetween",
8617
+ "KnowledgeMoveTooLargeError",
8618
+ "KnowledgePageDepthError",
8619
+ "KnowledgePageHasChildrenError",
8620
+ "KnowledgePageKeyConflictError"
8621
+ ];
8622
+ const KNOWLEDGE_PAGES_CORE_NUMBERS = [
8623
+ "MAX_KNOWLEDGE_MOVE_PAGES",
8624
+ "MAX_KNOWLEDGE_PAGE_DEPTH",
8625
+ "MAX_KNOWLEDGE_PAGE_LIST_LIMIT"
8626
+ ];
8627
+ function resolveKnowledgePagesCore(storageModule) {
8628
+ const module = typeof storageModule === "object" && storageModule !== null ? storageModule : {};
8629
+ const missing = [...KNOWLEDGE_PAGES_CORE_FUNCTIONS.filter((name) => typeof module[name] !== "function"), ...KNOWLEDGE_PAGES_CORE_NUMBERS.filter((name) => typeof module[name] !== "number")];
8630
+ if (missing.length > 0) throw new Error(`@mastra/core advertises Knowledge pages without the required storage API (missing ${missing.join(", ")})`);
8631
+ return module;
8632
+ }
8633
+ /** Loads core's page-store runtime once, after checking core advertises `knowledge-pages`. */
8634
+ function createKnowledgePagesCoreLoader(features, loadStorageModule) {
8635
+ let core;
8636
+ return async () => {
8637
+ if (!features.has("knowledge-pages")) throw new Error(`Knowledge requires a @mastra/core release with the "${KNOWLEDGE_PAGES_CORE_FEATURE}" feature. Upgrade @mastra/core to use Knowledge; other storage domains keep working on this version.`);
8638
+ core ??= loadStorageModule().then(resolveKnowledgePagesCore).catch((error) => {
8639
+ core = void 0;
8640
+ throw error;
8641
+ });
8642
+ return core;
8571
8643
  };
8572
8644
  }
8573
- /** Clamps a requested member limit to 1–{@link MAX_KNOWLEDGE_SCOPE_MEMBERS_LIMIT}. */
8574
- function knowledgeScopeMembersLimit(limit) {
8575
- if (limit === void 0 || !Number.isFinite(limit)) return 500;
8576
- return Math.min(Math.max(Math.trunc(limit), 1), 500);
8645
+ /**
8646
+ * Keyword-search words: the query split on whitespace, lowercased, deduplicated. Every word must
8647
+ * appear (as a case-insensitive substring) in a hit; an empty list means the search returns nothing.
8648
+ */
8649
+ function knowledgeSearchWords(query) {
8650
+ return [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))];
8577
8651
  }
8578
- /** Validates the page size and cursor of a `listScopeMembers` query; throws on a cursor from another scope. */
8579
- function parseListKnowledgeScopeMembersInput(input) {
8580
- const limit = knowledgeScopeMembersLimit(input.limit);
8581
- if (!input.cursor) return {
8582
- limit,
8583
- after: null
8584
- };
8585
- let value;
8586
- try {
8587
- value = JSON.parse(decodeURIComponent(input.cursor));
8588
- } catch {
8589
- throw new Error("Invalid Knowledge scope member cursor.");
8652
+ /**
8653
+ * Why `key` can't be a Knowledge page key, or undefined when it can. Keys are one path segment:
8654
+ * non-empty, with no `/` (path separator), `#` (scope/path separator) or `%` (escape character).
8655
+ */
8656
+ function knowledgePageKeyProblem(key) {
8657
+ if (!key) return "Knowledge page key must not be empty";
8658
+ if (/[/#%]/.test(key)) return `Knowledge page key "${key}" must not contain "/", "#" or "%"`;
8659
+ }
8660
+ // src/storage/domains/knowledge/pages.ts
8661
+ const loadPagesCore = createKnowledgePagesCoreLoader(coreFeatures, () => import("@mastra/core/storage"));
8662
+ const DEFAULT_LIST_LIMIT = 50;
8663
+ const PG_UNIQUE_VIOLATION$1 = "23505";
8664
+ const PG_KNOWLEDGE_PAGES_TABLES = {
8665
+ pages: "mastra_knowledge_pages",
8666
+ notes: "mastra_knowledge_notes",
8667
+ stamps: "mastra_knowledge_note_stamps",
8668
+ mentions: "mastra_knowledge_mentions",
8669
+ pins: "mastra_knowledge_pins",
8670
+ activity: "mastra_knowledge_activity",
8671
+ state: "mastra_knowledge_access_state"
8672
+ };
8673
+ /**
8674
+ * Schema-4 DDL. `COLLATE "C"` on every column that is ordered, prefix-matched or compared for
8675
+ * equality makes Postgres compare bytes, not locale rules, so address prefixes are case-sensitive and
8676
+ * names/positions sort in binary order regardless of the database's default collation.
8677
+ */
8678
+ function pgKnowledgePagesDDL(schemaName) {
8679
+ const q = qualifier(schemaName);
8680
+ const t = PG_KNOWLEDGE_PAGES_TABLES;
8681
+ const index = (name, table, columns, where = "", unique = false) => `CREATE ${unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS "${name}" ON ${q(table)} (${columns})${where ? ` WHERE ${where}` : ""}`;
8682
+ return [
8683
+ `CREATE TABLE IF NOT EXISTS ${q(t.pages)} (
8684
+ "id" text PRIMARY KEY,
8685
+ "scopeId" text NOT NULL,
8686
+ "parentId" text,
8687
+ "isScope" boolean NOT NULL,
8688
+ "address" text COLLATE "C",
8689
+ "declaration" text COLLATE "C",
8690
+ "key" text COLLATE "C",
8691
+ "position" text COLLATE "C" NOT NULL,
8692
+ "name" text COLLATE "C" NOT NULL,
8693
+ "canonicalName" text COLLATE "C" NOT NULL,
8694
+ "description" text,
8695
+ "body" text,
8696
+ "depth" integer NOT NULL,
8697
+ "version" integer NOT NULL,
8698
+ "mergedInto" text,
8699
+ "createdBy" jsonb NOT NULL,
8700
+ "updatedBy" jsonb NOT NULL,
8701
+ "createdAt" timestamptz NOT NULL,
8702
+ "updatedAt" timestamptz NOT NULL,
8703
+ "deletedAt" timestamptz,
8704
+ "deletedBy" text
8705
+ )`,
8706
+ `CREATE TABLE IF NOT EXISTS ${q(t.notes)} (
8707
+ "id" text PRIMARY KEY,
8708
+ "pageId" text NOT NULL REFERENCES ${q(t.pages)} ("id"),
8709
+ "text" text NOT NULL,
8710
+ "when" timestamptz,
8711
+ "provenance" jsonb NOT NULL,
8712
+ "version" integer NOT NULL,
8713
+ "createdAt" timestamptz NOT NULL,
8714
+ "updatedAt" timestamptz NOT NULL,
8715
+ "deletedAt" timestamptz,
8716
+ "deletedBy" text
8717
+ )`,
8718
+ `CREATE TABLE IF NOT EXISTS ${q(t.stamps)} (
8719
+ "noteId" text NOT NULL REFERENCES ${q(t.notes)} ("id"),
8720
+ "scopeId" text NOT NULL REFERENCES ${q(t.pages)} ("id"),
8721
+ PRIMARY KEY ("noteId", "scopeId")
8722
+ )`,
8723
+ `CREATE TABLE IF NOT EXISTS ${q(t.mentions)} (
8724
+ "noteId" text NOT NULL REFERENCES ${q(t.notes)} ("id"),
8725
+ "pageId" text NOT NULL REFERENCES ${q(t.pages)} ("id"),
8726
+ PRIMARY KEY ("noteId", "pageId")
8727
+ )`,
8728
+ `CREATE TABLE IF NOT EXISTS ${q(t.pins)} (
8729
+ "id" text PRIMARY KEY,
8730
+ "pageId" text NOT NULL UNIQUE REFERENCES ${q(t.pages)} ("id"),
8731
+ "audience" text[] NOT NULL,
8732
+ "createdBy" text NOT NULL,
8733
+ "createdAt" timestamptz NOT NULL,
8734
+ "updatedAt" timestamptz NOT NULL
8735
+ )`,
8736
+ `CREATE TABLE IF NOT EXISTS ${q(t.activity)} (
8737
+ "id" text PRIMARY KEY,
8738
+ "action" text NOT NULL,
8739
+ "scopeId" text NOT NULL,
8740
+ "pageId" text NOT NULL,
8741
+ "noteId" text,
8742
+ "provenance" jsonb NOT NULL,
8743
+ "createdAt" timestamptz NOT NULL
8744
+ )`,
8745
+ `CREATE TABLE IF NOT EXISTS ${q(t.state)} (
8746
+ "id" text PRIMARY KEY,
8747
+ "schemaVersion" integer NOT NULL
8748
+ )`,
8749
+ index("mastra_knowledge_pages_address_uq", t.pages, "\"address\"", "\"isScope\"", true),
8750
+ `DROP INDEX IF EXISTS ${q("mastra_knowledge_pages_key_uq")}`,
8751
+ index("mastra_knowledge_pages_parent_key_uq", t.pages, "\"parentId\",\"key\"", "\"key\" IS NOT NULL AND \"deletedAt\" IS NULL", true),
8752
+ index("mastra_knowledge_pages_scope_decl_parent_idx", t.pages, "\"declaration\",\"parentId\"", "\"isScope\""),
8753
+ index("mastra_knowledge_pages_parent_idx", t.pages, "\"parentId\",\"position\",\"id\""),
8754
+ index("mastra_knowledge_pages_scope_name_idx", t.pages, "\"scopeId\",\"name\",\"id\"", "\"deletedAt\" IS NULL"),
8755
+ index("mastra_knowledge_pages_name_idx", t.pages, "\"name\",\"id\"", "\"deletedAt\" IS NULL AND NOT \"isScope\""),
8756
+ index("mastra_knowledge_pages_canonical_idx", t.pages, "\"canonicalName\"", "\"deletedAt\" IS NULL"),
8757
+ index("mastra_knowledge_notes_page_idx", t.notes, "\"pageId\",\"createdAt\",\"id\""),
8758
+ index("mastra_knowledge_stamps_scope_idx", t.stamps, "\"scopeId\""),
8759
+ index("mastra_knowledge_mentions_page_idx", t.mentions, "\"pageId\""),
8760
+ `CREATE INDEX IF NOT EXISTS "mastra_knowledge_pins_audience_gin" ON ${q(t.pins)} USING gin ("audience")`,
8761
+ index("mastra_knowledge_pins_created_idx", t.pins, "\"createdAt\",\"id\""),
8762
+ index("mastra_knowledge_activity_page_idx", t.activity, "\"pageId\",\"createdAt\",\"id\""),
8763
+ index("mastra_knowledge_activity_created_idx", t.activity, "\"createdAt\",\"id\"")
8764
+ ];
8765
+ }
8766
+ function qualifier(schemaName) {
8767
+ return (table) => schemaName ? `"${schemaName}"."${table}"` : `"${table}"`;
8768
+ }
8769
+ /** Collects bind parameters and hands back their `$n` placeholders. */
8770
+ var Params = class {
8771
+ values = [];
8772
+ add(value) {
8773
+ this.values.push(value);
8774
+ return `$${this.values.length}`;
8775
+ }
8776
+ };
8777
+ /**
8778
+ * The read scope as bound arrays, registered once per query so the same `$n` is reused for every
8779
+ * check in it. A large frontier travels as a handful of array parameters (`= ANY($n::text[])`,
8780
+ * `unnest`), never as a long `IN (...)` list.
8781
+ */
8782
+ var ReadFilter = class {
8783
+ #all;
8784
+ #pages;
8785
+ #addresses;
8786
+ #prefixes;
8787
+ #openPrefixes;
8788
+ #children;
8789
+ constructor(read, params, pages) {
8790
+ this.#all = read === "all";
8791
+ this.#pages = pages;
8792
+ if (read === "all") return;
8793
+ if (read.addresses.length) this.#addresses = `${params.add(read.addresses)}::text[]`;
8794
+ const bounded = read.prefixes.filter((entry) => prefixUpperBound(entry.prefix) !== null);
8795
+ const open = read.prefixes.filter((entry) => prefixUpperBound(entry.prefix) === null);
8796
+ if (bounded.length) this.#prefixes = [
8797
+ `${params.add(bounded.map((entry) => entry.declaration))}::text[]`,
8798
+ `${params.add(bounded.map((entry) => entry.prefix))}::text[]`,
8799
+ `${params.add(bounded.map((entry) => prefixUpperBound(entry.prefix)))}::text[]`
8800
+ ];
8801
+ if (open.length) this.#openPrefixes = [`${params.add(open.map((entry) => entry.declaration))}::text[]`, `${params.add(open.map((entry) => entry.prefix))}::text[]`];
8802
+ if (read.children.length) this.#children = [`${params.add(read.children.map((entry) => entry.declaration))}::text[]`, `${params.add(read.children.map((entry) => entry.parentId))}::text[]`];
8803
+ }
8804
+ /** Whether the filter admits every scope (no restriction to apply). */
8805
+ get all() {
8806
+ return this.#all;
8807
+ }
8808
+ /**
8809
+ * The ids of every readable scope page, resolved through indexes: exact addresses hit the
8810
+ * address index, prefixes become a binary range on it (`address >= prefix AND address < upper`,
8811
+ * rechecked with `starts_with`; a prefix with no finite upper bound uses `>=` alone; the declaration test is `IS NOT DISTINCT FROM` on purpose so the
8812
+ * planner walks the address range instead of every scope of that declaration, so `_` and `%` stay literal and matching stays case-sensitive),
8813
+ * and one-hop children hit `(declaration, parentId)`.
8814
+ */
8815
+ readableIds() {
8816
+ if (this.#all) return `SELECT "id" FROM ${this.#pages} WHERE "isScope"`;
8817
+ const branches = [];
8818
+ if (this.#addresses) branches.push(`SELECT "id" FROM ${this.#pages} WHERE "isScope" AND "address" = ANY(${this.#addresses})`);
8819
+ if (this.#prefixes) branches.push(`SELECT ps."id" FROM unnest(${this.#prefixes[0]}, ${this.#prefixes[1]}, ${this.#prefixes[2]}) AS pr("declaration", "prefix", "upper") JOIN ${this.#pages} ps ON ps."isScope" AND ps."address" >= pr."prefix" AND ps."address" < pr."upper" AND ps."declaration" IS NOT DISTINCT FROM pr."declaration" AND starts_with(ps."address", pr."prefix")`);
8820
+ if (this.#openPrefixes) branches.push(`SELECT os."id" FROM unnest(${this.#openPrefixes[0]}, ${this.#openPrefixes[1]}) AS po("declaration", "prefix") JOIN ${this.#pages} os ON os."isScope" AND os."address" >= po."prefix" AND os."declaration" IS NOT DISTINCT FROM po."declaration" AND starts_with(os."address", po."prefix")`);
8821
+ if (this.#children) branches.push(`SELECT cs."id" FROM unnest(${this.#children[0]}, ${this.#children[1]}) AS ch("declaration", "parentId") JOIN ${this.#pages} cs ON cs."isScope" AND cs."declaration" = ch."declaration" AND cs."parentId" = ch."parentId"`);
8822
+ return branches.length ? branches.join(" UNION ") : `SELECT "id" FROM ${this.#pages} WHERE FALSE`;
8590
8823
  }
8591
- const parsed = value && typeof value === "object" ? value : {};
8592
- const updatedAt = typeof parsed.updatedAt === "string" ? new Date(parsed.updatedAt) : /* @__PURE__ */ new Date(NaN);
8593
- if (parsed.version !== 1 || parsed.type !== "scope-member" || parsed.scopeNodeId !== input.scopeNodeId || typeof parsed.name !== "string" || typeof parsed.id !== "string" || Number.isNaN(updatedAt.getTime())) throw new Error("Knowledge scope member cursor does not match this query.");
8824
+ /** True when a scope page aliased `scope` is readable. Matching is binary and case-sensitive. */
8825
+ readable(scope) {
8826
+ if (this.#all) return "TRUE";
8827
+ return `${scope}."id" IN (${this.readableIds()})`;
8828
+ }
8829
+ };
8830
+ /** Smallest string greater than every string starting with `prefix`, or null when none exists. */
8831
+ function prefixUpperBound(prefix) {
8832
+ const points = Array.from(prefix);
8833
+ const last = points.pop()?.codePointAt(0);
8834
+ if (last === void 0 || last >= 1114111 || last >= 55295 && last < 57344) return null;
8835
+ return points.join("") + String.fromCodePoint(last + 1);
8836
+ }
8837
+ function encodeCursor(parts) {
8838
+ return Buffer.from(JSON.stringify(parts)).toString("base64url");
8839
+ }
8840
+ function decodeCursor(cursor, arity) {
8841
+ try {
8842
+ const parts = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
8843
+ if (Array.isArray(parts) && parts.length === arity && parts.every((part) => typeof part === "string")) return parts;
8844
+ } catch {}
8845
+ throw new Error("Invalid Knowledge cursor");
8846
+ }
8847
+ function clampLimit(limit, max) {
8848
+ const value = limit ?? DEFAULT_LIST_LIMIT;
8849
+ if (!Number.isInteger(value) || value < 1) throw new Error("Knowledge list limit must be a positive integer");
8850
+ return Math.min(value, max);
8851
+ }
8852
+ function iso(value) {
8853
+ return value.toISOString();
8854
+ }
8855
+ function optionalDate(value) {
8856
+ return value == null ? void 0 : new Date(value);
8857
+ }
8858
+ function parseJson$1(value) {
8859
+ return typeof value === "string" ? JSON.parse(value) : value;
8860
+ }
8861
+ function toPage(row) {
8594
8862
  return {
8595
- limit,
8596
- after: {
8597
- updatedAt,
8598
- name: parsed.name,
8599
- id: parsed.id
8600
- }
8863
+ id: String(row.id),
8864
+ scopeId: String(row.scopeId),
8865
+ parentId: row.parentId == null ? null : String(row.parentId),
8866
+ isScope: row.isScope === true,
8867
+ ...row.address == null ? {} : { address: String(row.address) },
8868
+ ...row.declaration == null ? {} : { declaration: String(row.declaration) },
8869
+ ...row.key == null ? {} : { key: String(row.key) },
8870
+ position: String(row.position),
8871
+ name: String(row.name),
8872
+ ...row.description == null ? {} : { description: String(row.description) },
8873
+ ...row.body == null ? {} : { body: String(row.body) },
8874
+ version: Number(row.version),
8875
+ ...row.mergedInto == null ? {} : { mergedInto: String(row.mergedInto) },
8876
+ createdBy: parseJson$1(row.createdBy),
8877
+ updatedBy: parseJson$1(row.updatedBy),
8878
+ createdAt: new Date(row.createdAt),
8879
+ updatedAt: new Date(row.updatedAt),
8880
+ ...row.deletedAt == null ? {} : { deletedAt: new Date(row.deletedAt) },
8881
+ ...row.deletedBy == null ? {} : { deletedBy: String(row.deletedBy) }
8601
8882
  };
8602
8883
  }
8603
- /** Builds a page from up to `limit + 1` members in `listScopeMembers` order. */
8604
- function pageKnowledgeScopeMembers(rows, limit, input) {
8605
- const members = rows.slice(0, limit);
8606
- const last = members.at(-1);
8607
- const hasMore = rows.length > limit;
8884
+ function toNote(row) {
8885
+ const when = optionalDate(row.when);
8886
+ const deletedAt = optionalDate(row.deletedAt);
8608
8887
  return {
8609
- members,
8610
- hasMore,
8611
- nextCursor: hasMore && last ? encodeURIComponent(JSON.stringify({
8612
- version: 1,
8613
- type: "scope-member",
8614
- scopeNodeId: input.scopeNodeId,
8615
- updatedAt: last.updatedAt.toISOString(),
8616
- name: last.name,
8617
- id: last.id
8618
- })) : null
8888
+ id: String(row.id),
8889
+ pageId: String(row.pageId),
8890
+ text: String(row.text),
8891
+ ...when ? { when } : {},
8892
+ stampScopeIds: row.stampScopeIds ?? [],
8893
+ mentions: row.mentions ?? [],
8894
+ provenance: parseJson$1(row.provenance),
8895
+ version: Number(row.version),
8896
+ createdAt: new Date(row.createdAt),
8897
+ updatedAt: new Date(row.updatedAt),
8898
+ ...deletedAt ? { deletedAt } : {},
8899
+ ...row.deletedBy == null ? {} : { deletedBy: String(row.deletedBy) }
8619
8900
  };
8620
8901
  }
8621
- const TABLE_KNOWLEDGE_NODES$1 = "mastra_knowledge_nodes";
8622
- const TABLE_KNOWLEDGE_RECORDS$1 = "mastra_knowledge_records";
8623
- const TABLE_KNOWLEDGE_MENTIONS$1 = "mastra_knowledge_mentions";
8624
- const TABLE_KNOWLEDGE_ACTIVITY$1 = "mastra_knowledge_activity";
8625
- const TABLE_KNOWLEDGE_SEMANTIC_OUTBOX$1 = "mastra_knowledge_semantic_outbox";
8626
- const TABLE_KNOWLEDGE_NODE_SCOPES = "mastra_knowledge_node_scopes";
8627
- const TABLE_KNOWLEDGE_RECORD_SCOPES = "mastra_knowledge_record_scopes";
8628
- const TABLE_KNOWLEDGE_SCOPE_GRANTS = "mastra_knowledge_scope_grants";
8629
- const TABLE_KNOWLEDGE_ACCESS_STATE = "mastra_knowledge_access_state";
8630
- const TABLE_KNOWLEDGE_SCOPE_ADDRESSES = "mastra_knowledge_scope_addresses";
8631
- const TABLE_KNOWLEDGE_NODE_ADDRESSES = "mastra_knowledge_node_addresses";
8632
- const TABLE_KNOWLEDGE_IMPORT_STATE = "mastra_knowledge_import_state";
8633
- const TABLE_KNOWLEDGE_IMPORT_RUNS = "mastra_knowledge_import_runs";
8634
- const TABLE_KNOWLEDGE_PROPOSALS = "mastra_knowledge_proposals";
8635
- const KNOWLEDGE_TABLE_NAMES = [
8636
- TABLE_KNOWLEDGE_NODES$1,
8637
- TABLE_KNOWLEDGE_RECORDS$1,
8638
- TABLE_KNOWLEDGE_MENTIONS$1,
8639
- TABLE_KNOWLEDGE_ACTIVITY$1,
8640
- TABLE_KNOWLEDGE_SEMANTIC_OUTBOX$1,
8641
- TABLE_KNOWLEDGE_NODE_SCOPES,
8642
- TABLE_KNOWLEDGE_RECORD_SCOPES,
8643
- TABLE_KNOWLEDGE_SCOPE_GRANTS,
8644
- TABLE_KNOWLEDGE_ACCESS_STATE,
8645
- TABLE_KNOWLEDGE_SCOPE_ADDRESSES,
8646
- TABLE_KNOWLEDGE_NODE_ADDRESSES,
8647
- TABLE_KNOWLEDGE_IMPORT_STATE,
8648
- TABLE_KNOWLEDGE_IMPORT_RUNS,
8649
- TABLE_KNOWLEDGE_PROPOSALS
8650
- ];
8651
- /** Knowledge v1 tables with no v2 equivalent; an explicit schema reset drops them. */
8652
- const RETIRED_KNOWLEDGE_TABLE_NAMES = ["mastra_knowledge_cursors"];
8653
- /** Tables and indexes published v1 adapters created for every app, whether or not it used Knowledge. */
8654
- const PUBLISHED_KNOWLEDGE_V1_TABLE_NAMES = /* @__PURE__ */ new Set([
8655
- TABLE_KNOWLEDGE_NODES$1,
8656
- TABLE_KNOWLEDGE_RECORDS$1,
8657
- TABLE_KNOWLEDGE_MENTIONS$1,
8658
- TABLE_KNOWLEDGE_ACTIVITY$1,
8659
- TABLE_KNOWLEDGE_SEMANTIC_OUTBOX$1,
8660
- ...RETIRED_KNOWLEDGE_TABLE_NAMES
8661
- ]);
8662
- const PUBLISHED_KNOWLEDGE_V1_INDEX_NAMES = /* @__PURE__ */ new Set([
8663
- "idx_knowledge_nodes_identity",
8664
- "idx_knowledge_nodes_scope",
8665
- "idx_knowledge_records_node_latest",
8666
- "idx_knowledge_records_thread_latest",
8667
- "idx_knowledge_mentions_record",
8668
- "idx_knowledge_activity_latest",
8669
- "idx_knowledge_outbox_idempotency",
8670
- "idx_knowledge_outbox_claim"
8671
- ]);
8672
- const KNOWLEDGE_V2_NODES_SCHEMA = {
8673
- id: {
8674
- type: "text",
8675
- nullable: false,
8676
- primaryKey: true
8677
- },
8678
- name: {
8679
- type: "text",
8680
- nullable: false
8681
- },
8682
- kind: {
8683
- type: "text",
8684
- nullable: true
8685
- },
8686
- isScope: {
8687
- type: "boolean",
8688
- nullable: false
8689
- },
8690
- metadata: {
8691
- type: "jsonb",
8692
- nullable: true
8693
- },
8694
- version: {
8695
- type: "integer",
8696
- nullable: false
8697
- },
8698
- createdAt: {
8699
- type: "timestamp",
8700
- nullable: false
8701
- },
8702
- updatedAt: {
8703
- type: "timestamp",
8704
- nullable: false
8705
- },
8706
- deletedAt: {
8707
- type: "timestamp",
8708
- nullable: true
8709
- },
8710
- deletedBy: {
8711
- type: "text",
8712
- nullable: true
8713
- },
8714
- type: {
8715
- type: "text",
8716
- nullable: true
8717
- },
8718
- canonicalName: {
8719
- type: "text",
8720
- nullable: true
8721
- },
8722
- content: {
8723
- type: "text",
8724
- nullable: true
8725
- },
8726
- description: {
8727
- type: "text",
8728
- nullable: true
8729
- },
8730
- scope: {
8731
- type: "jsonb",
8732
- nullable: true
8733
- },
8734
- scopeKey: {
8735
- type: "text",
8736
- nullable: true
8737
- },
8738
- mergedInto: {
8739
- type: "text",
8740
- nullable: true
8902
+ function toPin(row) {
8903
+ return {
8904
+ id: String(row.id),
8905
+ pageId: String(row.pageId),
8906
+ audience: row.audience ?? [],
8907
+ createdBy: String(row.createdBy),
8908
+ createdAt: new Date(row.createdAt),
8909
+ updatedAt: new Date(row.updatedAt)
8910
+ };
8911
+ }
8912
+ function toListedPin(row) {
8913
+ return {
8914
+ ...toPin(row),
8915
+ pageName: String(row.pageName)
8916
+ };
8917
+ }
8918
+ function escapeLike(term) {
8919
+ return term.replace(/[\\%_]/g, (match) => `\\${match}`);
8920
+ }
8921
+ function isUniqueViolation$1(error) {
8922
+ return typeof error === "object" && error !== null && error.code === PG_UNIQUE_VIOLATION$1;
8923
+ }
8924
+ /**
8925
+ * Postgres implementation of the schema-4 {@link KnowledgePageStore}.
8926
+ *
8927
+ * Visibility is computed with live joins (a note's page home scope, its stamps, its mentioned pages'
8928
+ * current home scopes), so a move or merge, which rewrites `scopeId` on the moved pages in the same
8929
+ * transaction, can never leave a stale denormalized copy.
8930
+ */
8931
+ var PgKnowledgePages = class {
8932
+ #client;
8933
+ #schemaName;
8934
+ #bounds;
8935
+ #q;
8936
+ constructor(options) {
8937
+ this.#client = options.client;
8938
+ this.#schemaName = options.schemaName;
8939
+ this.#bounds = options.bounds;
8940
+ this.#q = qualifier(options.schemaName);
8941
+ }
8942
+ get #pages() {
8943
+ return this.#q(PG_KNOWLEDGE_PAGES_TABLES.pages);
8944
+ }
8945
+ get #notes() {
8946
+ return this.#q(PG_KNOWLEDGE_PAGES_TABLES.notes);
8947
+ }
8948
+ get #stamps() {
8949
+ return this.#q(PG_KNOWLEDGE_PAGES_TABLES.stamps);
8950
+ }
8951
+ get #mentions() {
8952
+ return this.#q(PG_KNOWLEDGE_PAGES_TABLES.mentions);
8953
+ }
8954
+ get #pins() {
8955
+ return this.#q(PG_KNOWLEDGE_PAGES_TABLES.pins);
8956
+ }
8957
+ get #activity() {
8958
+ return this.#q(PG_KNOWLEDGE_PAGES_TABLES.activity);
8959
+ }
8960
+ async #rows(db, sql, params = []) {
8961
+ return (await db.query(sql, params)).rows;
8962
+ }
8963
+ #tx(operation) {
8964
+ return this.#client.tx(operation);
8965
+ }
8966
+ /** The read-side `FROM` for notes: the note, its page, and the page's home scope. */
8967
+ #visibleNotes(filter, alias = "n") {
8968
+ return `${this.#notes} ${alias}
8969
+ JOIN ${this.#pages} np ON np."id" = ${alias}."pageId"
8970
+ JOIN ${this.#pages} nps ON nps."id" = np."scopeId"
8971
+ WHERE ${filter.readable("nps")}
8972
+ AND EXISTS (SELECT 1 FROM ${this.#stamps} st JOIN ${this.#pages} sts ON sts."id" = st."scopeId" WHERE st."noteId" = ${alias}."id" AND ${filter.readable("sts")})
8973
+ AND NOT EXISTS (SELECT 1 FROM ${this.#mentions} mn JOIN ${this.#pages} mp ON mp."id" = mn."pageId" JOIN ${this.#pages} mps ON mps."id" = mp."scopeId" WHERE mn."noteId" = ${alias}."id" AND NOT ${filter.readable("mps")})`;
8974
+ }
8975
+ /** Same note visibility as a bare predicate, for filters that start from another table. */
8976
+ #noteVisible(filter, noteIdColumn) {
8977
+ return `EXISTS (SELECT 1 FROM ${this.#notes} vn JOIN ${this.#pages} vp ON vp."id" = vn."pageId" JOIN ${this.#pages} vps ON vps."id" = vp."scopeId"
8978
+ WHERE vn."id" = ${noteIdColumn} AND ${filter.readable("vps")}
8979
+ AND EXISTS (SELECT 1 FROM ${this.#stamps} vst JOIN ${this.#pages} vsts ON vsts."id" = vst."scopeId" WHERE vst."noteId" = vn."id" AND ${filter.readable("vsts")})
8980
+ AND NOT EXISTS (SELECT 1 FROM ${this.#mentions} vmn JOIN ${this.#pages} vmp ON vmp."id" = vmn."pageId" JOIN ${this.#pages} vmps ON vmps."id" = vmp."scopeId" WHERE vmn."noteId" = vn."id" AND NOT ${filter.readable("vmps")}))`;
8981
+ }
8982
+ #noteColumns(alias = "n") {
8983
+ return `${alias}.*,
8984
+ ARRAY(SELECT st."scopeId" FROM ${this.#stamps} st WHERE st."noteId" = ${alias}."id" ORDER BY st."scopeId") AS "stampScopeIds",
8985
+ ARRAY(SELECT mn."pageId" FROM ${this.#mentions} mn WHERE mn."noteId" = ${alias}."id" ORDER BY mn."pageId") AS "mentions"`;
8986
+ }
8987
+ async #logActivity(db, event) {
8988
+ await db.query(`INSERT INTO ${this.#activity} ("id","action","scopeId","pageId","noteId","provenance","createdAt") VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7)`, [
8989
+ createKnowledgeUlid(),
8990
+ event.action,
8991
+ event.scopeId,
8992
+ event.pageId,
8993
+ event.noteId ?? null,
8994
+ JSON.stringify(event.provenance),
8995
+ iso(event.at)
8996
+ ]);
8741
8997
  }
8742
- };
8743
- const KNOWLEDGE_V2_RECORDS_SCHEMA = {
8744
- id: {
8745
- type: "text",
8746
- nullable: false,
8747
- primaryKey: true
8748
- },
8749
- node: {
8750
- type: "text",
8751
- nullable: false,
8752
- references: {
8753
- table: TABLE_KNOWLEDGE_NODES$1,
8754
- column: "id"
8755
- }
8756
- },
8757
- text: {
8758
- type: "text",
8759
- nullable: false
8760
- },
8761
- metadata: {
8762
- type: "jsonb",
8763
- nullable: true
8764
- },
8765
- version: {
8766
- type: "integer",
8767
- nullable: false
8768
- },
8769
- capturedAt: {
8770
- type: "timestamp",
8771
- nullable: false
8772
- },
8773
- updatedAt: {
8774
- type: "timestamp",
8775
- nullable: false
8776
- },
8777
- deletedAt: {
8778
- type: "timestamp",
8779
- nullable: true
8780
- },
8781
- deletedBy: {
8782
- type: "text",
8783
- nullable: true
8784
- },
8785
- scope: {
8786
- type: "jsonb",
8787
- nullable: true
8788
- },
8789
- scopeKey: {
8790
- type: "text",
8791
- nullable: true
8792
- },
8793
- sourceThreadId: {
8794
- type: "text",
8795
- nullable: true
8796
- },
8797
- when: {
8798
- type: "timestamp",
8799
- nullable: true
8998
+ async #lockPage(db, id) {
8999
+ const rows = await this.#rows(db, `SELECT * FROM ${this.#pages} WHERE "id" = $1 FOR UPDATE`, [id]);
9000
+ return rows[0] ? toPage(rows[0]) : null;
9001
+ }
9002
+ async #requireLivePage(db, id, lock = true) {
9003
+ const rows = await this.#rows(db, `SELECT * FROM ${this.#pages} WHERE "id" = $1${lock ? " FOR UPDATE" : ""}`, [id]);
9004
+ const page = rows[0] ? toPage(rows[0]) : null;
9005
+ if (!page || page.deletedAt) throw new KnowledgeNotFoundError("page", id);
9006
+ return page;
9007
+ }
9008
+ /** Position after the last live child of `parentId`. */
9009
+ async #lastPosition(db, parentId) {
9010
+ const rows = await this.#rows(db, parentId === null ? `SELECT "position" FROM ${this.#pages} WHERE "parentId" IS NULL AND "deletedAt" IS NULL ORDER BY "position" DESC LIMIT 1` : `SELECT "position" FROM ${this.#pages} WHERE "parentId" = $1 AND "deletedAt" IS NULL ORDER BY "position" DESC LIMIT 1`, parentId === null ? [] : [parentId]);
9011
+ return rows[0] ? String(rows[0].position) : void 0;
9012
+ }
9013
+ /** Ordinary descendants of `rootId` (excluding it), as a recursive CTE named `sub`. */
9014
+ #subtree(rootParam) {
9015
+ return `WITH RECURSIVE sub("id") AS (
9016
+ SELECT c."id" FROM ${this.#pages} c WHERE c."parentId" = ${rootParam} AND NOT c."isScope"
9017
+ UNION ALL
9018
+ SELECT c."id" FROM ${this.#pages} c JOIN sub ON c."parentId" = sub."id" WHERE NOT c."isScope"
9019
+ )`;
8800
9020
  }
8801
- };
8802
- const KNOWLEDGE_V2_MENTIONS_SCHEMA = {
8803
- recordId: {
8804
- type: "text",
8805
- nullable: false,
8806
- references: {
8807
- table: TABLE_KNOWLEDGE_RECORDS$1,
8808
- column: "id"
8809
- }
8810
- },
8811
- targetNodeId: {
8812
- type: "text",
8813
- nullable: true,
8814
- references: {
8815
- table: TABLE_KNOWLEDGE_NODES$1,
8816
- column: "id"
8817
- }
8818
- },
8819
- sourceType: {
8820
- type: "text",
8821
- nullable: true
8822
- },
8823
- sourceId: {
8824
- type: "text",
8825
- nullable: true
9021
+ /** Live descendants, capped, and the deepest live level. */
9022
+ async #subtreeStats(db, rootId) {
9023
+ const core = await loadPagesCore();
9024
+ const rows = await this.#rows(db, `${this.#subtree("$1")}
9025
+ SELECT (SELECT count(*) FROM (SELECT 1 FROM sub JOIN ${this.#pages} p ON p."id" = sub."id" WHERE p."deletedAt" IS NULL LIMIT ${core.MAX_KNOWLEDGE_MOVE_PAGES + 1}) l) AS live,
9026
+ (SELECT COALESCE(max(p."depth"), 0) FROM sub JOIN ${this.#pages} p ON p."id" = sub."id" WHERE p."deletedAt" IS NULL) AS "maxDepth"`, [rootId]);
9027
+ return {
9028
+ live: Number(rows[0]?.live ?? 0),
9029
+ maxDepth: Number(rows[0]?.maxDepth ?? 0)
9030
+ };
8826
9031
  }
8827
- };
8828
- const KNOWLEDGE_NODE_SCOPES_SCHEMA = {
8829
- nodeId: {
8830
- type: "text",
8831
- nullable: false,
8832
- references: {
8833
- table: TABLE_KNOWLEDGE_NODES$1,
8834
- column: "id"
8835
- }
8836
- },
8837
- scopeNodeId: {
8838
- type: "text",
8839
- nullable: false,
8840
- references: {
8841
- table: TABLE_KNOWLEDGE_NODES$1,
8842
- column: "id"
8843
- }
8844
- },
8845
- addedAt: {
8846
- type: "timestamp",
8847
- nullable: false
9032
+ /**
9033
+ * Refuses before any write when a live page arriving under `parentId` has a key a live child of
9034
+ * `parentId` already uses: the moved root itself, or, for a merge, the source's live children.
9035
+ */
9036
+ async #assertNoKeyConflicts(db, arriving, parentId, exceptId) {
9037
+ const core = await loadPagesCore();
9038
+ const arrivingWhere = arriving.rootId ? `c."id" = $1` : `c."parentId" = $1 AND NOT c."isScope"`;
9039
+ const rows = await this.#rows(db, `SELECT c."key" FROM ${this.#pages} c
9040
+ JOIN ${this.#pages} t ON t."parentId" = $2 AND t."key" = c."key" AND t."deletedAt" IS NULL AND t."id" <> c."id" AND t."id" IS DISTINCT FROM $3::text
9041
+ WHERE ${arrivingWhere} AND c."key" IS NOT NULL AND c."deletedAt" IS NULL
9042
+ LIMIT 1`, [
9043
+ arriving.rootId ?? arriving.childrenOf,
9044
+ parentId,
9045
+ exceptId ?? null
9046
+ ]);
9047
+ if (rows[0]) throw new core.KnowledgePageKeyConflictError(String(rows[0].key), parentId);
9048
+ }
9049
+ async #isInSubtree(db, rootId, candidateId) {
9050
+ return (await this.#rows(db, `${this.#subtree("$1")} SELECT 1 FROM sub WHERE "id" = $2 LIMIT 1`, [rootId, candidateId])).length > 0;
9051
+ }
9052
+ async materializeScope(input) {
9053
+ const bounds = await this.#bounds();
9054
+ bounds.assertKnowledgePageDescriptionWithinBound(input.description);
9055
+ for (const child of input.children ?? []) bounds.assertKnowledgePageDescriptionWithinBound(child.description);
9056
+ const checkTemplates = (templates) => {
9057
+ for (const template of templates) {
9058
+ bounds.assertKnowledgePageDescriptionWithinBound(template.description);
9059
+ checkTemplates(template.pages ?? []);
9060
+ }
9061
+ };
9062
+ checkTemplates(input.pages ?? []);
9063
+ return this.#tx(async (tx) => {
9064
+ await tx.query("SELECT pg_advisory_xact_lock(hashtext($1))", [`mastra-knowledge-scope:${this.#schemaName ?? ""}:${input.address}`]);
9065
+ const now = /* @__PURE__ */ new Date();
9066
+ let scope = await this.#scopeByAddress(tx, input.address);
9067
+ let created = false;
9068
+ let parentConflict;
9069
+ if (!scope) {
9070
+ if (input.parentId) await this.#requireLivePage(tx, input.parentId, false);
9071
+ scope = await this.#insertScope(tx, {
9072
+ address: input.address,
9073
+ declaration: input.declaration,
9074
+ name: input.name,
9075
+ description: input.description,
9076
+ parentId: input.parentId ?? null,
9077
+ provenance: input.provenance,
9078
+ at: now
9079
+ });
9080
+ created = true;
9081
+ } else if (input.parentId && scope.parentId === null) {
9082
+ await this.#requireLivePage(tx, input.parentId, false);
9083
+ scope = toPage((await this.#rows(tx, `UPDATE ${this.#pages} SET "parentId" = $2 WHERE "id" = $1 AND "parentId" IS NULL RETURNING *`, [scope.id, input.parentId]))[0]);
9084
+ } else if (input.parentId !== void 0 && (input.parentId ?? null) !== scope.parentId) parentConflict = {
9085
+ existingParentId: scope.parentId,
9086
+ requestedParentId: input.parentId ?? null
9087
+ };
9088
+ for (const child of input.children ?? []) {
9089
+ await tx.query("SELECT pg_advisory_xact_lock(hashtext($1))", [`mastra-knowledge-scope:${this.#schemaName ?? ""}:${child.address}`]);
9090
+ if (await this.#scopeByAddress(tx, child.address)) continue;
9091
+ await this.#insertScope(tx, {
9092
+ address: child.address,
9093
+ declaration: child.declaration,
9094
+ name: child.name,
9095
+ description: child.description,
9096
+ parentId: scope.id,
9097
+ provenance: input.provenance,
9098
+ at: now
9099
+ });
9100
+ }
9101
+ await this.#materializeTemplates(tx, scope, input.pages ?? [], input.provenance, now);
9102
+ return {
9103
+ scope,
9104
+ created,
9105
+ ...parentConflict ? { parentConflict } : {}
9106
+ };
9107
+ });
8848
9108
  }
8849
- };
8850
- const KNOWLEDGE_RECORD_SCOPES_SCHEMA = {
8851
- recordId: {
8852
- type: "text",
8853
- nullable: false,
8854
- references: {
8855
- table: TABLE_KNOWLEDGE_RECORDS$1,
8856
- column: "id"
8857
- }
8858
- },
8859
- scopeNodeId: {
8860
- type: "text",
8861
- nullable: false,
8862
- references: {
8863
- table: TABLE_KNOWLEDGE_NODES$1,
8864
- column: "id"
8865
- }
8866
- },
8867
- addedAt: {
8868
- type: "timestamp",
8869
- nullable: false
9109
+ async #materializeTemplates(db, parent, templates, provenance, at) {
9110
+ await loadPagesCore();
9111
+ for (const template of templates) {
9112
+ const problem = knowledgePageKeyProblem(template.key);
9113
+ if (problem) throw new Error(problem);
9114
+ const rows = await this.#rows(db, `SELECT * FROM ${this.#pages} WHERE "parentId" = $1 AND "key" = $2 AND "deletedAt" IS NULL`, [parent.id, template.key]);
9115
+ const page = rows[0] === void 0 ? await this.#insertPage(db, {
9116
+ parent,
9117
+ key: template.key,
9118
+ name: template.name,
9119
+ description: template.description,
9120
+ provenance,
9121
+ at
9122
+ }) : toPage(rows[0]);
9123
+ if (template.pages?.length) await this.#materializeTemplates(db, page, template.pages, provenance, at);
9124
+ }
9125
+ }
9126
+ async #scopeByAddress(db, address) {
9127
+ const rows = await this.#rows(db, `SELECT * FROM ${this.#pages} WHERE "isScope" AND "address" = $1`, [address]);
9128
+ return rows[0] ? toPage(rows[0]) : null;
9129
+ }
9130
+ async #insertScope(db, input) {
9131
+ const core = await loadPagesCore();
9132
+ const id = createKnowledgeUlid();
9133
+ const position = core.knowledgePositionBetween(await this.#lastPosition(db, input.parentId));
9134
+ const rows = await this.#rows(db, `INSERT INTO ${this.#pages} ("id","scopeId","parentId","isScope","address","declaration","position","name","canonicalName","description","depth","version","createdBy","updatedBy","createdAt","updatedAt")
9135
+ VALUES ($1,$1,$2,TRUE,$3,$4,$5,$6,$7,$8,0,1,$9::jsonb,$9::jsonb,$10,$10) RETURNING *`, [
9136
+ id,
9137
+ input.parentId,
9138
+ input.address,
9139
+ input.declaration,
9140
+ position,
9141
+ input.name,
9142
+ core.canonicalKnowledgeName(input.name),
9143
+ input.description ?? null,
9144
+ JSON.stringify(input.provenance),
9145
+ iso(input.at)
9146
+ ]);
9147
+ await this.#logActivity(db, {
9148
+ action: "scope-created",
9149
+ scopeId: id,
9150
+ pageId: id,
9151
+ provenance: input.provenance,
9152
+ at: input.at
9153
+ });
9154
+ return toPage(rows[0]);
9155
+ }
9156
+ async getScopesByAddress(addresses) {
9157
+ if (addresses.length === 0) return [];
9158
+ const rows = await this.#rows(this.#client, `SELECT * FROM ${this.#pages} WHERE "isScope" AND "address" = ANY($1::text[])`, [addresses]);
9159
+ const byAddress = new Map(rows.map((row) => [String(row.address), toPage(row)]));
9160
+ return [...new Set(addresses)].flatMap((address) => byAddress.get(address) ?? []);
9161
+ }
9162
+ async listScopeDeclarations() {
9163
+ return (await this.#rows(this.#client, `SELECT "declaration", COUNT(*)::int AS "scopes" FROM ${this.#pages}
9164
+ WHERE "isScope" AND "declaration" IS NOT NULL
9165
+ GROUP BY "declaration" ORDER BY "declaration" COLLATE "C"`, [])).map((row) => ({
9166
+ declaration: String(row.declaration),
9167
+ scopes: Number(row.scopes)
9168
+ }));
8870
9169
  }
8871
- };
8872
- const KNOWLEDGE_SCOPE_GRANTS_SCHEMA = {
8873
- scopeNodeId: {
8874
- type: "text",
8875
- nullable: false,
8876
- references: {
8877
- table: TABLE_KNOWLEDGE_NODES$1,
8878
- column: "id"
8879
- }
8880
- },
8881
- scopeRefId: {
8882
- type: "text",
8883
- nullable: false,
8884
- references: {
8885
- table: TABLE_KNOWLEDGE_NODES$1,
8886
- column: "id"
9170
+ async renameScopeDeclaration(input) {
9171
+ return this.#tx(async (tx) => {
9172
+ const rows = await this.#rows(tx, `SELECT "id", "address", "declaration" FROM ${this.#pages}
9173
+ WHERE "isScope" AND ("declaration" = $1 OR starts_with("declaration", $2))
9174
+ ORDER BY "id" FOR UPDATE`, [input.from, `${input.from}/`]);
9175
+ if (rows.length === 0) return 0;
9176
+ const renames = rows.map((row) => ({
9177
+ address: String(row.address),
9178
+ from: String(row.declaration),
9179
+ to: input.to + String(row.declaration).slice(input.from.length)
9180
+ }));
9181
+ input.check(renames);
9182
+ await tx.query(`UPDATE ${this.#pages} p SET "declaration" = r."to"
9183
+ FROM unnest($1::text[], $2::text[]) AS r("id", "to") WHERE p."id" = r."id"`, [rows.map((row) => String(row.id)), renames.map((rename) => rename.to)]);
9184
+ return rows.length;
9185
+ });
9186
+ }
9187
+ async listChildScopes(input) {
9188
+ const core = await loadPagesCore();
9189
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
9190
+ const params = new Params();
9191
+ const where = [`"isScope"`, `"deletedAt" IS NULL`];
9192
+ where.push(input.parentId === null ? `"parentId" IS NULL` : `"parentId" = ${params.add(input.parentId)}`);
9193
+ if (input.cursor) {
9194
+ const [position, id] = decodeCursor(input.cursor, 2);
9195
+ where.push(`("position", "id") > (${params.add(position)}, ${params.add(id)})`);
8887
9196
  }
8888
- },
8889
- role: {
8890
- type: "text",
8891
- nullable: false
8892
- },
8893
- canSuggest: {
8894
- type: "boolean",
8895
- nullable: true
9197
+ const rows = await this.#rows(this.#client, `SELECT * FROM ${this.#pages} WHERE ${where.join(" AND ")} ORDER BY "position", "id" LIMIT ${limit + 1}`, params.values);
9198
+ return this.#pageOutput(rows, limit, (page) => [page.position, page.id]);
8896
9199
  }
8897
- };
8898
- const KNOWLEDGE_ACCESS_STATE_SCHEMA = {
8899
- id: {
8900
- type: "text",
8901
- nullable: false,
8902
- primaryKey: true
8903
- },
8904
- epoch: {
8905
- type: "integer",
8906
- nullable: false
8907
- },
8908
- schemaVersion: {
8909
- type: "integer",
8910
- nullable: false
9200
+ #pageOutput(rows, limit, cursorOf) {
9201
+ const pages = rows.slice(0, limit).map(toPage);
9202
+ const last = pages[pages.length - 1];
9203
+ return {
9204
+ pages,
9205
+ ...rows.length > limit && last ? { nextCursor: encodeCursor(cursorOf(last)) } : {}
9206
+ };
8911
9207
  }
8912
- };
8913
- const KNOWLEDGE_SCOPE_ADDRESSES_SCHEMA = {
8914
- address: {
8915
- type: "text",
8916
- nullable: false,
8917
- primaryKey: true
8918
- },
8919
- scopeNodeId: {
8920
- type: "text",
8921
- nullable: false,
8922
- references: {
8923
- table: TABLE_KNOWLEDGE_NODES$1,
8924
- column: "id"
8925
- }
9208
+ async getPage(input) {
9209
+ const params = new Params();
9210
+ const id = params.add(input.id);
9211
+ const filter = new ReadFilter(input.read, params, this.#pages);
9212
+ const rows = await this.#rows(this.#client, `SELECT p.* FROM ${this.#pages} p JOIN ${this.#pages} s ON s."id" = p."scopeId" WHERE p."id" = ${id} AND ${filter.readable("s")}`, params.values);
9213
+ return rows[0] ? toPage(rows[0]) : null;
9214
+ }
9215
+ async getPageByPath(input) {
9216
+ if (!input.path.length) return null;
9217
+ let page;
9218
+ let parentId = input.scopeId;
9219
+ for (const key of input.path) {
9220
+ const params = new Params();
9221
+ const filter = new ReadFilter(input.read, params, this.#pages);
9222
+ const rows = await this.#rows(this.#client, `SELECT p.* FROM ${this.#pages} p JOIN ${this.#pages} s ON s."id" = p."scopeId"
9223
+ WHERE p."parentId" = ${params.add(parentId)} AND p."key" = ${params.add(key)} AND p."deletedAt" IS NULL AND NOT p."isScope" AND ${filter.readable("s")}`, params.values);
9224
+ if (!rows[0]) return null;
9225
+ page = toPage(rows[0]);
9226
+ parentId = page.id;
9227
+ }
9228
+ return page ?? null;
9229
+ }
9230
+ async findPagesByName(input) {
9231
+ const core = await loadPagesCore();
9232
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
9233
+ const params = new Params();
9234
+ const where = [`p."canonicalName" = ${params.add(core.canonicalKnowledgeName(input.name))}`, `p."deletedAt" IS NULL`];
9235
+ if (input.scopeId) where.push(`p."scopeId" = ${params.add(input.scopeId)}`);
9236
+ const filter = new ReadFilter(input.read, params, this.#pages);
9237
+ where.push(filter.readable("s"));
9238
+ return (await this.#rows(this.#client, `SELECT p.* FROM ${this.#pages} p JOIN ${this.#pages} s ON s."id" = p."scopeId"
9239
+ WHERE ${where.join(" AND ")} ORDER BY p."createdAt" DESC, p."id" DESC LIMIT ${limit}`, params.values)).map(toPage);
9240
+ }
9241
+ async listChildPages(input) {
9242
+ const core = await loadPagesCore();
9243
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
9244
+ const params = new Params();
9245
+ const where = [
9246
+ `p."parentId" = ${params.add(input.parentId)}`,
9247
+ `NOT p."isScope"`,
9248
+ `p."deletedAt" IS NULL`
9249
+ ];
9250
+ const filter = new ReadFilter(input.read, params, this.#pages);
9251
+ where.push(filter.readable("s"));
9252
+ if (input.cursor) {
9253
+ const [position, id] = decodeCursor(input.cursor, 2);
9254
+ where.push(`(p."position", p."id") > (${params.add(position)}, ${params.add(id)})`);
9255
+ }
9256
+ const rows = await this.#rows(this.#client, `SELECT p.* FROM ${this.#pages} p JOIN ${this.#pages} s ON s."id" = p."scopeId"
9257
+ WHERE ${where.join(" AND ")} ORDER BY p."position", p."id" LIMIT ${limit + 1}`, params.values);
9258
+ return this.#pageOutput(rows, limit, (page) => [page.position, page.id]);
9259
+ }
9260
+ async listPages(input) {
9261
+ const core = await loadPagesCore();
9262
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
9263
+ const params = new Params();
9264
+ const filter = new ReadFilter(input.read, params, this.#pages);
9265
+ const where = [
9266
+ `p."scopeId" = r."id"`,
9267
+ `NOT p."isScope"`,
9268
+ `p."deletedAt" IS NULL`
9269
+ ];
9270
+ if (input.namePrefix) where.push(`starts_with(p."canonicalName", ${params.add(core.canonicalKnowledgeName(input.namePrefix))})`);
9271
+ if (input.cursor) {
9272
+ const [name, id] = decodeCursor(input.cursor, 2);
9273
+ where.push(`(p."name", p."id") > (${params.add(name)}, ${params.add(id)})`);
9274
+ }
9275
+ if (filter.all) {
9276
+ const direct = where.slice(1);
9277
+ if (input.scopeId) direct.unshift(`p."scopeId" = ${params.add(input.scopeId)}`);
9278
+ const rows = await this.#rows(this.#client, `SELECT p.* FROM ${this.#pages} p WHERE ${direct.join(" AND ")} ORDER BY p."name", p."id" LIMIT ${limit + 1}`, params.values);
9279
+ return this.#pageOutput(rows, limit, (page) => [page.name, page.id]);
9280
+ }
9281
+ const scopes = input.scopeId ? `SELECT "id" FROM (${filter.readableIds()}) ri WHERE "id" = ${params.add(input.scopeId)}` : filter.readableIds();
9282
+ const rows = await this.#rows(this.#client, `SELECT x.* FROM (${scopes}) r CROSS JOIN LATERAL (
9283
+ SELECT p.* FROM ${this.#pages} p WHERE ${where.join(" AND ")} ORDER BY p."name", p."id" LIMIT ${limit + 1}
9284
+ ) x ORDER BY x."name", x."id" LIMIT ${limit + 1}`, params.values);
9285
+ return this.#pageOutput(rows, limit, (page) => [page.name, page.id]);
9286
+ }
9287
+ async createPage(input) {
9288
+ (await this.#bounds()).assertKnowledgePageDescriptionWithinBound(input.description);
9289
+ await loadPagesCore();
9290
+ if (input.key !== void 0) {
9291
+ const problem = knowledgePageKeyProblem(input.key);
9292
+ if (problem) throw new Error(problem);
9293
+ }
9294
+ return this.#tx(async (tx) => {
9295
+ const parent = await this.#requireLivePage(tx, input.parentId);
9296
+ return this.#insertPage(tx, {
9297
+ id: input.id,
9298
+ parent,
9299
+ key: input.key,
9300
+ name: input.name,
9301
+ description: input.description,
9302
+ body: input.body,
9303
+ position: input.position,
9304
+ provenance: input.provenance,
9305
+ at: /* @__PURE__ */ new Date()
9306
+ });
9307
+ });
8926
9308
  }
8927
- };
8928
- const KNOWLEDGE_NODE_ADDRESSES_SCHEMA = {
8929
- source: {
8930
- type: "text",
8931
- nullable: false
8932
- },
8933
- address: {
8934
- type: "text",
8935
- nullable: false
8936
- },
8937
- nodeId: {
8938
- type: "text",
8939
- nullable: false,
8940
- references: {
8941
- table: TABLE_KNOWLEDGE_NODES$1,
8942
- column: "id"
9309
+ async #insertPage(db, input) {
9310
+ const core = await loadPagesCore();
9311
+ const id = input.id ?? createKnowledgeUlid();
9312
+ const scopeId = input.parent.isScope ? input.parent.id : input.parent.scopeId;
9313
+ const depth = input.parent.isScope ? 1 : await this.#depthOf(db, input.parent.id) + 1;
9314
+ if (depth > core.MAX_KNOWLEDGE_PAGE_DEPTH) throw new core.KnowledgePageDepthError(id);
9315
+ const position = input.position ?? core.knowledgePositionBetween(await this.#lastPosition(db, input.parent.id));
9316
+ try {
9317
+ const rows = await this.#rows(db, `INSERT INTO ${this.#pages} ("id","scopeId","parentId","isScope","key","position","name","canonicalName","description","body","depth","version","createdBy","updatedBy","createdAt","updatedAt")
9318
+ VALUES ($1,$2,$3,FALSE,$4,$5,$6,$7,$8,$9,$10,1,$11::jsonb,$11::jsonb,$12,$12) RETURNING *`, [
9319
+ id,
9320
+ scopeId,
9321
+ input.parent.id,
9322
+ input.key ?? null,
9323
+ position,
9324
+ input.name,
9325
+ core.canonicalKnowledgeName(input.name),
9326
+ input.description ?? null,
9327
+ input.body ?? null,
9328
+ depth,
9329
+ JSON.stringify(input.provenance),
9330
+ iso(input.at)
9331
+ ]);
9332
+ await this.#logActivity(db, {
9333
+ action: "page-created",
9334
+ scopeId,
9335
+ pageId: id,
9336
+ provenance: input.provenance,
9337
+ at: input.at
9338
+ });
9339
+ return toPage(rows[0]);
9340
+ } catch (error) {
9341
+ if (isUniqueViolation$1(error)) {
9342
+ if (input.key) throw new core.KnowledgePageKeyConflictError(input.key, input.parent.id);
9343
+ throw new KnowledgeConflictError(id);
9344
+ }
9345
+ throw error;
8943
9346
  }
8944
9347
  }
8945
- };
8946
- const KNOWLEDGE_IMPORT_STATE_SCHEMA = {
8947
- importerId: {
8948
- type: "text",
8949
- nullable: false
8950
- },
8951
- binding: {
8952
- type: "text",
8953
- nullable: false
8954
- },
8955
- key: {
8956
- type: "text",
8957
- nullable: false
8958
- },
8959
- value: {
8960
- type: "text",
8961
- nullable: false
9348
+ async #depthOf(db, id) {
9349
+ const rows = await this.#rows(db, `SELECT "depth" FROM ${this.#pages} WHERE "id" = $1`, [id]);
9350
+ return Number(rows[0]?.depth ?? 0);
8962
9351
  }
8963
- };
8964
- const KNOWLEDGE_IMPORT_RUNS_SCHEMA = {
8965
- id: {
8966
- type: "text",
8967
- nullable: false,
8968
- primaryKey: true
8969
- },
8970
- importerId: {
8971
- type: "text",
8972
- nullable: false
8973
- },
8974
- binding: {
8975
- type: "text",
8976
- nullable: false
8977
- },
8978
- importKind: {
8979
- type: "text",
8980
- nullable: false
8981
- },
8982
- triggerKind: {
8983
- type: "text",
8984
- nullable: false
8985
- },
8986
- status: {
8987
- type: "text",
8988
- nullable: false
8989
- },
8990
- error: {
8991
- type: "text",
8992
- nullable: true
8993
- },
8994
- transcriptThreadId: {
8995
- type: "text",
8996
- nullable: true
8997
- },
8998
- traceId: {
8999
- type: "text",
9000
- nullable: true
9001
- },
9002
- queuedAt: {
9003
- type: "timestamp",
9004
- nullable: false
9005
- },
9006
- startedAt: {
9007
- type: "timestamp",
9008
- nullable: true
9009
- },
9010
- completedAt: {
9011
- type: "timestamp",
9012
- nullable: true
9352
+ async updatePage(input) {
9353
+ const core = await loadPagesCore();
9354
+ (await this.#bounds()).assertKnowledgePageDescriptionWithinBound(input.description);
9355
+ return this.#tx(async (tx) => {
9356
+ const page = await this.#requireLivePage(tx, input.id);
9357
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(input.id);
9358
+ const now = /* @__PURE__ */ new Date();
9359
+ const sets = [
9360
+ `"version" = "version" + 1`,
9361
+ `"updatedAt" = $2`,
9362
+ `"updatedBy" = $3::jsonb`
9363
+ ];
9364
+ const params = new Params();
9365
+ params.add(input.id);
9366
+ params.add(iso(now));
9367
+ params.add(JSON.stringify(input.provenance));
9368
+ if (input.name !== void 0) sets.push(`"name" = ${params.add(input.name)}`, `"canonicalName" = ${params.add(core.canonicalKnowledgeName(input.name))}`);
9369
+ if (input.description !== void 0) sets.push(`"description" = ${params.add(input.description === "" ? null : input.description)}`);
9370
+ if (input.body !== void 0) sets.push(`"body" = ${params.add(input.body)}`);
9371
+ const rows = await this.#rows(tx, `UPDATE ${this.#pages} SET ${sets.join(", ")} WHERE "id" = $1 RETURNING *`, params.values);
9372
+ await this.#logActivity(tx, {
9373
+ action: "page-updated",
9374
+ scopeId: page.scopeId,
9375
+ pageId: page.id,
9376
+ provenance: input.provenance,
9377
+ at: now
9378
+ });
9379
+ return toPage(rows[0]);
9380
+ });
9381
+ }
9382
+ async movePage(input) {
9383
+ const core = await loadPagesCore();
9384
+ return this.#tx(async (tx) => {
9385
+ const page = await this.#requireLivePage(tx, input.id);
9386
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(input.id);
9387
+ if (page.isScope) throw new Error(`Knowledge scope page ${input.id} can't be moved`);
9388
+ if (input.parentId === input.id || await this.#isInSubtree(tx, input.id, input.parentId)) throw new Error(`Knowledge page ${input.id} can't move under itself or its own subtree`);
9389
+ const parent = await this.#requireLivePage(tx, input.parentId);
9390
+ const stats = await this.#subtreeStats(tx, input.id);
9391
+ if (stats.live + 1 > core.MAX_KNOWLEDGE_MOVE_PAGES) throw new core.KnowledgeMoveTooLargeError(input.id, stats.live + 1);
9392
+ const newScopeId = parent.isScope ? parent.id : parent.scopeId;
9393
+ const newDepth = parent.isScope ? 1 : await this.#depthOf(tx, parent.id) + 1;
9394
+ const delta = newDepth - await this.#depthOf(tx, page.id);
9395
+ await this.#assertNoKeyConflicts(tx, { rootId: input.id }, parent.id);
9396
+ if (stats.maxDepth + delta > core.MAX_KNOWLEDGE_PAGE_DEPTH || newDepth > core.MAX_KNOWLEDGE_PAGE_DEPTH) throw new core.KnowledgePageDepthError(input.id);
9397
+ const position = input.position ?? core.knowledgePositionBetween(await this.#lastPosition(tx, parent.id));
9398
+ const now = /* @__PURE__ */ new Date();
9399
+ try {
9400
+ await tx.query(`${this.#subtree("$1")} UPDATE ${this.#pages} SET "scopeId" = $2, "depth" = "depth" + $3 WHERE "id" IN (SELECT "id" FROM sub)`, [
9401
+ input.id,
9402
+ newScopeId,
9403
+ delta
9404
+ ]);
9405
+ const rows = await this.#rows(tx, `UPDATE ${this.#pages} SET "parentId" = $2, "scopeId" = $3, "depth" = $4, "position" = $5, "version" = "version" + 1, "updatedAt" = $6, "updatedBy" = $7::jsonb WHERE "id" = $1 RETURNING *`, [
9406
+ input.id,
9407
+ parent.id,
9408
+ newScopeId,
9409
+ newDepth,
9410
+ position,
9411
+ iso(now),
9412
+ JSON.stringify(input.provenance)
9413
+ ]);
9414
+ await this.#logActivity(tx, {
9415
+ action: "page-moved",
9416
+ scopeId: newScopeId,
9417
+ pageId: input.id,
9418
+ provenance: input.provenance,
9419
+ at: now
9420
+ });
9421
+ return toPage(rows[0]);
9422
+ } catch (error) {
9423
+ if (isUniqueViolation$1(error)) throw new KnowledgeConflictError(page.key ? `${newScopeId}#${page.key}` : input.id);
9424
+ throw error;
9425
+ }
9426
+ });
9013
9427
  }
9014
- };
9015
- const KNOWLEDGE_V2_ACTIVITY_SCHEMA = {
9016
- id: {
9017
- type: "text",
9018
- nullable: false,
9019
- primaryKey: true
9020
- },
9021
- action: {
9022
- type: "text",
9023
- nullable: false
9024
- },
9025
- targetType: {
9026
- type: "text",
9027
- nullable: true
9028
- },
9029
- targetId: {
9030
- type: "text",
9031
- nullable: true
9032
- },
9033
- contextScopeId: {
9034
- type: "text",
9035
- nullable: true,
9036
- references: {
9037
- table: TABLE_KNOWLEDGE_NODES$1,
9038
- column: "id"
9039
- }
9040
- },
9041
- importRunId: {
9042
- type: "text",
9043
- nullable: true,
9044
- references: {
9045
- table: TABLE_KNOWLEDGE_IMPORT_RUNS,
9046
- column: "id"
9428
+ async mergePages(input) {
9429
+ const core = await loadPagesCore();
9430
+ return this.#tx(async (tx) => {
9431
+ if (input.sourceId === input.targetId) throw new Error(`Knowledge page ${input.sourceId} can't merge into itself or its own subtree`);
9432
+ const [firstId, secondId] = [input.sourceId, input.targetId].sort();
9433
+ await this.#lockPage(tx, firstId);
9434
+ await this.#lockPage(tx, secondId);
9435
+ const source = await this.#requireLivePage(tx, input.sourceId, false);
9436
+ const target = await this.#requireLivePage(tx, input.targetId, false);
9437
+ if (source.version !== input.sourceVersion) throw new KnowledgeConflictError(input.sourceId);
9438
+ if (source.isScope || target.isScope) throw new Error("Knowledge scope pages can't be merged");
9439
+ if (await this.#isInSubtree(tx, source.id, target.id)) throw new Error(`Knowledge page ${source.id} can't merge into itself or its own subtree`);
9440
+ const stats = await this.#subtreeStats(tx, source.id);
9441
+ if (stats.live > core.MAX_KNOWLEDGE_MOVE_PAGES) throw new core.KnowledgeMoveTooLargeError(source.id, stats.live);
9442
+ const delta = await this.#depthOf(tx, target.id) - await this.#depthOf(tx, source.id);
9443
+ await this.#assertNoKeyConflicts(tx, { childrenOf: source.id }, target.id, source.id);
9444
+ if (stats.maxDepth > 0 && stats.maxDepth + delta > core.MAX_KNOWLEDGE_PAGE_DEPTH) throw new core.KnowledgePageDepthError(source.id);
9445
+ const now = /* @__PURE__ */ new Date();
9446
+ await tx.query(`UPDATE ${this.#pages} SET "deletedAt" = $2, "deletedBy" = $3, "mergedInto" = $4, "scopeId" = $6, "version" = "version" + 1, "updatedAt" = $2, "updatedBy" = $5::jsonb WHERE "id" = $1`, [
9447
+ source.id,
9448
+ iso(now),
9449
+ input.provenance.author,
9450
+ target.id,
9451
+ JSON.stringify(input.provenance),
9452
+ target.scopeId
9453
+ ]);
9454
+ try {
9455
+ await tx.query(`${this.#subtree("$1")} UPDATE ${this.#pages} SET "scopeId" = $2, "depth" = "depth" + $3 WHERE "id" IN (SELECT "id" FROM sub)`, [
9456
+ source.id,
9457
+ target.scopeId,
9458
+ delta
9459
+ ]);
9460
+ await tx.query(`UPDATE ${this.#pages} SET "parentId" = $2 WHERE "parentId" = $1 AND NOT "isScope"`, [source.id, target.id]);
9461
+ } catch (error) {
9462
+ if (isUniqueViolation$1(error)) throw new KnowledgeConflictError(source.id);
9463
+ throw error;
9464
+ }
9465
+ await tx.query(`UPDATE ${this.#notes} SET "pageId" = $2 WHERE "pageId" = $1`, [source.id, target.id]);
9466
+ await tx.query(`DELETE FROM ${this.#mentions} m WHERE m."pageId" = $1 AND EXISTS (SELECT 1 FROM ${this.#mentions} t WHERE t."noteId" = m."noteId" AND t."pageId" = $2)`, [source.id, target.id]);
9467
+ await tx.query(`UPDATE ${this.#mentions} SET "pageId" = $2 WHERE "pageId" = $1`, [source.id, target.id]);
9468
+ const sourcePin = (await this.#rows(tx, `SELECT * FROM ${this.#pins} WHERE "pageId" = $1 FOR UPDATE`, [source.id]))[0];
9469
+ if (sourcePin) {
9470
+ await this.#upsertPinAudience(tx, target.id, sourcePin.audience ?? [], String(sourcePin.createdBy), now);
9471
+ await tx.query(`DELETE FROM ${this.#pins} WHERE "id" = $1`, [String(sourcePin.id)]);
9472
+ }
9473
+ const rows = await this.#rows(tx, `SELECT * FROM ${this.#pages} WHERE "id" = $1`, [target.id]);
9474
+ await this.#logActivity(tx, {
9475
+ action: "page-merged",
9476
+ scopeId: target.scopeId,
9477
+ pageId: source.id,
9478
+ provenance: input.provenance,
9479
+ at: now
9480
+ });
9481
+ return toPage(rows[0]);
9482
+ });
9483
+ }
9484
+ async deletePage(input) {
9485
+ const core = await loadPagesCore();
9486
+ return this.#tx(async (tx) => {
9487
+ const page = await this.#requireLivePage(tx, input.id);
9488
+ if (page.version !== input.expectedVersion) throw new KnowledgeConflictError(input.id);
9489
+ if (page.isScope) throw new Error(`Knowledge scope page ${input.id} can't be deleted`);
9490
+ if ((await this.#rows(tx, `SELECT 1 FROM ${this.#pages} WHERE "parentId" = $1 AND "deletedAt" IS NULL LIMIT 1`, [input.id])).length) throw new core.KnowledgePageHasChildrenError(input.id);
9491
+ const now = /* @__PURE__ */ new Date();
9492
+ const rows = await this.#rows(tx, `UPDATE ${this.#pages} SET "deletedAt" = $2, "deletedBy" = $3, "version" = "version" + 1, "updatedAt" = $2, "updatedBy" = $4::jsonb WHERE "id" = $1 RETURNING *`, [
9493
+ input.id,
9494
+ iso(now),
9495
+ input.deletedBy,
9496
+ JSON.stringify({ author: input.deletedBy })
9497
+ ]);
9498
+ await tx.query(`DELETE FROM ${this.#pins} WHERE "pageId" = $1`, [input.id]);
9499
+ await this.#logActivity(tx, {
9500
+ action: "page-deleted",
9501
+ scopeId: page.scopeId,
9502
+ pageId: page.id,
9503
+ provenance: { author: input.deletedBy },
9504
+ at: now
9505
+ });
9506
+ return toPage(rows[0]);
9507
+ });
9508
+ }
9509
+ async getNote(input) {
9510
+ const params = new Params();
9511
+ const id = params.add(input.id);
9512
+ const filter = new ReadFilter(input.read, params, this.#pages);
9513
+ const rows = await this.#rows(this.#client, `SELECT ${this.#noteColumns()} FROM ${this.#visibleNotes(filter)} AND n."id" = ${id}${input.includeDeleted ? "" : " AND n.\"deletedAt\" IS NULL"}`, params.values);
9514
+ return rows[0] ? toNote(rows[0]) : null;
9515
+ }
9516
+ async listNotes(input) {
9517
+ const core = await loadPagesCore();
9518
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
9519
+ const params = new Params();
9520
+ const filter = new ReadFilter(input.read, params, this.#pages);
9521
+ const extra = [`n."pageId" = ${params.add(input.pageId)}`];
9522
+ if (!input.includeDeleted) extra.push(`n."deletedAt" IS NULL`);
9523
+ if (input.cursor) {
9524
+ const [createdAt, id] = decodeCursor(input.cursor, 2);
9525
+ extra.push(`(n."createdAt", n."id") > (${params.add(createdAt)}::timestamptz, ${params.add(id)})`);
9526
+ }
9527
+ const rows = await this.#rows(this.#client, `SELECT ${this.#noteColumns()} FROM ${this.#visibleNotes(filter)} AND ${extra.join(" AND ")} ORDER BY n."createdAt", n."id" LIMIT ${limit + 1}`, params.values);
9528
+ return this.#noteOutput(rows, limit);
9529
+ }
9530
+ async countNotes(input) {
9531
+ const ids = [...new Set(input.pageIds)];
9532
+ const counts = Object.fromEntries(ids.map((id) => [id, 0]));
9533
+ if (!ids.length) return counts;
9534
+ const params = new Params();
9535
+ const filter = new ReadFilter(input.read, params, this.#pages);
9536
+ const rows = await this.#rows(this.#client, `SELECT n."pageId" AS "pageId", count(*)::int AS "count" FROM ${this.#visibleNotes(filter)} AND n."deletedAt" IS NULL AND n."pageId" = ANY(${params.add(ids)}::text[]) GROUP BY n."pageId"`, params.values);
9537
+ for (const row of rows) counts[row.pageId] = Number(row.count);
9538
+ return counts;
9539
+ }
9540
+ async listNotesMentioning(input) {
9541
+ const core = await loadPagesCore();
9542
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
9543
+ const params = new Params();
9544
+ const filter = new ReadFilter(input.read, params, this.#pages);
9545
+ const pageParam = params.add(input.pageId);
9546
+ const extra = [
9547
+ `n."deletedAt" IS NULL`,
9548
+ `n."pageId" <> ${pageParam}`,
9549
+ `np."deletedAt" IS NULL`,
9550
+ `EXISTS (SELECT 1 FROM ${this.#mentions} tm WHERE tm."noteId" = n."id" AND tm."pageId" = ${pageParam})`
9551
+ ];
9552
+ if (input.cursor) {
9553
+ const [createdAt, id] = decodeCursor(input.cursor, 2);
9554
+ extra.push(`(n."createdAt", n."id") < (${params.add(createdAt)}::timestamptz, ${params.add(id)})`);
9047
9555
  }
9048
- },
9049
- details: {
9050
- type: "jsonb",
9051
- nullable: true
9052
- },
9053
- createdAt: {
9054
- type: "timestamp",
9055
- nullable: false
9056
- },
9057
- recordType: {
9058
- type: "text",
9059
- nullable: true
9060
- },
9061
- recordId: {
9062
- type: "text",
9063
- nullable: true
9064
- },
9065
- scope: {
9066
- type: "jsonb",
9067
- nullable: true
9068
- },
9069
- scopeKey: {
9070
- type: "text",
9071
- nullable: true
9072
- },
9073
- sourceThreadId: {
9074
- type: "text",
9075
- nullable: true
9556
+ const rows = await this.#rows(this.#client, `SELECT ${this.#noteColumns()} FROM ${this.#visibleNotes(filter)} AND ${extra.join(" AND ")} ORDER BY n."createdAt" DESC, n."id" DESC LIMIT ${limit + 1}`, params.values);
9557
+ return this.#noteOutput(rows, limit);
9076
9558
  }
9077
- };
9078
- const KNOWLEDGE_PROPOSALS_SCHEMA = {
9079
- id: {
9080
- type: "text",
9081
- nullable: false,
9082
- primaryKey: true
9083
- },
9084
- targetType: {
9085
- type: "text",
9086
- nullable: false
9087
- },
9088
- targetId: {
9089
- type: "text",
9090
- nullable: false
9091
- },
9092
- action: {
9093
- type: "text",
9094
- nullable: false
9095
- },
9096
- changes: {
9097
- type: "jsonb",
9098
- nullable: false
9099
- },
9100
- reason: {
9101
- type: "text",
9102
- nullable: true
9103
- },
9104
- proposerContextScopeId: {
9105
- type: "text",
9106
- nullable: false
9107
- },
9108
- expectedVersion: {
9109
- type: "integer",
9110
- nullable: false
9111
- },
9112
- status: {
9113
- type: "text",
9114
- nullable: false
9115
- },
9116
- reviewerContextScopeId: {
9117
- type: "text",
9118
- nullable: true
9119
- },
9120
- reviewedAt: {
9121
- type: "timestamp",
9122
- nullable: true
9123
- },
9124
- createdAt: {
9125
- type: "timestamp",
9126
- nullable: false
9559
+ #noteOutput(rows, limit) {
9560
+ const notes = rows.slice(0, limit).map(toNote);
9561
+ const last = notes[notes.length - 1];
9562
+ return {
9563
+ notes,
9564
+ ...rows.length > limit && last ? { nextCursor: encodeCursor([iso(last.createdAt), last.id]) } : {}
9565
+ };
9127
9566
  }
9128
- };
9129
- function assertKnowledgeV2CoreSupport(features) {
9130
- if (!features.has("knowledge-v2")) throw new Error(`Knowledge v2 requires a @mastra/core release with the "${KNOWLEDGE_V2_CORE_FEATURE}" feature. Upgrade @mastra/core to use Knowledge; other storage domains keep working on this version.`);
9131
- }
9132
- function resolveKnowledgeV2Core(storageModule) {
9133
- if (typeof storageModule !== "object" || storageModule === null) throw new Error("@mastra/core advertises Knowledge v2 without the required storage API");
9134
- const { assertKnowledgeDescriptionWithinBound: assertDescription, assertKnowledgeRecordTextWithinBound: assertRecordText, assertKnowledgeSchemaCompatible: assertCompatible, inspectKnowledgeSchema: inspectSchema } = storageModule;
9135
- if (typeof assertDescription !== "function" || typeof assertRecordText !== "function" || typeof assertCompatible !== "function" || typeof inspectSchema !== "function") throw new Error("@mastra/core advertises Knowledge v2 without the required storage API");
9136
- return {
9137
- assertKnowledgeDescriptionWithinBound: (description) => assertDescription(description),
9138
- assertKnowledgeRecordTextWithinBound: (text) => assertRecordText(text),
9139
- assertKnowledgeSchemaCompatible: (inspection) => assertCompatible(inspection),
9140
- inspectKnowledgeSchema: (snapshot) => inspectSchema(snapshot)
9141
- };
9142
- }
9143
- function createKnowledgeV2CoreLoader(features, loadStorageModule) {
9144
- let knowledgeV2Core;
9145
- return async () => {
9146
- assertKnowledgeV2CoreSupport(features);
9147
- knowledgeV2Core ??= loadStorageModule().then(resolveKnowledgeV2Core).catch((error) => {
9148
- knowledgeV2Core = void 0;
9149
- throw error;
9150
- });
9151
- return knowledgeV2Core;
9152
- };
9153
- }
9154
- // src/storage/domains/knowledge/index.ts
9155
- const loadKnowledgeV2Core = createKnowledgeV2CoreLoader(coreFeatures, () => import("@mastra/core/storage"));
9156
- async function assertKnowledgeDescriptionWithinBoundCompat(description) {
9157
- const { assertKnowledgeDescriptionWithinBound } = await loadKnowledgeV2Core();
9158
- assertKnowledgeDescriptionWithinBound(description);
9159
- }
9160
- async function assertKnowledgeRecordTextWithinBoundCompat(text) {
9161
- const { assertKnowledgeRecordTextWithinBound } = await loadKnowledgeV2Core();
9162
- assertKnowledgeRecordTextWithinBound(text);
9163
- }
9164
- const camelCaseColumns = [
9165
- "canonicalName",
9166
- "scopeKey",
9167
- "mergedInto",
9168
- "createdAt",
9169
- "updatedAt",
9170
- "node",
9171
- "sourceThreadId",
9172
- "capturedAt",
9173
- "deletedAt",
9174
- "deletedBy",
9175
- "sourceType",
9176
- "sourceId",
9177
- "recordId",
9178
- "lastKnowledgeId",
9179
- "recordType",
9180
- "idempotencyKey",
9181
- "documentId",
9182
- "documentType",
9183
- "availableAt",
9184
- "claimedAt",
9185
- "claimedBy",
9186
- "completedAt",
9187
- "isScope",
9188
- "nodeId",
9189
- "targetNodeId",
9190
- "scopeNodeId",
9191
- "scopeRefId",
9192
- "canSuggest",
9193
- "schemaVersion",
9194
- "importerId",
9195
- "importKind",
9196
- "triggerKind",
9197
- "transcriptThreadId",
9198
- "traceId",
9199
- "queuedAt",
9200
- "startedAt",
9201
- "targetType",
9202
- "targetId",
9203
- "contextScopeId",
9204
- "importRunId",
9205
- "proposerContextScopeId",
9206
- "expectedVersion",
9207
- "reviewerContextScopeId",
9208
- "reviewedAt",
9209
- "addedAt"
9210
- ];
9211
- function transformSqlCode(sql, transform) {
9212
- return sql.split(/('(?:''|[^'])*')/g).map((part, index) => index % 2 === 0 ? transform(part) : part).join("");
9213
- }
9214
- function postgresSql(sql, schemaName) {
9215
- let normalized = transformSqlCode(sql, (code) => {
9216
- let transformed = code.replace(/jsonb\(\?\)/g, "?::jsonb");
9217
- for (const column of camelCaseColumns) transformed = transformed.replace(new RegExp(`(?<!")\\b${column}\\b(?!")`, "g"), `"${column}"`);
9218
- return transformed;
9219
- });
9220
- if (schemaName) {
9221
- const quotedSchema = `"${parseSchemaName(schemaName)}"`;
9222
- normalized = transformSqlCode(normalized, (code) => {
9223
- let transformed = code;
9224
- for (const table of [...KNOWLEDGE_TABLE_NAMES, ...RETIRED_KNOWLEDGE_TABLE_NAMES]) transformed = transformed.replaceAll(`"${table}"`, `${quotedSchema}."${table}"`);
9225
- return transformed;
9567
+ async addNote(input) {
9568
+ (await this.#bounds()).assertKnowledgeNoteTextWithinBound(input.text);
9569
+ if (input.stampScopeIds.length === 0) throw new Error("A Knowledge note needs at least one stamp scope");
9570
+ return this.#tx(async (tx) => {
9571
+ const page = await this.#requireLivePage(tx, input.pageId, false);
9572
+ const stampIds = [...new Set(input.stampScopeIds)];
9573
+ await this.#assertScopePages(tx, stampIds);
9574
+ const mentionIds = [...new Set(input.mentions)];
9575
+ if (mentionIds.length) {
9576
+ const found = await this.#rows(tx, `SELECT "id" FROM ${this.#pages} WHERE "id" = ANY($1::text[])`, [mentionIds]);
9577
+ const missing = mentionIds.find((id) => !found.some((row) => row.id === id));
9578
+ if (missing) throw new KnowledgeNotFoundError("page", missing);
9579
+ }
9580
+ const id = input.id ?? createKnowledgeUlid();
9581
+ const now = /* @__PURE__ */ new Date();
9582
+ await tx.query(`INSERT INTO ${this.#notes} ("id","pageId","text","when","provenance","version","createdAt","updatedAt") VALUES ($1,$2,$3,$4,$5::jsonb,1,$6,$6)`, [
9583
+ id,
9584
+ page.id,
9585
+ input.text,
9586
+ input.when ? iso(input.when) : null,
9587
+ JSON.stringify(input.provenance),
9588
+ iso(now)
9589
+ ]);
9590
+ await tx.query(`INSERT INTO ${this.#stamps} ("noteId","scopeId") SELECT $1, unnest($2::text[])`, [id, stampIds]);
9591
+ if (mentionIds.length) await tx.query(`INSERT INTO ${this.#mentions} ("noteId","pageId") SELECT $1, unnest($2::text[])`, [id, mentionIds]);
9592
+ await this.#logActivity(tx, {
9593
+ action: "note-added",
9594
+ scopeId: page.scopeId,
9595
+ pageId: page.id,
9596
+ noteId: id,
9597
+ provenance: input.provenance,
9598
+ at: now
9599
+ });
9600
+ return this.#noteById(tx, id);
9601
+ });
9602
+ }
9603
+ async #assertScopePages(db, ids) {
9604
+ const rows = await this.#rows(db, `SELECT "id" FROM ${this.#pages} WHERE "id" = ANY($1::text[]) AND "isScope"`, [ids]);
9605
+ const missing = ids.find((id) => !rows.some((row) => row.id === id));
9606
+ if (missing) throw new Error(`Knowledge note stamp ${missing} is not a scope page`);
9607
+ }
9608
+ async #noteById(db, id, lock = false) {
9609
+ const rows = await this.#rows(db, `SELECT ${this.#noteColumns()} FROM ${this.#notes} n WHERE n."id" = $1${lock ? " FOR UPDATE" : ""}`, [id]);
9610
+ if (!rows[0]) throw new KnowledgeNotFoundError("note", id);
9611
+ return toNote(rows[0]);
9612
+ }
9613
+ async restampNote(input) {
9614
+ if (input.stampScopeIds.length === 0) throw new Error("A Knowledge note needs at least one stamp scope");
9615
+ return this.#tx(async (tx) => {
9616
+ const note = (await this.#rows(tx, `SELECT * FROM ${this.#notes} WHERE "id" = $1 FOR UPDATE`, [input.id]))[0];
9617
+ if (!note || note.deletedAt) throw new KnowledgeNotFoundError("note", input.id);
9618
+ if (Number(note.version) !== input.expectedVersion) throw new KnowledgeConflictError(input.id);
9619
+ const stampIds = [...new Set(input.stampScopeIds)];
9620
+ await this.#assertScopePages(tx, stampIds);
9621
+ const now = /* @__PURE__ */ new Date();
9622
+ await tx.query(`DELETE FROM ${this.#stamps} WHERE "noteId" = $1`, [input.id]);
9623
+ await tx.query(`INSERT INTO ${this.#stamps} ("noteId","scopeId") SELECT $1, unnest($2::text[])`, [input.id, stampIds]);
9624
+ await tx.query(`UPDATE ${this.#notes} SET "version" = "version" + 1, "updatedAt" = $2 WHERE "id" = $1`, [input.id, iso(now)]);
9625
+ const page = await this.#pageScope(tx, String(note.pageId));
9626
+ await this.#logActivity(tx, {
9627
+ action: "note-restamped",
9628
+ scopeId: page,
9629
+ pageId: String(note.pageId),
9630
+ noteId: input.id,
9631
+ provenance: input.provenance,
9632
+ at: now
9633
+ });
9634
+ return this.#noteById(tx, input.id);
9635
+ });
9636
+ }
9637
+ async #pageScope(db, pageId) {
9638
+ const rows = await this.#rows(db, `SELECT "scopeId" FROM ${this.#pages} WHERE "id" = $1`, [pageId]);
9639
+ return String(rows[0]?.scopeId);
9640
+ }
9641
+ async removeNote(input) {
9642
+ return this.#tx(async (tx) => {
9643
+ const note = await this.#noteById(tx, input.id, true);
9644
+ if (note.deletedAt) return note;
9645
+ const now = /* @__PURE__ */ new Date();
9646
+ await tx.query(`UPDATE ${this.#notes} SET "deletedAt" = $2, "deletedBy" = $3, "version" = "version" + 1, "updatedAt" = $2 WHERE "id" = $1`, [
9647
+ input.id,
9648
+ iso(now),
9649
+ input.deletedBy
9650
+ ]);
9651
+ await this.#logActivity(tx, {
9652
+ action: "note-removed",
9653
+ scopeId: await this.#pageScope(tx, note.pageId),
9654
+ pageId: note.pageId,
9655
+ noteId: input.id,
9656
+ provenance: input.provenance,
9657
+ at: now
9658
+ });
9659
+ return this.#noteById(tx, input.id);
9226
9660
  });
9227
9661
  }
9228
- let index = 0;
9229
- return transformSqlCode(normalized, (code) => code.replace(/\?/g, () => `$${++index}`));
9230
- }
9231
- function createExecutor(client, schemaName) {
9232
- const execute = async (statement, qualifyWithSchema) => {
9233
- const sql = typeof statement === "string" ? statement : statement.sql;
9234
- const args = typeof statement === "string" ? [] : statement.args ?? [];
9235
- const result = await client.query(postgresSql(sql, qualifyWithSchema ? schemaName : void 0), args);
9236
- return {
9237
- rows: result.rows,
9238
- rowsAffected: result.rowCount ?? 0
9239
- };
9240
- };
9241
- return {
9242
- execute: (statement) => execute(statement, true),
9243
- executeRaw: (statement) => execute(statement, false)
9244
- };
9245
- }
9246
- /**
9247
- * Scope keys visible to a caller holding `scope`: a row is visible when its scope is a subset of the
9248
- * caller's (companion entries such as `resource:x:uncurated` make this more than a prefix match).
9249
- * Matching rows by `scopeKey` keeps visibility filters on an index; a caller scope has only a few
9250
- * entries, so the list stays small.
9251
- */
9252
- function visibleScopeKeys(scope) {
9253
- const canonical = canonicalizeKnowledgeScope(scope);
9254
- const keys = /* @__PURE__ */ new Set();
9255
- for (let mask = 1; mask < 1 << canonical.length; mask++) try {
9256
- keys.add(knowledgeScopeKey(canonical.filter((_, index) => mask & 1 << index)));
9257
- } catch {}
9258
- return [...keys];
9259
- }
9260
- const visibleSql = (keys, scopeKeyColumn = "scopeKey") => `${scopeKeyColumn} IN (${keys.map(() => "?").join(",")})`;
9261
- function parseJson$1(value) {
9262
- if (typeof value === "string") return JSON.parse(value);
9263
- if (value instanceof Uint8Array) return JSON.parse(new TextDecoder().decode(value));
9264
- if (value instanceof ArrayBuffer) return JSON.parse(new TextDecoder().decode(value));
9265
- return value;
9266
- }
9267
- /**
9268
- * Knowledge timestamps are written as UTC digits into timezone-naive columns
9269
- * ({@link postgresTimestamp} and the ISO strings passed to inserts), but the
9270
- * driver parses naive columns in the process-local timezone. Reinterpret the
9271
- * parsed components as UTC so reads return the digits that were stored.
9272
- */
9273
- function toDate$1(value) {
9274
- if (value instanceof Date) return new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate(), value.getHours(), value.getMinutes(), value.getSeconds(), value.getMilliseconds()));
9275
- const text = String(value);
9276
- if (/(Z|[+-]\d{2}(:?\d{2})?)$/.test(text)) return new Date(text);
9277
- return /* @__PURE__ */ new Date(`${text.replace(" ", "T")}Z`);
9278
- }
9279
- function optionalDate(value) {
9280
- return value == null ? void 0 : toDate$1(value);
9281
- }
9282
- function postgresTimestamp(value) {
9283
- const pad = (part, width = 2) => String(part).padStart(width, "0");
9284
- return `${value.getUTCFullYear()}-${pad(value.getUTCMonth() + 1)}-${pad(value.getUTCDate())} ${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:${pad(value.getUTCSeconds())}.${pad(value.getUTCMilliseconds(), 3)}`;
9285
- }
9286
- function canonicalName(name) {
9287
- return name.trim().toLocaleLowerCase();
9288
- }
9289
- function nodeReferenceId(node) {
9290
- return typeof node === "string" ? node : node.id;
9291
- }
9292
- function escapeLikePattern(value) {
9293
- return value.replaceAll("=", "==").replaceAll("%", "=%").replaceAll("_", "=_");
9294
- }
9295
- function parseNode(row) {
9296
- return {
9297
- id: String(row.id),
9298
- type: "node",
9299
- name: String(row.name),
9300
- kind: row.kind == null ? "" : String(row.kind),
9301
- content: row.content == null ? void 0 : String(row.content),
9302
- description: row.description == null ? void 0 : String(row.description),
9303
- isScope: row.isScope === true || row.isScope === 1 ? true : void 0,
9304
- scope: parseJson$1(row.scopeJson ?? row.scope),
9305
- version: Number(row.version),
9306
- mergedInto: row.mergedInto == null ? void 0 : String(row.mergedInto),
9307
- createdAt: toDate$1(row.createdAt),
9308
- updatedAt: toDate$1(row.updatedAt)
9309
- };
9310
- }
9311
- function parseKnowledge(row) {
9312
- return {
9313
- id: String(row.id),
9314
- node: String(row.node),
9315
- text: String(row.text),
9316
- scope: parseJson$1(row.scopeJson ?? row.scope),
9317
- sourceThreadId: String(row.sourceThreadId),
9318
- capturedAt: toDate$1(row.capturedAt),
9319
- when: optionalDate(row.when),
9320
- metadata: row.metadata == null ? void 0 : parseJson$1(row.metadata),
9321
- deletedAt: optionalDate(row.deletedAt),
9322
- deletedBy: row.deletedBy == null ? void 0 : String(row.deletedBy)
9323
- };
9324
- }
9325
- function parseOutbox(row) {
9326
- return {
9327
- id: String(row.id),
9328
- idempotencyKey: String(row.idempotencyKey),
9329
- documentId: String(row.documentId),
9330
- documentType: String(row.documentType),
9331
- operation: String(row.operation),
9332
- scope: parseJson$1(row.scopeJson ?? row.scope),
9333
- status: String(row.status),
9334
- attempts: Number(row.attempts),
9335
- availableAt: toDate$1(row.availableAt),
9336
- claimedAt: optionalDate(row.claimedAt),
9337
- claimedBy: row.claimedBy == null ? void 0 : String(row.claimedBy),
9338
- createdAt: toDate$1(row.createdAt),
9339
- completedAt: optionalDate(row.completedAt)
9340
- };
9341
- }
9342
- function knowledgeIndexes(schemaName) {
9343
- const table = (name) => {
9344
- const quotedName = `"${parseSqlIdentifier(name, "table name")}"`;
9345
- return schemaName ? `"${parseSchemaName(schemaName)}".${quotedName}` : quotedName;
9346
- };
9347
- return [
9348
- {
9349
- name: "idx_knowledge_nodes_identity",
9350
- sql: `CREATE UNIQUE INDEX IF NOT EXISTS idx_knowledge_nodes_identity ON ${table(TABLE_KNOWLEDGE_NODES)} ("type", "scopeKey", "canonicalName");`
9351
- },
9352
- {
9353
- name: "idx_knowledge_nodes_scope",
9354
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_nodes_scope ON ${table(TABLE_KNOWLEDGE_NODES)} ("scopeKey", "type");`
9355
- },
9356
- {
9357
- name: "idx_knowledge_nodes_name",
9358
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_nodes_name ON ${table(TABLE_KNOWLEDGE_NODES)} ("type", "canonicalName");`
9359
- },
9360
- {
9361
- name: "idx_knowledge_records_node_latest",
9362
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_records_node_latest ON ${table(TABLE_KNOWLEDGE_RECORDS)} ("node", "id" DESC);`
9363
- },
9364
- {
9365
- name: "idx_knowledge_records_thread_latest",
9366
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_records_thread_latest ON ${table(TABLE_KNOWLEDGE_RECORDS)} ("sourceThreadId", "id" DESC);`
9367
- },
9368
- {
9369
- name: "idx_knowledge_mentions_record",
9370
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_mentions_record ON ${table(TABLE_KNOWLEDGE_MENTIONS)} ("recordId", "sourceType", "sourceId");`
9371
- },
9372
- {
9373
- name: "idx_knowledge_activity_latest",
9374
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_activity_latest ON ${table(TABLE_KNOWLEDGE_ACTIVITY)} ("id" DESC);`
9375
- },
9376
- {
9377
- name: "idx_knowledge_records_scope",
9378
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_records_scope ON ${table(TABLE_KNOWLEDGE_RECORDS)} ("scopeKey", "id");`
9379
- },
9380
- {
9381
- name: "idx_knowledge_activity_scope",
9382
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_activity_scope ON ${table(TABLE_KNOWLEDGE_ACTIVITY)} ("scopeKey", "id" DESC);`
9383
- },
9384
- {
9385
- name: "idx_knowledge_outbox_idempotency",
9386
- sql: `CREATE UNIQUE INDEX IF NOT EXISTS idx_knowledge_outbox_idempotency ON ${table(TABLE_KNOWLEDGE_SEMANTIC_OUTBOX)} ("idempotencyKey");`
9387
- },
9388
- {
9389
- name: "idx_knowledge_outbox_claim",
9390
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_outbox_claim ON ${table(TABLE_KNOWLEDGE_SEMANTIC_OUTBOX)} ("status", "availableAt", "createdAt");`
9391
- },
9392
- {
9393
- name: "idx_knowledge_node_scopes_scope",
9394
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_node_scopes_scope ON ${table(TABLE_KNOWLEDGE_NODE_SCOPES)} ("scopeNodeId", "nodeId");`
9395
- },
9396
- {
9397
- name: "idx_knowledge_record_scopes_scope",
9398
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_record_scopes_scope ON ${table(TABLE_KNOWLEDGE_RECORD_SCOPES)} ("scopeNodeId", "recordId");`
9399
- },
9400
- {
9401
- name: "idx_knowledge_scope_grants_ref",
9402
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_scope_grants_ref ON ${table(TABLE_KNOWLEDGE_SCOPE_GRANTS)} ("scopeRefId", "scopeNodeId");`
9403
- },
9404
- {
9405
- name: "idx_knowledge_node_addresses_node",
9406
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_node_addresses_node ON ${table(TABLE_KNOWLEDGE_NODE_ADDRESSES)} ("nodeId");`
9407
- },
9662
+ async restoreNote(input) {
9663
+ return this.#tx(async (tx) => {
9664
+ const note = await this.#noteById(tx, input.id, true);
9665
+ if (!note.deletedAt) return note;
9666
+ const now = /* @__PURE__ */ new Date();
9667
+ await tx.query(`UPDATE ${this.#notes} SET "deletedAt" = NULL, "deletedBy" = NULL, "version" = "version" + 1, "updatedAt" = $2 WHERE "id" = $1`, [input.id, iso(now)]);
9668
+ await this.#logActivity(tx, {
9669
+ action: "note-restored",
9670
+ scopeId: await this.#pageScope(tx, note.pageId),
9671
+ pageId: note.pageId,
9672
+ noteId: input.id,
9673
+ provenance: input.provenance,
9674
+ at: now
9675
+ });
9676
+ return this.#noteById(tx, input.id);
9677
+ });
9678
+ }
9679
+ async searchPages(input) {
9680
+ const core = await loadPagesCore();
9681
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
9682
+ const words = knowledgeSearchWords(input.query);
9683
+ if (!words.length) return [];
9684
+ const phrase = input.query.trim().toLowerCase().replace(/\s+/g, " ");
9685
+ const hits = [];
9408
9686
  {
9409
- name: "idx_knowledge_import_runs_lookup",
9410
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_import_runs_lookup ON ${table(TABLE_KNOWLEDGE_IMPORT_RUNS)} ("importerId", "binding", "queuedAt" DESC);`
9411
- },
9687
+ const params = new Params();
9688
+ const filter = new ReadFilter(input.read, params, this.#pages);
9689
+ const patterns = words.map((word) => params.add(`%${escapeLike(word)}%`));
9690
+ const phrasePattern = params.add(`%${escapeLike(phrase)}%`);
9691
+ const where = [
9692
+ `p."deletedAt" IS NULL`,
9693
+ `NOT p."isScope"`,
9694
+ filter.readable("s")
9695
+ ];
9696
+ if (input.scopeIds?.length) where.push(`p."scopeId" = ANY(${params.add(input.scopeIds)}::text[])`);
9697
+ for (const pattern of patterns) where.push(`(p."name" ILIKE ${pattern} OR p."description" ILIKE ${pattern} OR p."body" ILIKE ${pattern})`);
9698
+ const tier = `CASE WHEN p."canonicalName" LIKE ${phrasePattern} THEN 0 WHEN ${patterns.map((pattern) => `p."name" ILIKE ${pattern}`).join(" AND ")} THEN 1 ELSE 2 END`;
9699
+ const rows = await this.#rows(this.#client, `SELECT p.* FROM ${this.#pages} p JOIN ${this.#pages} s ON s."id" = p."scopeId" WHERE ${where.join(" AND ")} ORDER BY ${tier}, p."updatedAt" DESC, p."id" ASC LIMIT ${limit}`, params.values);
9700
+ for (const row of rows) hits.push({
9701
+ type: "page",
9702
+ page: toPage(row)
9703
+ });
9704
+ }
9705
+ if (hits.length >= limit) return hits;
9412
9706
  {
9413
- name: "idx_knowledge_activity_import_run",
9414
- sql: `CREATE INDEX IF NOT EXISTS idx_knowledge_activity_import_run ON ${table(TABLE_KNOWLEDGE_ACTIVITY)} ("importRunId", "id" DESC);`
9707
+ const params = new Params();
9708
+ const filter = new ReadFilter(input.read, params, this.#pages);
9709
+ const extra = [`n."deletedAt" IS NULL`, `np."deletedAt" IS NULL`];
9710
+ if (input.scopeIds?.length) extra.push(`np."scopeId" = ANY(${params.add(input.scopeIds)}::text[])`);
9711
+ for (const word of words) extra.push(`n."text" ILIKE ${params.add(`%${escapeLike(word)}%`)}`);
9712
+ const rows = await this.#rows(this.#client, `SELECT ${this.#noteColumns()}, row_to_json(np) AS "pageJson" FROM ${this.#visibleNotes(filter)} AND ${extra.join(" AND ")} ORDER BY n."updatedAt" DESC, n."id" DESC LIMIT ${limit - hits.length}`, params.values);
9713
+ for (const row of rows) hits.push({
9714
+ type: "note",
9715
+ note: toNote(row),
9716
+ page: toPage(parseJson$1(row.pageJson))
9717
+ });
9718
+ }
9719
+ return hits;
9720
+ }
9721
+ async listPageActivity(input) {
9722
+ const core = await loadPagesCore();
9723
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
9724
+ const params = new Params();
9725
+ const filter = new ReadFilter(input.read, params, this.#pages);
9726
+ const where = [filter.readable("s"), `(a."noteId" IS NULL OR ${this.#noteVisible(filter, "a.\"noteId\"")})`];
9727
+ if (input.scopeId) where.push(`s."id" = ${params.add(input.scopeId)}`);
9728
+ if (input.pageId) where.push(`a."pageId" = ${params.add(input.pageId)}`);
9729
+ if (input.cursor) {
9730
+ const [createdAt, id] = decodeCursor(input.cursor, 2);
9731
+ where.push(`(a."createdAt", a."id") < (${params.add(createdAt)}::timestamptz, ${params.add(id)})`);
9415
9732
  }
9416
- ];
9733
+ const rows = await this.#rows(this.#client, `SELECT a.* FROM ${this.#activity} a JOIN ${this.#pages} p ON p."id" = a."pageId" JOIN ${this.#pages} s ON s."id" = p."scopeId"
9734
+ WHERE ${where.join(" AND ")} ORDER BY a."createdAt" DESC, a."id" DESC LIMIT ${limit + 1}`, params.values);
9735
+ const events = rows.slice(0, limit).map((row) => ({
9736
+ id: String(row.id),
9737
+ action: String(row.action),
9738
+ scopeId: String(row.scopeId),
9739
+ pageId: String(row.pageId),
9740
+ ...row.noteId == null ? {} : { noteId: String(row.noteId) },
9741
+ provenance: parseJson$1(row.provenance),
9742
+ createdAt: new Date(row.createdAt)
9743
+ }));
9744
+ const last = events[events.length - 1];
9745
+ return {
9746
+ events,
9747
+ ...rows.length > limit && last ? { nextCursor: encodeCursor([iso(last.createdAt), last.id]) } : {}
9748
+ };
9749
+ }
9750
+ async addPinAudience(input) {
9751
+ return this.#tx(async (tx) => {
9752
+ const page = await this.#requireLivePage(tx, input.pageId, false);
9753
+ const now = /* @__PURE__ */ new Date();
9754
+ const { pin, changed } = await this.#upsertPinAudience(tx, page.id, input.audience, input.createdBy, now);
9755
+ if (changed) await this.#logActivity(tx, {
9756
+ action: "pin-added",
9757
+ scopeId: page.scopeId,
9758
+ pageId: page.id,
9759
+ provenance: { author: input.createdBy },
9760
+ at: now
9761
+ });
9762
+ return pin;
9763
+ });
9764
+ }
9765
+ async #upsertPinAudience(db, pageId, audience, createdBy, now) {
9766
+ const existing = (await this.#rows(db, `SELECT * FROM ${this.#pins} WHERE "pageId" = $1 FOR UPDATE`, [pageId]))[0];
9767
+ if (!existing) return {
9768
+ pin: toPin((await this.#rows(db, `INSERT INTO ${this.#pins} ("id","pageId","audience","createdBy","createdAt","updatedAt") VALUES ($1,$2,$3::text[],$4,$5,$5) RETURNING *`, [
9769
+ createKnowledgeUlid(),
9770
+ pageId,
9771
+ [...new Set(audience)],
9772
+ createdBy,
9773
+ iso(now)
9774
+ ]))[0]),
9775
+ changed: true
9776
+ };
9777
+ const current = existing.audience ?? [];
9778
+ const merged = [.../* @__PURE__ */ new Set([...current, ...audience])];
9779
+ if (merged.length === current.length) return {
9780
+ pin: toPin(existing),
9781
+ changed: false
9782
+ };
9783
+ return {
9784
+ pin: toPin((await this.#rows(db, `UPDATE ${this.#pins} SET "audience" = $2::text[], "updatedAt" = $3 WHERE "id" = $1 RETURNING *`, [
9785
+ String(existing.id),
9786
+ merged,
9787
+ iso(now)
9788
+ ]))[0]),
9789
+ changed: true
9790
+ };
9791
+ }
9792
+ async removePinAudience(input) {
9793
+ return this.#tx(async (tx) => {
9794
+ const existing = (await this.#rows(tx, `SELECT * FROM ${this.#pins} WHERE "pageId" = $1 FOR UPDATE`, [input.pageId]))[0];
9795
+ if (!existing) return null;
9796
+ const current = existing.audience ?? [];
9797
+ const remaining = current.filter((entry) => !input.audience.includes(entry));
9798
+ if (remaining.length === current.length) return toPin(existing);
9799
+ const now = /* @__PURE__ */ new Date();
9800
+ let pin = null;
9801
+ if (remaining.length === 0) await tx.query(`DELETE FROM ${this.#pins} WHERE "id" = $1`, [String(existing.id)]);
9802
+ else pin = toPin((await this.#rows(tx, `UPDATE ${this.#pins} SET "audience" = $2::text[], "updatedAt" = $3 WHERE "id" = $1 RETURNING *`, [
9803
+ String(existing.id),
9804
+ remaining,
9805
+ iso(now)
9806
+ ]))[0]);
9807
+ await this.#logActivity(tx, {
9808
+ action: "pin-removed",
9809
+ scopeId: await this.#pageScope(tx, input.pageId),
9810
+ pageId: input.pageId,
9811
+ provenance: { author: input.removedBy },
9812
+ at: now
9813
+ });
9814
+ return pin;
9815
+ });
9816
+ }
9817
+ /** Deletes every row but keeps the tables and the schema-version marker. */
9818
+ async clearAll() {
9819
+ const t = PG_KNOWLEDGE_PAGES_TABLES;
9820
+ const tables = [
9821
+ t.activity,
9822
+ t.pins,
9823
+ t.mentions,
9824
+ t.stamps,
9825
+ t.notes,
9826
+ t.pages
9827
+ ].map((name) => this.#q(name)).join(", ");
9828
+ await this.#client.query(`TRUNCATE ${tables}`);
9829
+ }
9830
+ async getPages(input) {
9831
+ if (!input.ids.length) return [];
9832
+ const params = new Params();
9833
+ const ids = params.add([...new Set(input.ids)]);
9834
+ const filter = new ReadFilter(input.read, params, this.#pages);
9835
+ return (await this.#rows(this.#client, `SELECT p.* FROM ${this.#pages} p JOIN ${this.#pages} s ON s."id" = p."scopeId"
9836
+ WHERE p."id" = ANY(${ids}::text[]) AND p."deletedAt" IS NULL AND ${filter.readable("s")}`, params.values)).map(toPage);
9837
+ }
9838
+ async listPins(input) {
9839
+ const core = await loadPagesCore();
9840
+ const limit = clampLimit(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
9841
+ const params = new Params();
9842
+ const where = [`p."deletedAt" IS NULL`, new ReadFilter(input.read, params, this.#pages).readable("s")];
9843
+ if (input.audience !== "all") where.push(`pn."audience" && ${params.add(input.audience)}::text[]`);
9844
+ if (input.pageIds) where.push(`pn."pageId" = ANY(${params.add(input.pageIds)}::text[])`);
9845
+ if (input.excludePageIds?.length) where.push(`pn."pageId" <> ALL(${params.add(input.excludePageIds)}::text[])`);
9846
+ if (input.withBody) where.push(`p."body" ~ '\\S'`);
9847
+ const from = `FROM ${this.#pins} pn JOIN ${this.#pages} p ON p."id" = pn."pageId" JOIN ${this.#pages} s ON s."id" = p."scopeId"`;
9848
+ const totalWhere = where.join(" AND ");
9849
+ if (input.cursor) {
9850
+ const [createdAt, id] = decodeCursor(input.cursor, 2);
9851
+ where.push(`(pn."createdAt", pn."id") < (${params.add(createdAt)}::timestamptz, ${params.add(id)})`);
9852
+ }
9853
+ const rows = await this.#rows(this.#client, `SELECT pn.*, p."name" AS "pageName" ${from}
9854
+ WHERE ${where.join(" AND ")} ORDER BY pn."createdAt" DESC, pn."id" DESC LIMIT ${limit + 1}`, params.values);
9855
+ let total;
9856
+ if (input.count) {
9857
+ const counted = await this.#rows(this.#client, `SELECT count(*)::int AS "total" ${from} WHERE ${totalWhere}`, params.values.slice(0, params.values.length - (input.cursor ? 2 : 0)));
9858
+ total = Number(counted[0]?.total ?? 0);
9859
+ }
9860
+ const pins = rows.slice(0, limit).map(toListedPin);
9861
+ const last = pins[pins.length - 1];
9862
+ return {
9863
+ pins,
9864
+ ...rows.length > limit && last ? { nextCursor: encodeCursor([iso(last.createdAt), last.id]) } : {},
9865
+ ...total === void 0 ? {} : { total }
9866
+ };
9867
+ }
9868
+ };
9869
+ // src/storage/domains/knowledge/pages-schema.ts
9870
+ const qualify = (schemaName, table) => schemaName ? `"${schemaName}"."${table}"` : `"${table}"`;
9871
+ /** Thrown when existing Knowledge tables can't be used as schema 4 without a reset. */
9872
+ var PgKnowledgeResetRequiredError = class extends Error {
9873
+ inspection;
9874
+ constructor(inspection) {
9875
+ super(knowledgePagesResetMessage(inspection.reason));
9876
+ this.name = "KnowledgeSchemaResetRequiredError";
9877
+ this.inspection = inspection;
9878
+ }
9879
+ };
9880
+ /** Looks at every `mastra_knowledge_*` table and the version row without changing anything. */
9881
+ async function inspectPgKnowledgePagesSchema(db, schemaName) {
9882
+ return inspectKnowledgePagesSchema(await pgKnowledgeSnapshot(db, schemaName));
9883
+ }
9884
+ /** Creates the schema-4 tables, refusing (with the reset message) over anything older. */
9885
+ async function initPgKnowledgePagesSchema(client, schemaName) {
9886
+ await client.tx(async (tx) => {
9887
+ await tx.query("SELECT pg_advisory_xact_lock(hashtext($1))", [`mastra-knowledge-schema:${schemaName ?? ""}`]);
9888
+ const drop = legacyKnowledgeTablesToDrop(await pgKnowledgeSnapshot(tx, schemaName));
9889
+ if (drop.length > 0) await tx.query(`DROP TABLE IF EXISTS ${drop.map((table) => qualify(schemaName, table)).join(", ")} CASCADE`);
9890
+ const inspection = await inspectPgKnowledgePagesSchema(tx, schemaName);
9891
+ if (inspection.status === "incompatible-reset-required") throw new PgKnowledgeResetRequiredError(inspection);
9892
+ for (const statement of pgKnowledgePagesDDL(schemaName)) await tx.query(statement);
9893
+ await tx.query(`INSERT INTO ${qualify(schemaName, PG_KNOWLEDGE_PAGES_TABLES.state)} ("id","schemaVersion") VALUES ('knowledge', $1) ON CONFLICT ("id") DO NOTHING`, [4]);
9894
+ });
9417
9895
  }
9418
- function knowledgeIndexDDL(schemaName) {
9419
- return knowledgeIndexes(schemaName).map((index) => index.sql);
9896
+ /**
9897
+ * Every `mastra_knowledge_*` table and the schema-4 version, if any. The state table is read as
9898
+ * whole rows because schema 2 used the same name with a different shape, and a failed query would
9899
+ * abort the init transaction.
9900
+ */
9901
+ async function pgKnowledgeSnapshot(db, schemaName) {
9902
+ const tableNames = (await db.query(`SELECT table_name FROM information_schema.tables WHERE table_schema = COALESCE($1, current_schema()) AND table_name LIKE 'mastra\\_knowledge\\_%'`, [schemaName ?? null])).rows.map((row) => String(row.table_name));
9903
+ if (!tableNames.includes(PG_KNOWLEDGE_PAGES_TABLES.state)) return { tableNames };
9904
+ const row = (await db.query(`SELECT to_jsonb(s) AS row FROM ${qualify(schemaName, PG_KNOWLEDGE_PAGES_TABLES.state)} s`)).rows.map((r) => r.row).find((r) => r.id === "knowledge");
9905
+ return {
9906
+ tableNames,
9907
+ schemaVersion: typeof row?.schemaVersion === "number" ? row.schemaVersion : void 0
9908
+ };
9420
9909
  }
9421
- const KNOWLEDGE_CURATION_CURSOR_REMOVED_MESSAGE = "Knowledge curation cursors were removed: observation-time curate is the only Knowledge writer and needs no cursor.";
9422
- const knowledgeTableDefinitions = [
9423
- {
9424
- tableName: TABLE_KNOWLEDGE_NODES,
9425
- schema: KNOWLEDGE_V2_NODES_SCHEMA
9426
- },
9427
- {
9428
- tableName: TABLE_KNOWLEDGE_RECORDS,
9429
- schema: KNOWLEDGE_V2_RECORDS_SCHEMA
9430
- },
9431
- {
9432
- tableName: TABLE_KNOWLEDGE_MENTIONS,
9433
- schema: KNOWLEDGE_V2_MENTIONS_SCHEMA,
9434
- compositePrimaryKey: ["recordId", "sourceId"]
9435
- },
9436
- {
9437
- tableName: TABLE_KNOWLEDGE_NODE_SCOPES,
9438
- schema: KNOWLEDGE_NODE_SCOPES_SCHEMA,
9439
- compositePrimaryKey: ["nodeId", "scopeNodeId"]
9440
- },
9441
- {
9442
- tableName: TABLE_KNOWLEDGE_RECORD_SCOPES,
9443
- schema: KNOWLEDGE_RECORD_SCOPES_SCHEMA,
9444
- compositePrimaryKey: ["recordId", "scopeNodeId"]
9445
- },
9446
- {
9447
- tableName: TABLE_KNOWLEDGE_SCOPE_GRANTS,
9448
- schema: KNOWLEDGE_SCOPE_GRANTS_SCHEMA,
9449
- compositePrimaryKey: ["scopeNodeId", "scopeRefId"]
9450
- },
9451
- {
9452
- tableName: TABLE_KNOWLEDGE_ACCESS_STATE,
9453
- schema: KNOWLEDGE_ACCESS_STATE_SCHEMA
9454
- },
9455
- {
9456
- tableName: TABLE_KNOWLEDGE_SCOPE_ADDRESSES,
9457
- schema: KNOWLEDGE_SCOPE_ADDRESSES_SCHEMA
9458
- },
9459
- {
9460
- tableName: TABLE_KNOWLEDGE_NODE_ADDRESSES,
9461
- schema: KNOWLEDGE_NODE_ADDRESSES_SCHEMA,
9462
- compositePrimaryKey: ["source", "address"]
9463
- },
9464
- {
9465
- tableName: TABLE_KNOWLEDGE_IMPORT_STATE,
9466
- schema: KNOWLEDGE_IMPORT_STATE_SCHEMA,
9467
- compositePrimaryKey: [
9468
- "importerId",
9469
- "binding",
9470
- "key"
9471
- ]
9472
- },
9473
- {
9474
- tableName: TABLE_KNOWLEDGE_IMPORT_RUNS,
9475
- schema: KNOWLEDGE_IMPORT_RUNS_SCHEMA
9476
- },
9477
- {
9478
- tableName: TABLE_KNOWLEDGE_PROPOSALS,
9479
- schema: KNOWLEDGE_PROPOSALS_SCHEMA
9480
- },
9481
- {
9482
- tableName: TABLE_KNOWLEDGE_ACTIVITY,
9483
- schema: KNOWLEDGE_V2_ACTIVITY_SCHEMA
9484
- },
9485
- {
9486
- tableName: TABLE_KNOWLEDGE_SEMANTIC_OUTBOX,
9487
- schema: KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA
9488
- }
9489
- ];
9910
+ /** Drops exactly the Knowledge tables (never Memory's) and recreates schema 4. */
9911
+ async function resetPgKnowledgePagesSchema(client, schemaName) {
9912
+ const tables = KNOWLEDGE_RESETTABLE_TABLE_NAMES.map((table) => qualify(schemaName, table)).join(", ");
9913
+ await client.query(`DROP TABLE IF EXISTS ${tables} CASCADE`);
9914
+ await initPgKnowledgePagesSchema(client, schemaName);
9915
+ }
9916
+ // src/storage/domains/knowledge/index.ts
9917
+ const loadKnowledgePagesCore = createKnowledgePagesCoreLoader(coreFeatures, () => import("@mastra/core/storage"));
9490
9918
  function pgSetting(config, key) {
9491
9919
  const value = config[key] || process.env[`PG${key.toUpperCase()}`] || defaults[key];
9492
9920
  return value === void 0 || value === null || value === "" ? void 0 : String(value);
@@ -9526,1153 +9954,137 @@ function getPgKnowledgeIsolationKey(config) {
9526
9954
  if (target) return `pg:${target}:schema:${schema}`;
9527
9955
  return `pg:unidentified:schema:${schema}`;
9528
9956
  }
9957
+ /** @experimental Knowledge APIs are experimental and may change without notice. */
9529
9958
  var KnowledgePG = class extends KnowledgeStorage {
9530
- static MANAGED_TABLES = KNOWLEDGE_TABLE_NAMES;
9531
9959
  static getExportDDL(schemaName) {
9532
- return [...knowledgeTableDefinitions.map((definition) => generateTableSQL({
9533
- ...definition,
9534
- schemaName,
9535
- includeAllConstraints: true
9536
- })), ...knowledgeIndexDDL(schemaName)];
9960
+ return pgKnowledgePagesDDL(schemaName).map((statement) => `${statement};`);
9537
9961
  }
9538
9962
  #client;
9539
- #executor;
9540
- /** Reader-backed executor for standalone reads; mutations and read-modify-write stay on #executor. */
9541
- #readExecutor;
9542
- #db;
9543
9963
  #schemaName;
9964
+ #pages;
9544
9965
  constructor(config) {
9545
9966
  super({ storageIsolationKey: config.storageIsolationKey ?? getPgKnowledgeIsolationKey(config) });
9546
- const { client, readClient, schemaName, skipDefaultIndexes } = resolvePgConfig(config);
9967
+ const { client, schemaName } = resolvePgConfig(config);
9547
9968
  this.#client = client;
9548
9969
  this.#schemaName = schemaName;
9549
- this.#executor = createExecutor(client, schemaName);
9550
- this.#readExecutor = createExecutor(readClient, schemaName);
9551
- this.#db = new PgDB({
9970
+ this.#pages = new PgKnowledgePages({
9552
9971
  client,
9553
- readClient,
9554
9972
  schemaName,
9555
- skipDefaultIndexes
9973
+ bounds: async () => {
9974
+ const core = await loadKnowledgePagesCore();
9975
+ return {
9976
+ assertKnowledgePageDescriptionWithinBound: core.assertKnowledgePageDescriptionWithinBound,
9977
+ assertKnowledgeNoteTextWithinBound: core.assertKnowledgeNoteTextWithinBound
9978
+ };
9979
+ }
9556
9980
  });
9557
9981
  }
9558
9982
  getCapabilities() {
9559
9983
  return {
9560
- contractVersion: 2,
9561
- schemaVersion: 2,
9562
- supportsV2: true,
9984
+ ...super.getCapabilities(),
9985
+ schemaVersion: 4,
9563
9986
  supportsSchemaInspection: true,
9564
9987
  supportsExplicitReset: true
9565
9988
  };
9566
9989
  }
9567
- async inspectSchema() {
9568
- const { inspectKnowledgeSchema } = await loadKnowledgeV2Core();
9569
- try {
9570
- const snapshot = getSchemaSnapshot(this.#client, this.#schemaName);
9571
- if (snapshot) {
9572
- const tableNames = KNOWLEDGE_TABLE_NAMES.filter((table) => snapshot.tables.has(table));
9573
- return this.#classifySchema(this.#executor, tableNames, snapshot.columns);
9574
- }
9575
- return this.#inspectSchemaWithExecutor(this.#executor);
9576
- } catch (error) {
9577
- return inspectKnowledgeSchema({
9578
- available: false,
9579
- tableNames: [],
9580
- reason: error instanceof Error ? error.message : String(error)
9581
- });
9582
- }
9583
- }
9584
- async #inspectSchemaWithExecutor(executor) {
9585
- const tableNames = (await executor.execute({
9586
- sql: `SELECT table_name FROM information_schema.tables WHERE table_schema = COALESCE(?, current_schema()) AND table_name = ANY(?::text[])`,
9587
- args: [this.#schemaName ?? null, [...KNOWLEDGE_TABLE_NAMES]]
9588
- })).rows.map((row) => String(row.table_name));
9589
- const columnResult = await executor.execute({
9590
- sql: `SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = COALESCE(?, current_schema()) AND table_name = ANY(?::text[])`,
9591
- args: [this.#schemaName ?? null, [...KNOWLEDGE_TABLE_NAMES]]
9592
- });
9593
- const columns = /* @__PURE__ */ new Map();
9594
- for (const row of columnResult.rows) {
9595
- const table = String(row.table_name);
9596
- const names = columns.get(table) ?? /* @__PURE__ */ new Set();
9597
- names.add(String(row.column_name));
9598
- columns.set(table, names);
9599
- }
9600
- return this.#classifySchema(executor, tableNames, columns);
9601
- }
9602
- async #classifySchema(executor, tableNames, columns) {
9603
- const { inspectKnowledgeSchema } = await loadKnowledgeV2Core();
9604
- if (tableNames.length === 0) return inspectKnowledgeSchema({
9605
- available: true,
9606
- tableNames
9607
- });
9608
- const missingTables = KNOWLEDGE_TABLE_NAMES.filter((table) => !tableNames.includes(table));
9609
- if (missingTables.length > 0) return inspectKnowledgeSchema({
9610
- available: true,
9611
- tableNames,
9612
- reason: `Missing Knowledge v2 tables: ${missingTables.join(", ")}`
9613
- });
9614
- for (const { tableName: table, schema } of knowledgeTableDefinitions) {
9615
- const actual = columns.get(table) ?? /* @__PURE__ */ new Set();
9616
- const missing = Object.keys(schema).filter((column) => !actual.has(column));
9617
- if (missing.length > 0) return inspectKnowledgeSchema({
9618
- available: true,
9619
- tableNames,
9620
- reason: `Knowledge table ${table} is missing v2 columns: ${missing.join(", ")}`
9621
- });
9622
- }
9623
- const accessState = await executor.execute(`SELECT schemaVersion FROM "${TABLE_KNOWLEDGE_ACCESS_STATE}" WHERE id='global'`);
9624
- if (Number(accessState.rows[0]?.schemaVersion) !== 2) return inspectKnowledgeSchema({
9625
- available: true,
9626
- tableNames,
9627
- reason: "Knowledge schema version marker is missing or incompatible"
9628
- });
9629
- return inspectKnowledgeSchema({
9630
- available: true,
9631
- tableNames,
9632
- schemaVersion: 2
9633
- });
9634
- }
9635
9990
  async init() {
9636
- await this.#transaction(async (tx) => {
9637
- await tx.execute({
9638
- sql: "SELECT pg_advisory_xact_lock(hashtext(?))",
9639
- args: [`mastra-knowledge-v2:${this.#schemaName ?? "current_schema"}`]
9640
- });
9641
- const { assertKnowledgeSchemaCompatible } = await loadKnowledgeV2Core();
9642
- let inspection = await this.#inspectSchemaWithExecutor(tx);
9643
- if (inspection.status === "incompatible-reset-required" && await this.#isPublishedV1Layout(tx)) {
9644
- const tables = [...RETIRED_KNOWLEDGE_TABLE_NAMES, ...[...KNOWLEDGE_TABLE_NAMES].reverse()].map((table) => `"${table}"`).join(", ");
9645
- await tx.execute(`DROP TABLE IF EXISTS ${tables}`);
9646
- inspection = await this.#inspectSchemaWithExecutor(tx);
9647
- }
9648
- assertKnowledgeSchemaCompatible(inspection);
9649
- for (const definition of knowledgeTableDefinitions) await tx.executeRaw(generateTableSQL({
9650
- ...definition,
9651
- schemaName: this.#schemaName,
9652
- includeAllConstraints: true
9653
- }));
9654
- for (const index of knowledgeIndexes(this.#schemaName)) await tx.executeRaw(index.sql);
9655
- await tx.execute({
9656
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_ACCESS_STATE}" (id, epoch, schemaVersion) VALUES ('global', 0, ?) ON CONFLICT (id) DO NOTHING`,
9657
- args: [2]
9658
- });
9659
- });
9660
- }
9661
- /**
9662
- * True when the only Knowledge objects are the tables and indexes published v1 adapters created,
9663
- * with or without rows. Anything else (v2 tables, unknown tables, views, triggers, extra indexes)
9664
- * needs an explicit reset.
9665
- */
9666
- async #isPublishedV1Layout(executor) {
9667
- const schema = this.#schemaName ?? null;
9668
- const relations = await executor.execute({
9669
- sql: `SELECT table_name, table_type FROM information_schema.tables WHERE table_schema = COALESCE(?, current_schema()) AND table_name LIKE 'mastra\\_knowledge\\_%'`,
9670
- args: [schema]
9671
- });
9672
- const tables = [];
9673
- for (const row of relations.rows) {
9674
- const name = String(row.table_name);
9675
- if (row.table_type !== "BASE TABLE" || !PUBLISHED_KNOWLEDGE_V1_TABLE_NAMES.has(name)) return false;
9676
- tables.push(name);
9677
- }
9678
- const indexes = await executor.execute({
9679
- sql: `SELECT indexname FROM pg_indexes WHERE schemaname = COALESCE(?, current_schema()) AND tablename = ANY(?::text[])`,
9680
- args: [schema, tables]
9681
- });
9682
- for (const row of indexes.rows) {
9683
- const name = String(row.indexname);
9684
- if (!PUBLISHED_KNOWLEDGE_V1_INDEX_NAMES.has(name) && !name.endsWith("_pkey")) return false;
9685
- }
9686
- if ((await executor.execute({
9687
- sql: `SELECT 1 FROM information_schema.view_table_usage WHERE table_schema = COALESCE(?, current_schema()) AND table_name = ANY(?::text[]) UNION ALL SELECT 1 FROM information_schema.triggers WHERE event_object_schema = COALESCE(?, current_schema()) AND event_object_table = ANY(?::text[]) LIMIT 1`,
9688
- args: [
9689
- schema,
9690
- tables,
9691
- schema,
9692
- tables
9693
- ]
9694
- })).rows.length > 0) return false;
9695
- return true;
9991
+ await initPgKnowledgePagesSchema(this.#client, this.#schemaName);
9696
9992
  }
9697
- async dangerouslyClearAll() {
9698
- await this.#transaction(async (tx) => {
9699
- for (const table of [
9700
- TABLE_KNOWLEDGE_RECORD_SCOPES,
9701
- TABLE_KNOWLEDGE_NODE_SCOPES,
9702
- TABLE_KNOWLEDGE_SCOPE_GRANTS,
9703
- TABLE_KNOWLEDGE_SCOPE_ADDRESSES,
9704
- TABLE_KNOWLEDGE_NODE_ADDRESSES,
9705
- TABLE_KNOWLEDGE_MENTIONS,
9706
- TABLE_KNOWLEDGE_PROPOSALS,
9707
- TABLE_KNOWLEDGE_ACTIVITY,
9708
- TABLE_KNOWLEDGE_IMPORT_STATE,
9709
- TABLE_KNOWLEDGE_IMPORT_RUNS,
9710
- TABLE_KNOWLEDGE_SEMANTIC_OUTBOX,
9711
- TABLE_KNOWLEDGE_RECORDS,
9712
- TABLE_KNOWLEDGE_NODES
9713
- ]) await tx.execute(`DELETE FROM "${table}"`);
9714
- await tx.execute(`UPDATE "${TABLE_KNOWLEDGE_ACCESS_STATE}" SET epoch = 0 WHERE id = 'global'`);
9715
- });
9993
+ async inspectSchema() {
9994
+ return inspectPgKnowledgePagesSchema(this.#client, this.#schemaName);
9716
9995
  }
9717
9996
  async dangerouslyReset() {
9718
- const tables = [...RETIRED_KNOWLEDGE_TABLE_NAMES, ...[...KNOWLEDGE_TABLE_NAMES].reverse()].map((table) => `"${table}"`).join(", ");
9719
- await this.#executor.execute(`DROP TABLE IF EXISTS ${tables}`);
9720
- await this.init();
9721
- }
9722
- async reconcileStructure(plan) {
9723
- return this.#transaction(async (tx) => {
9724
- await tx.execute({
9725
- sql: `SELECT pg_advisory_xact_lock(hashtext(?))`,
9726
- args: [`mastra-knowledge-reconcile:${this.#schemaName}`]
9727
- });
9728
- const scopes = {};
9729
- const createdScopeIds = [];
9730
- const createdAddresses = /* @__PURE__ */ new Set();
9731
- const retrofit = plan.retrofit ?? true;
9732
- let structureChanged = false;
9733
- const deletedScopeAddresses = /* @__PURE__ */ new Set();
9734
- const resolveAddress = async (address) => {
9735
- if (scopes[address]) return scopes[address];
9736
- const row = (await tx.execute({
9737
- sql: `SELECT a."scopeNodeId",n."isScope",n."deletedAt" FROM "${TABLE_KNOWLEDGE_SCOPE_ADDRESSES}" a JOIN "${TABLE_KNOWLEDGE_NODES}" n ON n.id=a."scopeNodeId" WHERE a.address=?`,
9738
- args: [address]
9739
- })).rows[0];
9740
- if (!row) return void 0;
9741
- if (!row.isScope) throw new Error(`Knowledge address ${address} does not reference a scope`);
9742
- if (row.deletedAt) deletedScopeAddresses.add(address);
9743
- scopes[address] = String(row.scopeNodeId);
9744
- return scopes[address];
9745
- };
9746
- for (const scope of plan.scopes) {
9747
- if (await resolveAddress(scope.address)) continue;
9748
- const id = randomUUID();
9749
- const now = (/* @__PURE__ */ new Date()).toISOString();
9750
- await tx.execute({
9751
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_NODES}" (id,type,name,"canonicalName",kind,description,"isScope",metadata,version,"createdAt","updatedAt") VALUES (?,'node',?,?,?,?,TRUE,?,1,?,?)`,
9752
- args: [
9753
- id,
9754
- scope.name,
9755
- canonicalName(scope.name),
9756
- scope.kind ?? null,
9757
- scope.description ?? null,
9758
- scope.metadata ?? null,
9759
- now,
9760
- now
9761
- ]
9762
- });
9763
- await tx.execute({
9764
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_SCOPE_ADDRESSES}" (address,"scopeNodeId") VALUES (?,?)`,
9765
- args: [scope.address, id]
9766
- });
9767
- scopes[scope.address] = id;
9768
- createdAddresses.add(scope.address);
9769
- createdScopeIds.push(id);
9770
- structureChanged = true;
9771
- }
9772
- for (const scope of plan.scopes) {
9773
- if (!createdAddresses.has(scope.address) && (!retrofit || deletedScopeAddresses.has(scope.address))) continue;
9774
- const scopeNodeId = scopes[scope.address];
9775
- for (const parentAddress of scope.parentAddresses ?? []) {
9776
- const parentId = await resolveAddress(parentAddress);
9777
- if (!parentId || deletedScopeAddresses.has(parentAddress)) {
9778
- const deletedParentId = scopes[parentAddress];
9779
- if ((deletedParentId ? await tx.execute({
9780
- sql: `SELECT 1 FROM "mastra_knowledge_node_scopes" WHERE "nodeId"=? AND "scopeNodeId"=?`,
9781
- args: [scopeNodeId, deletedParentId]
9782
- }) : void 0)?.rows.length) continue;
9783
- throw new Error(`Knowledge parent scope does not exist: ${parentAddress}`);
9784
- }
9785
- if ((await tx.execute({
9786
- sql: `SELECT 1 FROM "mastra_knowledge_node_scopes" WHERE "nodeId"=? AND "scopeNodeId"=?`,
9787
- args: [scopeNodeId, parentId]
9788
- })).rows.length) continue;
9789
- if ((await tx.execute({
9790
- sql: `SELECT n.id FROM "mastra_knowledge_node_scopes" ns JOIN "${TABLE_KNOWLEDGE_NODES}" n ON n.id=ns."nodeId" WHERE ns."scopeNodeId"=? AND n."isScope" AND n."canonicalName"=? AND n."deletedAt" IS NULL AND n.id<>? LIMIT 1`,
9791
- args: [
9792
- parentId,
9793
- canonicalName(scope.name),
9794
- scopeNodeId
9795
- ]
9796
- })).rows.length) throw new Error(`Knowledge scope name ${scope.name} already exists under ${parentAddress}`);
9797
- const inserted = await tx.execute({
9798
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_NODE_SCOPES}" ("nodeId","scopeNodeId","addedAt") VALUES (?,?,?) ON CONFLICT DO NOTHING`,
9799
- args: [
9800
- scopeNodeId,
9801
- parentId,
9802
- (/* @__PURE__ */ new Date()).toISOString()
9803
- ]
9804
- });
9805
- structureChanged ||= inserted.rowsAffected > 0;
9806
- }
9807
- for (const grant of scope.grants ?? []) {
9808
- const scopeRefId = await resolveAddress(grant.scopeRefAddress);
9809
- if (!scopeRefId || deletedScopeAddresses.has(grant.scopeRefAddress)) {
9810
- const deletedScopeRefId = scopes[grant.scopeRefAddress];
9811
- if ((deletedScopeRefId ? await tx.execute({
9812
- sql: `SELECT 1 FROM "mastra_knowledge_scope_grants" WHERE "scopeNodeId"=? AND "scopeRefId"=?`,
9813
- args: [scopeNodeId, deletedScopeRefId]
9814
- }) : void 0)?.rows.length) continue;
9815
- throw new Error(`Knowledge grant scope does not exist: ${grant.scopeRefAddress}`);
9816
- }
9817
- const inserted = await tx.execute({
9818
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_SCOPE_GRANTS}" ("scopeNodeId","scopeRefId",role,"canSuggest") VALUES (?,?,?,?) ON CONFLICT DO NOTHING`,
9819
- args: [
9820
- scopeNodeId,
9821
- scopeRefId,
9822
- grant.role,
9823
- grant.canSuggest ?? null
9824
- ]
9825
- });
9826
- structureChanged ||= inserted.rowsAffected > 0;
9827
- }
9828
- }
9829
- if (structureChanged) await tx.execute(`UPDATE "${TABLE_KNOWLEDGE_ACCESS_STATE}" SET epoch=epoch+1 WHERE id='global'`);
9830
- const state = await tx.execute(`SELECT epoch FROM "${TABLE_KNOWLEDGE_ACCESS_STATE}" WHERE id='global'`);
9831
- return {
9832
- scopes,
9833
- createdScopeIds,
9834
- deletedScopeAddresses: [...deletedScopeAddresses],
9835
- changed: structureChanged,
9836
- accessEpoch: Number(state.rows[0]?.epoch ?? 0)
9837
- };
9838
- });
9839
- }
9840
- async listScopeNodes(input = {}) {
9841
- const { limit, after } = parseListKnowledgeScopeNodesInput(input);
9842
- if (input.addresses?.length === 0 || input.ids?.length === 0) return {
9843
- scopes: [],
9844
- nextCursor: null
9845
- };
9846
- const args = [];
9847
- const where = [`n."isScope"`, `n."deletedAt" IS NULL`];
9848
- let within = "";
9849
- if (input.withinAddress !== void 0) {
9850
- within = `WITH RECURSIVE within_scope(id) AS (SELECT r.id FROM "${TABLE_KNOWLEDGE_NODES}" r JOIN "${TABLE_KNOWLEDGE_SCOPE_ADDRESSES}" ra ON ra."scopeNodeId"=r.id WHERE ra.address=? AND r."isScope" AND r."deletedAt" IS NULL UNION SELECT ns."nodeId" FROM "${TABLE_KNOWLEDGE_NODE_SCOPES}" ns JOIN within_scope w ON ns."scopeNodeId"=w.id JOIN "${TABLE_KNOWLEDGE_NODES}" c ON c.id=ns."nodeId" WHERE c."isScope" AND c."deletedAt" IS NULL) `;
9851
- args.push(input.withinAddress);
9852
- where.push("n.id IN (SELECT id FROM within_scope)");
9853
- }
9854
- if (input.addresses) {
9855
- where.push(`a.address IN (${input.addresses.map(() => "?").join(",")})`);
9856
- args.push(...input.addresses);
9857
- }
9858
- if (input.ids) {
9859
- where.push(`n.id IN (${input.ids.map(() => "?").join(",")})`);
9860
- args.push(...input.ids);
9861
- }
9862
- if (after) {
9863
- where.push("(n.name COLLATE \"C\" > ? OR (n.name = ? AND n.id > ?))");
9864
- args.push(after.name, after.name, after.id);
9865
- }
9866
- args.push(limit + 1);
9867
- const rows = (await this.#readExecutor.execute({
9868
- sql: `${within}SELECT n.id,n.name,n.kind,n.description,a.address FROM "${TABLE_KNOWLEDGE_NODES}" n LEFT JOIN "${TABLE_KNOWLEDGE_SCOPE_ADDRESSES}" a ON a."scopeNodeId"=n.id WHERE ${where.join(" AND ")} ORDER BY n.name COLLATE "C", n.id LIMIT ?`,
9869
- args
9870
- })).rows;
9871
- if (rows.length === 0) return {
9872
- scopes: [],
9873
- nextCursor: null
9874
- };
9875
- const parents = await this.#readExecutor.execute({
9876
- sql: `SELECT ns."nodeId",ns."scopeNodeId" FROM "${TABLE_KNOWLEDGE_NODE_SCOPES}" ns WHERE ns."nodeId" IN (${rows.map(() => "?").join(",")}) ORDER BY ns."scopeNodeId" COLLATE "C"`,
9877
- args: rows.map((row) => String(row.id))
9878
- });
9879
- const parentsByScopeId = /* @__PURE__ */ new Map();
9880
- for (const row of parents.rows) {
9881
- const scopeId = String(row.nodeId);
9882
- const parentId = String(row.scopeNodeId);
9883
- const existing = parentsByScopeId.get(scopeId);
9884
- if (existing) existing.push(parentId);
9885
- else parentsByScopeId.set(scopeId, [parentId]);
9886
- }
9887
- return pageKnowledgeScopeNodes(rows.map((row) => ({
9888
- id: String(row.id),
9889
- address: String(row.address),
9890
- name: String(row.name),
9891
- ...row.kind == null ? {} : { kind: String(row.kind) },
9892
- ...row.description == null ? {} : { description: String(row.description) },
9893
- parentIds: parentsByScopeId.get(String(row.id)) ?? []
9894
- })), limit, input);
9895
- }
9896
- async listScopeMembers(input) {
9897
- const { limit, after } = parseListKnowledgeScopeMembersInput(input);
9898
- const args = [input.scopeNodeId];
9899
- let keyset = "";
9900
- if (after) {
9901
- const updatedAt = postgresTimestamp(after.updatedAt);
9902
- keyset = ` AND (n."updatedAt" < ? OR (n."updatedAt" = ? AND (n.name > ? OR (n.name = ? AND n.id > ?))))`;
9903
- args.push(updatedAt, updatedAt, after.name, after.name, after.id);
9904
- }
9905
- args.push(limit + 1);
9906
- return pageKnowledgeScopeMembers((await this.#readExecutor.execute({
9907
- sql: `SELECT *, scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_NODES}" n WHERE EXISTS (SELECT 1 FROM "${TABLE_KNOWLEDGE_NODE_SCOPES}" ns WHERE ns."nodeId"=n.id AND ns."scopeNodeId"=?) AND n."deletedAt" IS NULL AND n."mergedInto" IS NULL${keyset} ORDER BY n."updatedAt" DESC, n.name ASC, n.id ASC LIMIT ?`,
9908
- args
9909
- })).rows.map(parseNode), limit, input);
9910
- }
9911
- async createNode(input) {
9912
- await assertKnowledgeDescriptionWithinBoundCompat(input.description);
9913
- const scope = canonicalizeKnowledgeScope(input.scope);
9914
- return this.#transaction(async (tx) => {
9915
- const existing = await this.#getNodeByName(tx, input.name, scope);
9916
- if (existing) {
9917
- const terminal = await this.#resolveTerminalNode(tx, existing.id);
9918
- if (!isKnowledgeScopeVisible(terminal.scope, scope)) throw new Error(`Merged knowledge node is not visible from scope: ${input.name}`);
9919
- await this.#placeNodeInScopes(tx, terminal.id, input.scopeAddresses, /* @__PURE__ */ new Date());
9920
- return terminal;
9921
- }
9922
- const now = /* @__PURE__ */ new Date();
9923
- const node = {
9924
- id: input.id ?? crypto.randomUUID(),
9925
- type: "node",
9926
- name: input.name.trim(),
9927
- kind: input.kind,
9928
- content: input.content,
9929
- description: input.description,
9930
- scope,
9931
- version: 1,
9932
- createdAt: now,
9933
- updatedAt: now
9934
- };
9935
- await tx.execute({
9936
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_NODES}" (id,type,name,canonicalName,kind,content,description,isScope,scope,scopeKey,version,mergedInto,createdAt,updatedAt) VALUES (?,?,?,?,?,?,?,FALSE,jsonb(?),?,?,NULL,?,?)`,
9937
- args: [
9938
- node.id,
9939
- "node",
9940
- node.name,
9941
- canonicalName(node.name),
9942
- node.kind,
9943
- node.content ?? null,
9944
- node.description ?? null,
9945
- JSON.stringify(scope),
9946
- knowledgeScopeKey(scope),
9947
- node.version,
9948
- now.toISOString(),
9949
- now.toISOString()
9950
- ]
9951
- });
9952
- await this.#replaceNodeScopes(tx, node.id, scope, now);
9953
- await this.#placeNodeInScopes(tx, node.id, input.scopeAddresses, now);
9954
- await this.#replaceMentions(tx, "node", node.id, node.content ?? "", input.resolutionScope ?? scope, scope);
9955
- await this.#activity(tx, "node-created", "node", node.id, scope);
9956
- await this.#outbox(tx, "node", node.id, "upsert", node.version, scope);
9957
- return node;
9958
- });
9959
- }
9960
- async getNode(id) {
9961
- return this.#getNode(this.#readExecutor, id);
9962
- }
9963
- async getNodeByName(input) {
9964
- return this.#getNodeByName(this.#readExecutor, input.name, canonicalizeKnowledgeScope(input.scope));
9965
- }
9966
- async resolveNode(input) {
9967
- return this.#resolveNode(this.#readExecutor, input.name, canonicalizeKnowledgeScope(input.scope));
9968
- }
9969
- async listNodes(input) {
9970
- const keys = visibleScopeKeys(canonicalizeKnowledgeScope(input.scope));
9971
- const clauses = [
9972
- `type = 'node'`,
9973
- "mergedInto IS NULL",
9974
- visibleSql(keys)
9975
- ];
9976
- const args = [...keys];
9977
- if (input.namePrefix) {
9978
- clauses.push("canonicalName LIKE ? ESCAPE '='");
9979
- args.push(`${escapeLikePattern(canonicalName(input.namePrefix))}%`);
9980
- }
9981
- if (input.kind) {
9982
- clauses.push("kind = ?");
9983
- args.push(input.kind);
9984
- }
9985
- if (input.hasContent !== void 0) clauses.push(input.hasContent ? "content IS NOT NULL AND content <> ''" : "(content IS NULL OR content = '')");
9986
- if (input.cursor) {
9987
- const cursor = parseKnowledgeNodeCursor(input.cursor, {
9988
- namePrefix: input.namePrefix,
9989
- kind: input.kind,
9990
- hasContent: input.hasContent
9991
- });
9992
- const updatedAt = postgresTimestamp(cursor.updatedAt);
9993
- clauses.push("(updatedAt < ? OR (updatedAt = ? AND (name > ? OR (name = ? AND id > ?))))");
9994
- args.push(updatedAt, updatedAt, cursor.name, cursor.name, cursor.id);
9995
- }
9996
- args.push(input.limit ?? 100);
9997
- return (await this.#readExecutor.execute({
9998
- sql: `SELECT *, scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_NODES}" WHERE ${clauses.join(" AND ")} ORDER BY updatedAt DESC, name ASC, id ASC LIMIT ?`,
9999
- args
10000
- })).rows.map(parseNode);
10001
- }
10002
- async updateNode(input) {
10003
- await assertKnowledgeDescriptionWithinBoundCompat(input.description);
10004
- return this.#transaction(async (tx) => {
10005
- const existing = await this.#getNode(tx, input.id);
10006
- if (!existing) throw new KnowledgeNotFoundError("node", input.id);
10007
- if (existing.mergedInto) throw new Error(`Cannot update merged knowledge node: ${input.id}`);
10008
- const scope = canonicalizeKnowledgeScope(input.scope ?? existing.scope);
10009
- const name = (input.name ?? existing.name).trim();
10010
- const content = input.content ?? existing.content;
10011
- const description = input.description ?? existing.description;
10012
- const now = /* @__PURE__ */ new Date();
10013
- if ((await tx.execute({
10014
- sql: `UPDATE "${TABLE_KNOWLEDGE_NODES}" SET name=?,canonicalName=?,kind=?,content=?,description=?,scope=jsonb(?),scopeKey=?,version=version+1,updatedAt=? WHERE id=? AND type='node' AND version=?`,
10015
- args: [
10016
- name,
10017
- canonicalName(name),
10018
- input.kind ?? existing.kind,
10019
- content ?? null,
10020
- description ?? null,
10021
- JSON.stringify(scope),
10022
- knowledgeScopeKey(scope),
10023
- now.toISOString(),
10024
- input.id,
10025
- input.version
10026
- ]
10027
- })).rowsAffected === 0) throw new KnowledgeConflictError(input.id);
10028
- if (knowledgeScopeKey(existing.scope) !== knowledgeScopeKey(scope)) await this.#swapIdentityScopes(tx, input.id, existing.scope, scope, now);
10029
- if (input.content !== void 0 || input.name !== void 0 || input.scope !== void 0) await this.#replaceMentions(tx, "node", input.id, content ?? "", input.resolutionScope ?? scope, scope);
10030
- await this.#activity(tx, "node-updated", "node", input.id, scope);
10031
- if (knowledgeScopeKey(existing.scope) !== knowledgeScopeKey(scope)) {
10032
- await this.#outbox(tx, "node", input.id, "delete", createKnowledgeUlid(), existing.scope);
10033
- const records = await tx.execute({
10034
- sql: `SELECT id,scope AS "scopeJson",deletedAt FROM "${TABLE_KNOWLEDGE_RECORDS}" WHERE node=?`,
10035
- args: [input.id]
10036
- });
10037
- for (const row of records.rows) {
10038
- const factScope = parseJson$1(row.scopeJson);
10039
- await this.#outbox(tx, "record", String(row.id), "delete", createKnowledgeUlid(), factScope);
10040
- if (row.deletedAt == null) await this.#outbox(tx, "record", String(row.id), "upsert", createKnowledgeUlid(), factScope);
10041
- }
10042
- }
10043
- await this.#outbox(tx, "node", input.id, "upsert", input.version + 1, scope);
10044
- return {
10045
- ...existing,
10046
- name,
10047
- kind: input.kind ?? existing.kind,
10048
- content,
10049
- description,
10050
- scope,
10051
- version: input.version + 1,
10052
- updatedAt: now
10053
- };
10054
- });
9997
+ await resetPgKnowledgePagesSchema(this.#client, this.#schemaName);
10055
9998
  }
10056
- async mergeNodes(input) {
10057
- if (input.sourceId === input.targetId) throw new Error("Cannot merge a knowledge node into itself");
10058
- return this.#transaction(async (tx) => {
10059
- const source = await this.#getNode(tx, input.sourceId);
10060
- if (!source) throw new KnowledgeNotFoundError("node", input.sourceId);
10061
- const target = await this.#resolveTerminalNode(tx, input.targetId);
10062
- if (!target) throw new KnowledgeNotFoundError("node", input.targetId);
10063
- if (target.id === source.id) throw new Error("Cannot create a knowledge merge cycle");
10064
- if (!isKnowledgeScopeVisible(target.scope, source.scope)) throw new Error("Cannot merge a knowledge node into a target that is narrower than its source scope");
10065
- const affected = await tx.execute({
10066
- sql: `SELECT DISTINCT m.sourceType,m.sourceId,COALESCE(f.scope,r.scope) AS "scopeJson",CASE WHEN f.deletedAt IS NULL THEN 0 ELSE 1 END AS deleted FROM "${TABLE_KNOWLEDGE_MENTIONS}" m LEFT JOIN "${TABLE_KNOWLEDGE_RECORDS}" f ON m.sourceType='record' AND f.id=m.sourceId LEFT JOIN "${TABLE_KNOWLEDGE_NODES}" r ON m.sourceType='node' AND r.id=m.sourceId WHERE m.recordId=?`,
10067
- args: [source.id]
10068
- });
10069
- const movedFacts = await tx.execute({
10070
- sql: `SELECT id,scope AS "scopeJson",deletedAt FROM "${TABLE_KNOWLEDGE_RECORDS}" WHERE node=?`,
10071
- args: [source.id]
10072
- });
10073
- if ((await tx.execute({
10074
- sql: `UPDATE "${TABLE_KNOWLEDGE_NODES}" SET mergedInto=?,version=version+1,updatedAt=? WHERE id=? AND type='node' AND version=? AND mergedInto IS NULL`,
10075
- args: [
10076
- target.id,
10077
- (/* @__PURE__ */ new Date()).toISOString(),
10078
- source.id,
10079
- input.sourceVersion
10080
- ]
10081
- })).rowsAffected === 0) throw new KnowledgeConflictError(source.id);
10082
- await tx.execute({
10083
- sql: `UPDATE "${TABLE_KNOWLEDGE_RECORDS}" SET node=?,version=version+1,updatedAt=? WHERE node=?`,
10084
- args: [
10085
- target.id,
10086
- (/* @__PURE__ */ new Date()).toISOString(),
10087
- source.id
10088
- ]
10089
- });
10090
- await tx.execute({
10091
- sql: `DELETE FROM "${TABLE_KNOWLEDGE_MENTIONS}" WHERE recordId=? AND EXISTS (SELECT 1 FROM "${TABLE_KNOWLEDGE_MENTIONS}" target WHERE target.sourceType="${TABLE_KNOWLEDGE_MENTIONS}".sourceType AND target.sourceId="${TABLE_KNOWLEDGE_MENTIONS}".sourceId AND target.recordId=?)`,
10092
- args: [source.id, target.id]
10093
- });
10094
- await tx.execute({
10095
- sql: `UPDATE "${TABLE_KNOWLEDGE_MENTIONS}" SET recordId=? WHERE recordId=?`,
10096
- args: [target.id, source.id]
10097
- });
10098
- for (const row of movedFacts.rows) await this.#outbox(tx, "record", String(row.id), row.deletedAt == null ? "upsert" : "delete", createKnowledgeUlid(), parseJson$1(row.scopeJson));
10099
- for (const row of affected.rows) await this.#outbox(tx, String(row.sourceType), String(row.sourceId), Number(row.deleted) ? "delete" : "upsert", createKnowledgeUlid(), parseJson$1(row.scopeJson));
10100
- let mergedTarget = target;
10101
- if (target.description === void 0 && source.description) {
10102
- const adoptedAt = /* @__PURE__ */ new Date();
10103
- if ((await tx.execute({
10104
- sql: `UPDATE "${TABLE_KNOWLEDGE_NODES}" SET description=?,version=version+1,updatedAt=? WHERE id=? AND type='node' AND version=? AND description IS NULL`,
10105
- args: [
10106
- source.description,
10107
- adoptedAt.toISOString(),
10108
- target.id,
10109
- target.version
10110
- ]
10111
- })).rowsAffected > 0) {
10112
- mergedTarget = {
10113
- ...target,
10114
- description: source.description,
10115
- version: target.version + 1,
10116
- updatedAt: adoptedAt
10117
- };
10118
- await this.#activity(tx, "node-updated", "node", target.id, target.scope);
10119
- }
10120
- }
10121
- await this.#activity(tx, "node-merged", "node", source.id, source.scope);
10122
- await this.#outbox(tx, "node", source.id, "delete", input.sourceVersion + 1, source.scope);
10123
- await this.#outbox(tx, "node", target.id, "upsert", createKnowledgeUlid(), mergedTarget.scope);
10124
- return mergedTarget;
10125
- });
10126
- }
10127
- async appendKnowledge(input) {
10128
- await assertKnowledgeRecordTextWithinBoundCompat(input.text);
10129
- const scope = canonicalizeKnowledgeScope(input.scope);
10130
- const resolutionScope = canonicalizeKnowledgeScope(input.resolutionScope);
10131
- const defaultScope = canonicalizeKnowledgeScope(input.defaultScope);
10132
- return this.#transaction(async (tx) => {
10133
- const parent = await this.#resolveTerminalNode(tx, nodeReferenceId(input.node));
10134
- if (!parent) throw new KnowledgeNotFoundError("node", nodeReferenceId(input.node));
10135
- const metadataJson = input.metadata ? toPgJson(input.metadata) : null;
10136
- const record = {
10137
- id: input.id ?? createKnowledgeUlid(),
10138
- node: parent.id,
10139
- text: input.text,
10140
- scope,
10141
- sourceThreadId: input.sourceThreadId,
10142
- capturedAt: /* @__PURE__ */ new Date(),
10143
- when: input.when ? new Date(input.when) : void 0,
10144
- metadata: input.metadata
10145
- };
10146
- await tx.execute({
10147
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_RECORDS}" (id,node,text,scope,scopeKey,sourceThreadId,capturedAt,"when",metadata,version,updatedAt,deletedAt,deletedBy) VALUES (?,?,?,jsonb(?),?,?,?,?,jsonb(?),?,?,NULL,NULL)`,
10148
- args: [
10149
- record.id,
10150
- record.node,
10151
- record.text,
10152
- JSON.stringify(scope),
10153
- knowledgeScopeKey(scope),
10154
- record.sourceThreadId,
10155
- record.capturedAt.toISOString(),
10156
- record.when?.toISOString() ?? null,
10157
- metadataJson,
10158
- 1,
10159
- record.capturedAt.toISOString()
10160
- ]
10161
- });
10162
- await this.#replaceRecordScopes(tx, record.id, scope, record.capturedAt);
10163
- await this.#replaceMentions(tx, "record", record.id, record.text, resolutionScope, defaultScope);
10164
- await this.#activity(tx, "record-created", "record", record.id, scope, record.sourceThreadId);
10165
- await this.#outbox(tx, "record", record.id, "upsert", record.id, scope);
10166
- return metadataJson ? {
10167
- ...record,
10168
- metadata: JSON.parse(metadataJson)
10169
- } : record;
10170
- });
9999
+ async dangerouslyClearAll() {
10000
+ await this.#pages.clearAll();
10171
10001
  }
10172
- async getKnowledge(input) {
10173
- const result = await this.#readExecutor.execute({
10174
- sql: `SELECT *,scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_RECORDS}" WHERE id=?${input.includeDeleted ? "" : " AND deletedAt IS NULL"}`,
10175
- args: [input.id]
10176
- });
10177
- return result.rows[0] ? parseKnowledge(result.rows[0]) : null;
10002
+ materializeScope(input) {
10003
+ return this.#pages.materializeScope(input);
10178
10004
  }
10179
- async listKnowledgeAbout(input) {
10180
- return this.#queryKnowledge(input, "about");
10005
+ getScopesByAddress(input) {
10006
+ return this.#pages.getScopesByAddress(input);
10181
10007
  }
10182
- async listKnowledgeMentioning(input) {
10183
- return this.#queryKnowledge(input, "mentioning");
10008
+ listScopeDeclarations() {
10009
+ return this.#pages.listScopeDeclarations();
10184
10010
  }
10185
- async listKnowledgeRelatedTo(input) {
10186
- return this.#queryKnowledge(input, "related");
10011
+ renameScopeDeclaration(input) {
10012
+ return this.#pages.renameScopeDeclaration(input);
10187
10013
  }
10188
- async knowledgeBySource(input) {
10189
- const keys = visibleScopeKeys(canonicalizeKnowledgeScope(input.scope));
10190
- const args = [input.sourceThreadId, ...keys];
10191
- if (input.after) args.push(input.after);
10192
- const limit = input.limit ?? 100;
10193
- args.push(limit + 1);
10194
- const records = (await this.#readExecutor.execute({
10195
- sql: `SELECT *,scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_RECORDS}" WHERE sourceThreadId=? AND ${visibleSql(keys)}${input.includeDeleted ? "" : " AND deletedAt IS NULL"}${input.after ? " AND id > ?" : ""} ORDER BY id ASC LIMIT ?`,
10196
- args
10197
- })).rows.map(parseKnowledge);
10198
- return {
10199
- records: records.slice(0, limit),
10200
- nextCursor: records.length > limit ? records[limit - 1]?.id : void 0
10201
- };
10014
+ listChildScopes(input) {
10015
+ return this.#pages.listChildScopes(input);
10202
10016
  }
10203
- async removeKnowledge(input) {
10204
- return this.#transaction(async (tx) => {
10205
- const record = await this.#getKnowledge(tx, input.id, true);
10206
- if (!record) throw new KnowledgeNotFoundError("record", input.id);
10207
- if (record.deletedAt) return record;
10208
- const deletedAt = /* @__PURE__ */ new Date();
10209
- await tx.execute({
10210
- sql: `UPDATE "${TABLE_KNOWLEDGE_RECORDS}" SET deletedAt=?,deletedBy=?,version=version+1,updatedAt=? WHERE id=? AND deletedAt IS NULL`,
10211
- args: [
10212
- deletedAt.toISOString(),
10213
- input.deletedBy,
10214
- deletedAt.toISOString(),
10215
- input.id
10216
- ]
10217
- });
10218
- await this.#activity(tx, "record-deleted", "record", input.id, record.scope, record.sourceThreadId);
10219
- await this.#outbox(tx, "record", input.id, "delete", deletedAt.toISOString(), record.scope);
10220
- return {
10221
- ...record,
10222
- deletedAt,
10223
- deletedBy: input.deletedBy
10224
- };
10225
- });
10017
+ getPages(input) {
10018
+ return this.#pages.getPages(input);
10226
10019
  }
10227
- async restoreKnowledge(input) {
10228
- return this.#transaction(async (tx) => {
10229
- const record = await this.#getKnowledge(tx, input.id, true);
10230
- if (!record) throw new KnowledgeNotFoundError("record", input.id);
10231
- if (!record.deletedAt) return record;
10232
- await tx.execute({
10233
- sql: `UPDATE "${TABLE_KNOWLEDGE_RECORDS}" SET deletedAt=NULL,deletedBy=NULL,version=version+1,updatedAt=? WHERE id=?`,
10234
- args: [(/* @__PURE__ */ new Date()).toISOString(), input.id]
10235
- });
10236
- await this.#activity(tx, "record-restored", "record", input.id, record.scope, record.sourceThreadId);
10237
- await this.#outbox(tx, "record", input.id, "upsert", createKnowledgeUlid(), record.scope);
10238
- return {
10239
- ...record,
10240
- deletedAt: void 0,
10241
- deletedBy: void 0
10242
- };
10243
- });
10020
+ getPage(input) {
10021
+ return this.#pages.getPage(input);
10244
10022
  }
10245
- async rescopeKnowledge(input) {
10246
- const scope = canonicalizeKnowledgeScope(input.scope);
10247
- return this.#transaction(async (tx) => {
10248
- const record = await this.#getKnowledge(tx, input.id, true);
10249
- if (!record) throw new KnowledgeNotFoundError("record", input.id);
10250
- const updatedAt = /* @__PURE__ */ new Date();
10251
- await tx.execute({
10252
- sql: `UPDATE "${TABLE_KNOWLEDGE_RECORDS}" SET scope=jsonb(?),scopeKey=?,version=version+1,updatedAt=? WHERE id=?`,
10253
- args: [
10254
- JSON.stringify(scope),
10255
- knowledgeScopeKey(scope),
10256
- updatedAt.toISOString(),
10257
- input.id
10258
- ]
10259
- });
10260
- await this.#replaceRecordScopes(tx, input.id, scope, updatedAt);
10261
- await this.#activity(tx, "record-rescoped", "record", input.id, scope, record.sourceThreadId);
10262
- if (knowledgeScopeKey(record.scope) !== knowledgeScopeKey(scope)) await this.#outbox(tx, "record", input.id, "delete", createKnowledgeUlid(), record.scope);
10263
- if (!record.deletedAt) await this.#outbox(tx, "record", input.id, "upsert", createKnowledgeUlid(), scope);
10264
- return {
10265
- ...record,
10266
- scope
10267
- };
10268
- });
10023
+ getPageByPath(input) {
10024
+ return this.#pages.getPageByPath(input);
10269
10025
  }
10270
- async search(input) {
10271
- const scope = canonicalizeKnowledgeScope(input.scope);
10272
- const keys = visibleScopeKeys(scope);
10273
- const normalizedQuery = input.query.trim().toLocaleLowerCase();
10274
- if (!normalizedQuery) return [];
10275
- const query = `%${escapeLikePattern(normalizedQuery)}%`;
10276
- const results = (await this.#readExecutor.execute({
10277
- sql: `SELECT *,scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_NODES}" WHERE mergedInto IS NULL AND ${visibleSql(keys)} AND (canonicalName LIKE ? ESCAPE '=' OR lower(COALESCE(kind,'')) LIKE ? ESCAPE '=' OR lower(COALESCE(content,'')) LIKE ? ESCAPE '=' OR lower(COALESCE(description,'')) LIKE ? ESCAPE '=') ORDER BY updatedAt DESC LIMIT ?`,
10278
- args: [
10279
- ...keys,
10280
- query,
10281
- query,
10282
- query,
10283
- query,
10284
- input.limit ?? 20
10285
- ]
10286
- })).rows.map((row) => ({
10287
- type: String(row.type),
10288
- id: String(row.id),
10289
- recordId: String(row.id),
10290
- name: String(row.name),
10291
- text: [
10292
- String(row.name),
10293
- ...row.description ? [String(row.description)] : [],
10294
- ...row.content ? [String(row.content)] : []
10295
- ].join("\n"),
10296
- scope: parseJson$1(row.scopeJson)
10297
- }));
10298
- if (results.length < (input.limit ?? 20)) {
10299
- const records = await this.#readExecutor.execute({
10300
- sql: `SELECT f.*,f.scope AS "scopeJson",r.name,r.scope AS "parentScopeJson" FROM "${TABLE_KNOWLEDGE_RECORDS}" f JOIN "${TABLE_KNOWLEDGE_NODES}" r ON r.id=f.node AND r.type='node' AND r.mergedInto IS NULL WHERE f.deletedAt IS NULL AND ${visibleSql(keys, "f.scopeKey")} AND lower(f.text) LIKE ? ESCAPE '=' ORDER BY f.id DESC LIMIT ?`,
10301
- args: [
10302
- ...keys,
10303
- query,
10304
- (input.limit ?? 20) - results.length
10305
- ]
10306
- });
10307
- results.push(...records.rows.map((row) => {
10308
- const parentVisible = isKnowledgeScopeVisible(parseJson$1(row.parentScopeJson), scope);
10309
- return {
10310
- type: "record",
10311
- id: String(row.id),
10312
- recordId: parentVisible ? String(row.node) : String(row.id),
10313
- name: parentVisible ? String(row.name) : "(private node)",
10314
- text: String(row.text),
10315
- scope: parseJson$1(row.scopeJson)
10316
- };
10317
- }));
10318
- }
10319
- return results;
10026
+ findPagesByName(input) {
10027
+ return this.#pages.findPagesByName(input);
10320
10028
  }
10321
- /**
10322
- * @deprecated Curation cursors were removed. Observation-time curate is the only Knowledge writer and needs no
10323
- * cursor. Always throws.
10324
- */
10325
- async getCurationCursor(_input) {
10326
- throw new Error(KNOWLEDGE_CURATION_CURSOR_REMOVED_MESSAGE);
10029
+ listChildPages(input) {
10030
+ return this.#pages.listChildPages(input);
10327
10031
  }
10328
- /**
10329
- * @deprecated Curation cursors were removed. Observation-time curate is the only Knowledge writer and needs no
10330
- * cursor. Always throws.
10331
- */
10332
- async advanceCurationCursor(_input) {
10333
- throw new Error(KNOWLEDGE_CURATION_CURSOR_REMOVED_MESSAGE);
10334
- }
10335
- async listActivity(input) {
10336
- const keys = visibleScopeKeys(canonicalizeKnowledgeScope(input.scope));
10337
- return (await this.#readExecutor.execute({
10338
- sql: `SELECT *,scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_ACTIVITY}" WHERE ${visibleSql(keys)}${input.after ? " AND id < ?" : ""} ORDER BY id DESC LIMIT ?`,
10339
- args: [
10340
- ...keys,
10341
- ...input.after ? [input.after] : [],
10342
- input.limit ?? 100
10343
- ]
10344
- })).rows.map((row) => ({
10345
- id: String(row.id),
10346
- action: String(row.action),
10347
- recordType: String(row.recordType),
10348
- recordId: String(row.recordId),
10349
- scope: parseJson$1(row.scopeJson),
10350
- sourceThreadId: row.sourceThreadId == null ? void 0 : String(row.sourceThreadId),
10351
- createdAt: toDate$1(row.createdAt)
10352
- }));
10032
+ listPages(input) {
10033
+ return this.#pages.listPages(input);
10353
10034
  }
10354
- async listSemanticOutbox(input = {}) {
10355
- const clauses = [];
10356
- const args = [];
10357
- if (input.status) {
10358
- clauses.push("status=?");
10359
- args.push(input.status);
10360
- }
10361
- if (input.scope) {
10362
- const keys = visibleScopeKeys(input.scope);
10363
- clauses.push(visibleSql(keys));
10364
- args.push(...keys);
10365
- }
10366
- args.push(input.limit ?? 100);
10367
- return (await this.#executor.execute({
10368
- sql: `SELECT *,scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}"${clauses.length ? ` WHERE ${clauses.join(" AND ")}` : ""} ORDER BY createdAt ASC,id ASC LIMIT ?`,
10369
- args
10370
- })).rows.map(parseOutbox);
10371
- }
10372
- async claimSemanticOutbox(input) {
10373
- const now = input.now ?? /* @__PURE__ */ new Date();
10374
- const stale = new Date(now.getTime() - (input.claimTimeoutMs ?? 6e4));
10375
- return this.#transaction(async (tx) => {
10376
- const clauses = [
10377
- `availableAt <= ?`,
10378
- `(status='pending' OR (status='processing' AND claimedAt <= ?))`,
10379
- `NOT EXISTS (SELECT 1 FROM "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" AS earlier WHERE earlier.documentId = "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}".documentId AND earlier.status != 'completed' AND (earlier.createdAt < "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}".createdAt OR (earlier.createdAt = "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}".createdAt AND earlier.id < "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}".id)))`
10380
- ];
10381
- const args = [now.toISOString(), stale.toISOString()];
10382
- if (input.scope) {
10383
- const keys = visibleScopeKeys(input.scope);
10384
- clauses.push(visibleSql(keys));
10385
- args.push(...keys);
10386
- }
10387
- args.push(input.limit ?? 100);
10388
- const ids = (await tx.execute({
10389
- sql: `SELECT id FROM "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" WHERE ${clauses.join(" AND ")} ORDER BY createdAt ASC,id ASC LIMIT ? FOR UPDATE SKIP LOCKED`,
10390
- args
10391
- })).rows.map((row) => String(row.id));
10392
- for (const id of ids) await tx.execute({
10393
- sql: `UPDATE "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" SET status='processing',attempts=attempts+1,claimedAt=?,claimedBy=? WHERE id=?`,
10394
- args: [
10395
- now.toISOString(),
10396
- input.workerId,
10397
- id
10398
- ]
10399
- });
10400
- if (!ids.length) return [];
10401
- return (await tx.execute({
10402
- sql: `SELECT *,scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" WHERE id IN (${ids.map(() => "?").join(",")}) ORDER BY createdAt ASC,id ASC`,
10403
- args: ids
10404
- })).rows.map(parseOutbox);
10405
- });
10035
+ createPage(input) {
10036
+ return this.#pages.createPage(input);
10406
10037
  }
10407
- async completeSemanticOutbox(input) {
10408
- if (!input.ids.length) return;
10409
- const now = (/* @__PURE__ */ new Date()).toISOString();
10410
- await this.#transaction(async (tx) => {
10411
- for (const id of input.ids) await tx.execute({
10412
- sql: `UPDATE "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" SET status='completed',completedAt=? WHERE id=? AND status='processing' AND claimedBy=?`,
10413
- args: [
10414
- now,
10415
- id,
10416
- input.workerId
10417
- ]
10418
- });
10419
- });
10038
+ updatePage(input) {
10039
+ return this.#pages.updatePage(input);
10420
10040
  }
10421
- async releaseSemanticOutbox(input) {
10422
- if (!input.ids.length) return;
10423
- await this.#transaction(async (tx) => {
10424
- for (const id of input.ids) await tx.execute({
10425
- sql: `UPDATE "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" SET status='pending',availableAt=?,claimedAt=NULL,claimedBy=NULL WHERE id=? AND status='processing' AND claimedBy=?`,
10426
- args: [
10427
- (input.retryAt ?? /* @__PURE__ */ new Date()).toISOString(),
10428
- id,
10429
- input.workerId
10430
- ]
10431
- });
10432
- });
10041
+ movePage(input) {
10042
+ return this.#pages.movePage(input);
10433
10043
  }
10434
- async #transaction(operation) {
10435
- return this.#client.tx((tx) => operation(createExecutor(tx, this.#schemaName)));
10044
+ mergePages(input) {
10045
+ return this.#pages.mergePages(input);
10436
10046
  }
10437
- async #getNode(executor, id) {
10438
- const result = await executor.execute({
10439
- sql: `SELECT *,scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_NODES}" WHERE id=? AND type='node'`,
10440
- args: [id]
10441
- });
10442
- return result.rows[0] ? parseNode(result.rows[0]) : null;
10047
+ deletePage(input) {
10048
+ return this.#pages.deletePage(input);
10443
10049
  }
10444
- async #getNodeByName(executor, name, scope) {
10445
- const result = await executor.execute({
10446
- sql: `SELECT *,scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_NODES}" WHERE type='node' AND scopeKey=? AND canonicalName=?`,
10447
- args: [knowledgeScopeKey(scope), canonicalName(name)]
10448
- });
10449
- return result.rows[0] ? parseNode(result.rows[0]) : null;
10050
+ getNote(input) {
10051
+ return this.#pages.getNote(input);
10450
10052
  }
10451
- async #resolveNode(executor, name, scope) {
10452
- const keys = visibleScopeKeys(scope);
10453
- const candidates = (await executor.execute({
10454
- sql: `SELECT *,scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_NODES}" WHERE type='node' AND canonicalName=? AND ("scopeKey" IN (${keys.map(() => "?").join(",")}) OR "mergedInto" IS NOT NULL)`,
10455
- args: [canonicalName(name), ...keys]
10456
- })).rows.map(parseNode).sort((left, right) => right.scope.length - left.scope.length);
10457
- for (const candidate of candidates) {
10458
- const terminal = await this.#resolveTerminalNode(executor, candidate.id);
10459
- if (terminal && isKnowledgeScopeVisible(terminal.scope, scope)) return terminal;
10460
- }
10461
- return null;
10053
+ listNotes(input) {
10054
+ return this.#pages.listNotes(input);
10462
10055
  }
10463
- async #resolveTerminalNode(executor, id) {
10464
- let node = await this.#getNode(executor, id);
10465
- const seen = /* @__PURE__ */ new Set();
10466
- while (node?.mergedInto) {
10467
- if (seen.has(node.id)) throw new Error(`Knowledge merge cycle detected at ${node.id}`);
10468
- seen.add(node.id);
10469
- node = await this.#getNode(executor, node.mergedInto);
10470
- }
10471
- return node;
10056
+ countNotes(input) {
10057
+ return this.#pages.countNotes(input);
10472
10058
  }
10473
- async #getKnowledge(executor, id, includeDeleted) {
10474
- const result = await executor.execute({
10475
- sql: `SELECT *,scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_RECORDS}" WHERE id=?${includeDeleted ? "" : " AND deletedAt IS NULL"}`,
10476
- args: [id]
10477
- });
10478
- return result.rows[0] ? parseKnowledge(result.rows[0]) : null;
10059
+ listNotesMentioning(input) {
10060
+ return this.#pages.listNotesMentioning(input);
10479
10061
  }
10480
- async #queryKnowledge(input, relationship) {
10481
- const scope = canonicalizeKnowledgeScope(input.scope);
10482
- const node = await this.#resolveTerminalNode(this.#readExecutor, nodeReferenceId(input.node));
10483
- if (!node) return { records: [] };
10484
- const keys = visibleScopeKeys(scope);
10485
- const args = [
10486
- node.id,
10487
- ...relationship === "related" ? [node.id] : [],
10488
- ...keys
10489
- ];
10490
- if (input.after) args.push(input.after);
10491
- args.push((input.limit ?? 100) + 1);
10492
- const records = (await this.#readExecutor.execute({
10493
- sql: `SELECT DISTINCT f.*,f.scope AS "scopeJson" FROM "${TABLE_KNOWLEDGE_RECORDS}" f${relationship === "about" ? "" : ` LEFT JOIN "${TABLE_KNOWLEDGE_MENTIONS}" m ON m.sourceType='record' AND m.sourceId=f.id`} WHERE ${relationship === "about" ? "f.node=?" : relationship === "mentioning" ? "m.recordId=?" : "(f.node=? OR m.recordId=?)"} AND ${visibleSql(keys, "f.scopeKey")}${input.includeDeleted ? "" : " AND f.deletedAt IS NULL"}${input.after ? " AND f.id < ?" : ""} ORDER BY f.id DESC LIMIT ?`,
10494
- args
10495
- })).rows.map(parseKnowledge);
10496
- const limit = input.limit ?? 100;
10497
- return {
10498
- records: records.slice(0, limit),
10499
- nextCursor: records.length > limit ? records[limit - 1]?.id : void 0
10500
- };
10062
+ addNote(input) {
10063
+ return this.#pages.addNote(input);
10501
10064
  }
10502
- async #resolveScopeNodeIds(executor, addresses) {
10503
- const scopeNodeIds = /* @__PURE__ */ new Set();
10504
- for (const address of addresses) {
10505
- const result = await executor.execute({
10506
- sql: `SELECT scopeNodeId FROM "${TABLE_KNOWLEDGE_SCOPE_ADDRESSES}" WHERE address=?`,
10507
- args: [address]
10508
- });
10509
- if (result.rows[0]?.scopeNodeId != null) scopeNodeIds.add(String(result.rows[0].scopeNodeId));
10510
- }
10511
- return [...scopeNodeIds];
10065
+ restampNote(input) {
10066
+ return this.#pages.restampNote(input);
10512
10067
  }
10513
- async #replaceNodeScopes(executor, nodeId, addresses, addedAt) {
10514
- await executor.execute({
10515
- sql: `DELETE FROM "${TABLE_KNOWLEDGE_NODE_SCOPES}" WHERE nodeId=?`,
10516
- args: [nodeId]
10517
- });
10518
- for (const scopeNodeId of await this.#resolveScopeNodeIds(executor, addresses)) await executor.execute({
10519
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_NODE_SCOPES}" (nodeId,scopeNodeId,addedAt) VALUES (?,?,?) ON CONFLICT DO NOTHING`,
10520
- args: [
10521
- nodeId,
10522
- scopeNodeId,
10523
- addedAt.toISOString()
10524
- ]
10525
- });
10068
+ removeNote(input) {
10069
+ return this.#pages.removeNote(input);
10526
10070
  }
10527
- /**
10528
- * Move a node's identity memberships from `from` to `to` without touching structural
10529
- * placements added by `#placeNodeInScopes`, which a scope change must not erase.
10530
- */
10531
- async #swapIdentityScopes(executor, nodeId, from, to, addedAt) {
10532
- const next = await this.#resolveScopeNodeIds(executor, to);
10533
- for (const scopeNodeId of await this.#resolveScopeNodeIds(executor, from)) {
10534
- if (next.includes(scopeNodeId)) continue;
10535
- await executor.execute({
10536
- sql: `DELETE FROM "${TABLE_KNOWLEDGE_NODE_SCOPES}" WHERE nodeId=? AND scopeNodeId=?`,
10537
- args: [nodeId, scopeNodeId]
10538
- });
10539
- }
10540
- for (const scopeNodeId of next) await executor.execute({
10541
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_NODE_SCOPES}" (nodeId,scopeNodeId,addedAt) VALUES (?,?,?) ON CONFLICT DO NOTHING`,
10542
- args: [
10543
- nodeId,
10544
- scopeNodeId,
10545
- addedAt.toISOString()
10546
- ]
10547
- });
10071
+ restoreNote(input) {
10072
+ return this.#pages.restoreNote(input);
10548
10073
  }
10549
- /**
10550
- * Additive structural placement: every address must resolve to a live scope node
10551
- * (unlike identity membership, an unknown address is a caller error, not a lazy
10552
- * materialization miss). Runs inside the caller's transaction, so a throw aborts
10553
- * the whole mutation.
10554
- */
10555
- async #placeNodeInScopes(executor, nodeId, addresses, addedAt) {
10556
- for (const address of addresses ?? []) {
10557
- const scopeNodeId = (await executor.execute({
10558
- sql: `SELECT sa.scopeNodeId AS "scopeNodeId" FROM "${TABLE_KNOWLEDGE_SCOPE_ADDRESSES}" sa JOIN "${TABLE_KNOWLEDGE_NODES}" n ON n.id=sa."scopeNodeId" WHERE sa.address=? AND n."isScope" AND n."deletedAt" IS NULL`,
10559
- args: [address]
10560
- })).rows[0]?.scopeNodeId;
10561
- if (scopeNodeId == null) throw new KnowledgeNotFoundError("scope", address);
10562
- await executor.execute({
10563
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_NODE_SCOPES}" ("nodeId","scopeNodeId","addedAt") VALUES (?,?,?) ON CONFLICT DO NOTHING`,
10564
- args: [
10565
- nodeId,
10566
- String(scopeNodeId),
10567
- addedAt.toISOString()
10568
- ]
10569
- });
10570
- }
10074
+ searchPages(input) {
10075
+ return this.#pages.searchPages(input);
10571
10076
  }
10572
- async #replaceRecordScopes(executor, recordId, addresses, addedAt) {
10573
- await executor.execute({
10574
- sql: `DELETE FROM "${TABLE_KNOWLEDGE_RECORD_SCOPES}" WHERE recordId=?`,
10575
- args: [recordId]
10576
- });
10577
- for (const scopeNodeId of await this.#resolveScopeNodeIds(executor, addresses)) await executor.execute({
10578
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_RECORD_SCOPES}" (recordId,scopeNodeId,addedAt) VALUES (?,?,?) ON CONFLICT DO NOTHING`,
10579
- args: [
10580
- recordId,
10581
- scopeNodeId,
10582
- addedAt.toISOString()
10583
- ]
10584
- });
10077
+ listPageActivity(input) {
10078
+ return this.#pages.listPageActivity(input);
10585
10079
  }
10586
- async #replaceMentions(tx, sourceType, sourceId, text, resolutionScope, defaultScope) {
10587
- await tx.execute({
10588
- sql: `DELETE FROM "${TABLE_KNOWLEDGE_MENTIONS}" WHERE sourceType=? AND sourceId=?`,
10589
- args: [sourceType, sourceId]
10590
- });
10591
- for (const name of parseKnowledgeWikilinks(text)) {
10592
- let node = await this.#resolveNode(tx, name, resolutionScope);
10593
- if (!node) {
10594
- node = await this.#getNodeByName(tx, name, defaultScope);
10595
- if (node) node = await this.#resolveTerminalNode(tx, node.id);
10596
- if (!node) {
10597
- const now = /* @__PURE__ */ new Date();
10598
- node = {
10599
- id: crypto.randomUUID(),
10600
- type: "node",
10601
- name,
10602
- kind: "node",
10603
- scope: defaultScope,
10604
- version: 1,
10605
- createdAt: now,
10606
- updatedAt: now
10607
- };
10608
- await tx.execute({
10609
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_NODES}" (id,type,name,canonicalName,kind,content,isScope,scope,scopeKey,version,mergedInto,createdAt,updatedAt) VALUES (?,?,?,?,?,NULL,FALSE,jsonb(?),?,?,NULL,?,?)`,
10610
- args: [
10611
- node.id,
10612
- "node",
10613
- node.name,
10614
- canonicalName(node.name),
10615
- node.kind,
10616
- JSON.stringify(defaultScope),
10617
- knowledgeScopeKey(defaultScope),
10618
- 1,
10619
- now.toISOString(),
10620
- now.toISOString()
10621
- ]
10622
- });
10623
- await this.#replaceNodeScopes(tx, node.id, defaultScope, now);
10624
- await this.#activity(tx, "node-created", "node", node.id, defaultScope);
10625
- await this.#outbox(tx, "node", node.id, "upsert", 1, defaultScope);
10626
- }
10627
- }
10628
- await tx.execute({
10629
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_MENTIONS}" (sourceType,sourceId,recordId) VALUES (?,?,?) ON CONFLICT DO NOTHING`,
10630
- args: [
10631
- sourceType,
10632
- sourceId,
10633
- node.id
10634
- ]
10635
- });
10636
- }
10080
+ addPinAudience(input) {
10081
+ return this.#pages.addPinAudience(input);
10637
10082
  }
10638
- async #activity(executor, action, recordType, recordId, scope, sourceThreadId) {
10639
- const now = /* @__PURE__ */ new Date();
10640
- const [contextScopeId] = await this.#resolveScopeNodeIds(executor, scope);
10641
- await executor.execute({
10642
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_ACTIVITY}" (id,action,targetType,targetId,contextScopeId,recordType,recordId,scope,scopeKey,sourceThreadId,createdAt) VALUES (?,?,?,?,?,?,?,jsonb(?),?,?,?)`,
10643
- args: [
10644
- createKnowledgeUlid(),
10645
- action,
10646
- recordType,
10647
- recordId,
10648
- contextScopeId ?? null,
10649
- recordType,
10650
- recordId,
10651
- JSON.stringify(scope),
10652
- knowledgeScopeKey(scope),
10653
- sourceThreadId ?? null,
10654
- now.toISOString()
10655
- ]
10656
- });
10083
+ removePinAudience(input) {
10084
+ return this.#pages.removePinAudience(input);
10657
10085
  }
10658
- async #outbox(executor, documentType, id, operation, version, scope) {
10659
- const documentId = knowledgeSemanticDocumentId(documentType, id);
10660
- const idempotencyKey = knowledgeSemanticIdempotencyKey(documentId, operation, version);
10661
- const now = /* @__PURE__ */ new Date();
10662
- await executor.execute({
10663
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" (id,idempotencyKey,documentId,documentType,operation,scope,scopeKey,status,attempts,availableAt,claimedAt,claimedBy,createdAt,completedAt) VALUES (?,?,?,?,?,jsonb(?),?,'pending',0,?,NULL,NULL,?,NULL) ON CONFLICT DO NOTHING`,
10664
- args: [
10665
- createKnowledgeUlid(),
10666
- idempotencyKey,
10667
- documentId,
10668
- documentType,
10669
- operation,
10670
- JSON.stringify(scope),
10671
- knowledgeScopeKey(scope),
10672
- now.toISOString(),
10673
- now.toISOString()
10674
- ]
10675
- });
10086
+ listPins(input) {
10087
+ return this.#pages.listPins(input);
10676
10088
  }
10677
10089
  };
10678
10090
  // src/storage/domains/mcp-clients/index.ts