@mastra/libsql 1.28.0 → 1.29.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 { createClient } from "@libsql/client";
2
2
  import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
3
- import { AGENTS_SCHEMA, AGENT_VERSIONS_SCHEMA, AgentsStorage, BackgroundTasksStorage, BlobStore, ChannelsStorage, DATASETS_SCHEMA, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, DatasetsStorage, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, ExperimentsStorage, FAVORITES_SCHEMA, FactoryStorage, FavoritesStorage, HarnessStorage, KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA, KnowledgeConflictError, KnowledgeNotFoundError, KnowledgeStorage, MCPClientsStorage, MCPServersStorage, MCP_CLIENTS_SCHEMA, MCP_CLIENT_VERSIONS_SCHEMA, MCP_SERVERS_SCHEMA, MCP_SERVER_VERSIONS_SCHEMA, MastraCompositeStore, MemoryStorage, NotificationsStorage, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, ObservabilityStorage, PROMPT_BLOCKS_SCHEMA, PROMPT_BLOCK_VERSIONS_SCHEMA, PromptBlocksStorage, RUN_FENCING_TABLE_SCHEMAS, RunFenceConflictError, SCORERS_SCHEMA, SCORER_DEFINITIONS_SCHEMA, SCORER_DEFINITION_VERSIONS_SCHEMA, SKILLS_SCHEMA, SKILL_BLOBS_SCHEMA, SKILL_VERSIONS_SCHEMA, SPAN_SCHEMA, 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_HARNESS_SESSIONS, 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, THREAD_STATE_SCHEMA, TOOL_PROVIDER_CONNECTIONS_SCHEMA, ThreadStateStorage, ToolProviderConnectionsStorage, TraceStatus, UniqueViolationError, WORKSPACES_SCHEMA, WORKSPACE_VERSIONS_SCHEMA, WorkflowDefinitionsStorage, WorkflowsStorage, WorkspacesStorage, calculatePagination, canonicalizeKnowledgeScope, createKnowledgeUlid, createStorageErrorId, createVectorErrorId, ensureDate, executeRetentionPrune, getSqlType, hasErrorCode, isKnowledgeScopeVisible, isRunFenceConflictError, knowledgeScopeKey, knowledgeSemanticDocumentId, knowledgeSemanticIdempotencyKey, listTracesArgsSchema, matchesExpectedWorkflowStatus, matchesRunFence, mergeWorkflowStepResult, normalizePerPage, normalizeScheduleTarget, parseKnowledgeNodeCursor, parseKnowledgeWikilinks, resolveListOrderBy, resolveRetentionTargets, resolveRunFence, retentionCutoffMs, runRetentionBatches, safelyParseJSON, toTraceSpans, transformScoreRow, validateStorageMetadataFilter } from "@mastra/core/storage";
3
+ import { AGENTS_SCHEMA, AGENT_VERSIONS_SCHEMA, AgentsStorage, BackgroundTasksStorage, BlobStore, ChannelsStorage, DATASETS_SCHEMA, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, DatasetsStorage, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, ExperimentsStorage, FAVORITES_SCHEMA, FactoryStorage, FavoritesStorage, HarnessStorage, KnowledgeConflictError, KnowledgeNotFoundError, KnowledgeSchemaResetRequiredError, KnowledgeStorage, MCPClientsStorage, MCPServersStorage, MCP_CLIENTS_SCHEMA, MCP_CLIENT_VERSIONS_SCHEMA, MCP_SERVERS_SCHEMA, MCP_SERVER_VERSIONS_SCHEMA, MastraCompositeStore, MemoryStorage, NotificationsStorage, OBSERVATIONAL_MEMORY_TABLE_SCHEMA, ObservabilityStorage, PROMPT_BLOCKS_SCHEMA, PROMPT_BLOCK_VERSIONS_SCHEMA, PromptBlocksStorage, RUN_FENCING_TABLE_SCHEMAS, RunFenceConflictError, SCORERS_SCHEMA, SCORER_DEFINITIONS_SCHEMA, SCORER_DEFINITION_VERSIONS_SCHEMA, SKILLS_SCHEMA, SKILL_BLOBS_SCHEMA, SKILL_VERSIONS_SCHEMA, SPAN_SCHEMA, 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_HARNESS_SESSIONS, 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, THREAD_STATE_SCHEMA, TOOL_PROVIDER_CONNECTIONS_SCHEMA, ThreadStateStorage, ToolProviderConnectionsStorage, TraceStatus, UniqueViolationError, WORKSPACES_SCHEMA, WORKSPACE_VERSIONS_SCHEMA, WorkflowDefinitionsStorage, WorkflowsStorage, WorkspacesStorage, calculatePagination, createKnowledgeUlid, createStorageErrorId, createVectorErrorId, ensureDate, executeRetentionPrune, getSqlType, hasErrorCode, isRunFenceConflictError, listTracesArgsSchema, matchesExpectedWorkflowStatus, matchesRunFence, mergeWorkflowStepResult, normalizePerPage, normalizeScheduleTarget, resolveListOrderBy, resolveRetentionTargets, resolveRunFence, retentionCutoffMs, runRetentionBatches, safelyParseJSON, 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 { basename, dirname, isAbsolute, join, resolve } from "path";
@@ -8,7 +8,6 @@ import { AsyncLocalStorage } from "async_hooks";
8
8
  import { BaseFilterTranslator } from "@mastra/core/vector/filter";
9
9
  import { realpath } from "fs/promises";
10
10
  import { MastraBase } from "@mastra/core/base";
11
- import { randomUUID } from "crypto";
12
11
  import { coreFeatures } from "@mastra/core/features";
13
12
  import { MessageList } from "@mastra/core/agent";
14
13
  import { saveScorePayloadSchema } from "@mastra/core/evals";
@@ -692,7 +691,7 @@ const FILTER_OPERATORS = {
692
691
  transformValue: () => {
693
692
  if (Array.isArray(value)) return [JSON.stringify(value)];
694
693
  if (typeof value === "object" && value !== null) return [JSON.stringify(value)];
695
- if (typeof value === "string") return [escapeLikePattern$1(value)];
694
+ if (typeof value === "string") return [escapeLikePattern(value)];
696
695
  return [value];
697
696
  }
698
697
  };
@@ -709,7 +708,7 @@ const parseJsonPathKey = (key) => {
709
708
  const getJsonPath = (key) => {
710
709
  return `'$.${parseJsonPathKey(key)}'`;
711
710
  };
712
- function escapeLikePattern$1(str) {
711
+ function escapeLikePattern(str) {
713
712
  return str.replace(/([%_\\])/g, "\\$1");
714
713
  }
715
714
  function buildFilterQuery(filter) {
@@ -3394,7 +3393,7 @@ function serializeJson(v) {
3394
3393
  if (serialized === void 0) throw new Error("Failed to serialize background task value as JSON");
3395
3394
  return serialized;
3396
3395
  }
3397
- function parseJson$4(val) {
3396
+ function parseJson$3(val) {
3398
3397
  if (val == null) return void 0;
3399
3398
  if (typeof val === "string") try {
3400
3399
  return JSON.parse(val);
@@ -3409,14 +3408,14 @@ function rowToTask(row) {
3409
3408
  status: String(row.status),
3410
3409
  toolName: String(row.tool_name),
3411
3410
  toolCallId: String(row.tool_call_id),
3412
- args: parseJson$4(row.args) ?? {},
3411
+ args: parseJson$3(row.args) ?? {},
3413
3412
  agentId: String(row.agent_id),
3414
3413
  threadId: row.thread_id != null ? String(row.thread_id) : void 0,
3415
3414
  resourceId: row.resource_id != null ? String(row.resource_id) : void 0,
3416
3415
  runId: String(row.run_id),
3417
- result: parseJson$4(row.result),
3418
- error: parseJson$4(row.error),
3419
- suspendPayload: parseJson$4(row.suspend_payload),
3416
+ result: parseJson$3(row.result),
3417
+ error: parseJson$3(row.error),
3418
+ suspendPayload: parseJson$3(row.suspend_payload),
3420
3419
  retryCount: Number(row.retry_count),
3421
3420
  maxRetries: Number(row.max_retries),
3422
3421
  timeoutMs: Number(row.timeout_ms),
@@ -3427,7 +3426,7 @@ function rowToTask(row) {
3427
3426
  ownerId: row.ownerId != null ? String(row.ownerId) : void 0,
3428
3427
  leaseExpiresAt: row.leaseExpiresAt ? new Date(String(row.leaseExpiresAt)) : void 0,
3429
3428
  expiresAt: row.expiresAt ? new Date(String(row.expiresAt)) : void 0,
3430
- metadata: parseJson$4(row.metadata)
3429
+ metadata: parseJson$3(row.metadata)
3431
3430
  };
3432
3431
  }
3433
3432
  var BackgroundTasksLibSQL = class BackgroundTasksLibSQL extends BackgroundTasksStorage {
@@ -6394,10 +6393,10 @@ var FavoritesLibSQL = class extends FavoritesStorage {
6394
6393
  }
6395
6394
  };
6396
6395
  // src/storage/domains/harness/index.ts
6397
- const toDate$1 = (value) => new Date(value);
6396
+ const toDate = (value) => new Date(value);
6398
6397
  const toOptionalDate = (value) => {
6399
6398
  if (value == null) return void 0;
6400
- return toDate$1(value);
6399
+ return toDate(value);
6401
6400
  };
6402
6401
  function cloneJson(value) {
6403
6402
  return value === void 0 ? void 0 : structuredClone(value);
@@ -6408,8 +6407,8 @@ function hydratePendingItem(item) {
6408
6407
  kind: item.kind,
6409
6408
  status: item.status,
6410
6409
  sessionId: item.sessionId,
6411
- createdAt: toDate$1(item.createdAt),
6412
- updatedAt: toDate$1(item.updatedAt)
6410
+ createdAt: toDate(item.createdAt),
6411
+ updatedAt: toDate(item.updatedAt)
6413
6412
  };
6414
6413
  if (item.runId !== void 0) record.runId = item.runId;
6415
6414
  if (item.traceId !== void 0) record.traceId = item.traceId;
@@ -6427,8 +6426,8 @@ function rowToSession(row) {
6427
6426
  origin: row.origin,
6428
6427
  modeId: row.modeId,
6429
6428
  modelId: row.modelId,
6430
- createdAt: toDate$1(row.createdAt),
6431
- lastActivityAt: toDate$1(row.lastActivityAt)
6429
+ createdAt: toDate(row.createdAt),
6430
+ lastActivityAt: toDate(row.lastActivityAt)
6432
6431
  };
6433
6432
  if (row.parentSessionId != null) record.parentSessionId = row.parentSessionId;
6434
6433
  if (row.subagentDepth != null) record.subagentDepth = row.subagentDepth;
@@ -6537,1973 +6536,1585 @@ var HarnessLibSQL = class HarnessLibSQL extends HarnessStorage {
6537
6536
  })).map(rowToSession);
6538
6537
  }
6539
6538
  };
6540
- // ../../packages/_internal-core/dist/knowledge-compat/index.js
6541
- const KNOWLEDGE_V2_CORE_FEATURE = "knowledge-v2";
6542
- /** Hard cap on scope nodes returned by one `listScopeNodes` read. */
6543
- const MAX_KNOWLEDGE_SCOPE_NODES = 1e3;
6544
- function knowledgeScopeNodeFilterKey(input) {
6545
- return JSON.stringify([
6546
- input.withinAddress ?? null,
6547
- input.addresses ? [...input.addresses].sort() : null,
6548
- input.ids ? [...input.ids].sort() : null
6549
- ]);
6550
- }
6551
- function createKnowledgeScopeNodeCursor(scope, input) {
6552
- return encodeURIComponent(JSON.stringify({
6553
- version: 1,
6554
- type: "scope",
6555
- name: scope.name,
6556
- id: scope.id,
6557
- filter: knowledgeScopeNodeFilterKey(input)
6558
- }));
6559
- }
6560
- /** Validates the page size and cursor of a `listScopeNodes` query; throws on a cursor from a different query. */
6561
- function parseListKnowledgeScopeNodesInput(input = {}) {
6562
- const requested = Number.isFinite(input.limit) ? Math.trunc(input.limit) : MAX_KNOWLEDGE_SCOPE_NODES;
6563
- const limit = Math.min(Math.max(requested, 1), MAX_KNOWLEDGE_SCOPE_NODES);
6564
- if (!input.cursor) return {
6565
- limit,
6566
- after: null
6567
- };
6568
- let value;
6569
- try {
6570
- value = JSON.parse(decodeURIComponent(input.cursor));
6571
- } catch {
6572
- throw new Error("Invalid Knowledge scope node cursor.");
6573
- }
6574
- const parsed = value && typeof value === "object" ? value : {};
6575
- 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.");
6576
- return {
6577
- limit,
6578
- after: {
6579
- name: parsed.name,
6580
- id: parsed.id
6581
- }
6582
- };
6583
- }
6584
- /** Builds a page from up to `limit + 1` name/id-ordered scope nodes. */
6585
- function pageKnowledgeScopeNodes(rows, limit, input) {
6586
- const scopes = rows.slice(0, limit);
6587
- const last = scopes.at(-1);
6588
- return {
6589
- scopes,
6590
- nextCursor: rows.length > limit && last ? createKnowledgeScopeNodeCursor(last, input) : null
6591
- };
6592
- }
6593
- /** Clamps a requested member limit to 1–{@link MAX_KNOWLEDGE_SCOPE_MEMBERS_LIMIT}. */
6594
- function knowledgeScopeMembersLimit(limit) {
6595
- if (limit === void 0 || !Number.isFinite(limit)) return 500;
6596
- return Math.min(Math.max(Math.trunc(limit), 1), 500);
6597
- }
6598
- /** Validates the page size and cursor of a `listScopeMembers` query; throws on a cursor from another scope. */
6599
- function parseListKnowledgeScopeMembersInput(input) {
6600
- const limit = knowledgeScopeMembersLimit(input.limit);
6601
- if (!input.cursor) return {
6602
- limit,
6603
- after: null
6604
- };
6605
- let value;
6606
- try {
6607
- value = JSON.parse(decodeURIComponent(input.cursor));
6608
- } catch {
6609
- throw new Error("Invalid Knowledge scope member cursor.");
6610
- }
6611
- const parsed = value && typeof value === "object" ? value : {};
6612
- const updatedAt = typeof parsed.updatedAt === "string" ? new Date(parsed.updatedAt) : /* @__PURE__ */ new Date(NaN);
6613
- 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.");
6614
- return {
6615
- limit,
6616
- after: {
6617
- updatedAt,
6618
- name: parsed.name,
6619
- id: parsed.id
6620
- }
6621
- };
6622
- }
6623
- /** Builds a page from up to `limit + 1` members in `listScopeMembers` order. */
6624
- function pageKnowledgeScopeMembers(rows, limit, input) {
6625
- const members = rows.slice(0, limit);
6626
- const last = members.at(-1);
6627
- const hasMore = rows.length > limit;
6628
- return {
6629
- members,
6630
- hasMore,
6631
- nextCursor: hasMore && last ? encodeURIComponent(JSON.stringify({
6632
- version: 1,
6633
- type: "scope-member",
6634
- scopeNodeId: input.scopeNodeId,
6635
- updatedAt: last.updatedAt.toISOString(),
6636
- name: last.name,
6637
- id: last.id
6638
- })) : null
6639
- };
6640
- }
6641
- const TABLE_KNOWLEDGE_NODES$1 = "mastra_knowledge_nodes";
6642
- const TABLE_KNOWLEDGE_RECORDS$1 = "mastra_knowledge_records";
6643
- const TABLE_KNOWLEDGE_MENTIONS$1 = "mastra_knowledge_mentions";
6644
- const TABLE_KNOWLEDGE_ACTIVITY$1 = "mastra_knowledge_activity";
6645
- const TABLE_KNOWLEDGE_SEMANTIC_OUTBOX$1 = "mastra_knowledge_semantic_outbox";
6646
- const TABLE_KNOWLEDGE_NODE_SCOPES = "mastra_knowledge_node_scopes";
6647
- const TABLE_KNOWLEDGE_RECORD_SCOPES = "mastra_knowledge_record_scopes";
6648
- const TABLE_KNOWLEDGE_SCOPE_GRANTS = "mastra_knowledge_scope_grants";
6649
- const TABLE_KNOWLEDGE_ACCESS_STATE = "mastra_knowledge_access_state";
6650
- const TABLE_KNOWLEDGE_SCOPE_ADDRESSES = "mastra_knowledge_scope_addresses";
6651
- const TABLE_KNOWLEDGE_NODE_ADDRESSES = "mastra_knowledge_node_addresses";
6652
- const TABLE_KNOWLEDGE_IMPORT_STATE = "mastra_knowledge_import_state";
6653
- const TABLE_KNOWLEDGE_IMPORT_RUNS = "mastra_knowledge_import_runs";
6654
- const TABLE_KNOWLEDGE_PROPOSALS = "mastra_knowledge_proposals";
6655
6539
  const KNOWLEDGE_TABLE_NAMES = [
6656
- TABLE_KNOWLEDGE_NODES$1,
6657
- TABLE_KNOWLEDGE_RECORDS$1,
6658
- TABLE_KNOWLEDGE_MENTIONS$1,
6659
- TABLE_KNOWLEDGE_ACTIVITY$1,
6660
- TABLE_KNOWLEDGE_SEMANTIC_OUTBOX$1,
6661
- TABLE_KNOWLEDGE_NODE_SCOPES,
6662
- TABLE_KNOWLEDGE_RECORD_SCOPES,
6663
- TABLE_KNOWLEDGE_SCOPE_GRANTS,
6664
- TABLE_KNOWLEDGE_ACCESS_STATE,
6665
- TABLE_KNOWLEDGE_SCOPE_ADDRESSES,
6666
- TABLE_KNOWLEDGE_NODE_ADDRESSES,
6667
- TABLE_KNOWLEDGE_IMPORT_STATE,
6668
- TABLE_KNOWLEDGE_IMPORT_RUNS,
6669
- TABLE_KNOWLEDGE_PROPOSALS
6540
+ "mastra_knowledge_nodes",
6541
+ "mastra_knowledge_records",
6542
+ "mastra_knowledge_mentions",
6543
+ "mastra_knowledge_activity",
6544
+ "mastra_knowledge_semantic_outbox",
6545
+ "mastra_knowledge_node_scopes",
6546
+ "mastra_knowledge_record_scopes",
6547
+ "mastra_knowledge_scope_grants",
6548
+ "mastra_knowledge_access_state",
6549
+ "mastra_knowledge_scope_addresses",
6550
+ "mastra_knowledge_node_addresses",
6551
+ "mastra_knowledge_import_state",
6552
+ "mastra_knowledge_import_runs",
6553
+ "mastra_knowledge_proposals"
6670
6554
  ];
6671
6555
  /** Knowledge v1 tables with no v2 equivalent; an explicit schema reset drops them. */
6672
6556
  const RETIRED_KNOWLEDGE_TABLE_NAMES = ["mastra_knowledge_cursors"];
6673
- /** Tables and indexes published v1 adapters created for every app, whether or not it used Knowledge. */
6674
- const PUBLISHED_KNOWLEDGE_V1_TABLE_NAMES = /* @__PURE__ */ new Set([
6675
- TABLE_KNOWLEDGE_NODES$1,
6676
- TABLE_KNOWLEDGE_RECORDS$1,
6677
- TABLE_KNOWLEDGE_MENTIONS$1,
6678
- TABLE_KNOWLEDGE_ACTIVITY$1,
6679
- TABLE_KNOWLEDGE_SEMANTIC_OUTBOX$1,
6557
+ const KNOWLEDGE_PAGES_CORE_FEATURE = "knowledge-pages";
6558
+ const TABLE_KNOWLEDGE_PAGES = "mastra_knowledge_pages";
6559
+ const TABLE_KNOWLEDGE_NOTES = "mastra_knowledge_notes";
6560
+ const TABLE_KNOWLEDGE_NOTE_STAMPS = "mastra_knowledge_note_stamps";
6561
+ /** Same name as the schema-2 table; schema 4 re-keys it to note → page. */
6562
+ const TABLE_KNOWLEDGE_PAGE_MENTIONS = "mastra_knowledge_mentions";
6563
+ const TABLE_KNOWLEDGE_PINS = "mastra_knowledge_pins";
6564
+ /** Same name as schema 2; schema 4 re-keys it to scope/page/note. */
6565
+ const TABLE_KNOWLEDGE_PAGE_ACTIVITY = "mastra_knowledge_activity";
6566
+ /** Holds `{ id: 'knowledge', schemaVersion: 4 }`, written when the schema-4 tables are created. */
6567
+ const TABLE_KNOWLEDGE_PAGES_STATE = "mastra_knowledge_access_state";
6568
+ const KNOWLEDGE_PAGES_TABLE_NAMES = [
6569
+ TABLE_KNOWLEDGE_PAGES,
6570
+ TABLE_KNOWLEDGE_NOTES,
6571
+ TABLE_KNOWLEDGE_NOTE_STAMPS,
6572
+ TABLE_KNOWLEDGE_PAGE_MENTIONS,
6573
+ TABLE_KNOWLEDGE_PINS,
6574
+ TABLE_KNOWLEDGE_PAGE_ACTIVITY,
6575
+ TABLE_KNOWLEDGE_PAGES_STATE
6576
+ ];
6577
+ /** Every Knowledge table any schema version created. Reset drops these and nothing else. */
6578
+ const KNOWLEDGE_RESETTABLE_TABLE_NAMES = [.../* @__PURE__ */ new Set([
6579
+ ...KNOWLEDGE_PAGES_TABLE_NAMES,
6580
+ ...KNOWLEDGE_TABLE_NAMES,
6680
6581
  ...RETIRED_KNOWLEDGE_TABLE_NAMES
6681
- ]);
6682
- const PUBLISHED_KNOWLEDGE_V1_INDEX_NAMES = /* @__PURE__ */ new Set([
6683
- "idx_knowledge_nodes_identity",
6684
- "idx_knowledge_nodes_scope",
6685
- "idx_knowledge_records_node_latest",
6686
- "idx_knowledge_records_thread_latest",
6687
- "idx_knowledge_mentions_record",
6688
- "idx_knowledge_activity_latest",
6689
- "idx_knowledge_outbox_idempotency",
6690
- "idx_knowledge_outbox_claim"
6691
- ]);
6692
- const KNOWLEDGE_V2_NODES_SCHEMA = {
6693
- id: {
6694
- type: "text",
6695
- nullable: false,
6696
- primaryKey: true
6697
- },
6698
- name: {
6699
- type: "text",
6700
- nullable: false
6701
- },
6702
- kind: {
6703
- type: "text",
6704
- nullable: true
6705
- },
6706
- isScope: {
6707
- type: "boolean",
6708
- nullable: false
6709
- },
6710
- metadata: {
6711
- type: "jsonb",
6712
- nullable: true
6713
- },
6714
- version: {
6715
- type: "integer",
6716
- nullable: false
6717
- },
6718
- createdAt: {
6719
- type: "timestamp",
6720
- nullable: false
6721
- },
6722
- updatedAt: {
6723
- type: "timestamp",
6724
- nullable: false
6725
- },
6726
- deletedAt: {
6727
- type: "timestamp",
6728
- nullable: true
6729
- },
6730
- deletedBy: {
6731
- type: "text",
6732
- nullable: true
6733
- },
6734
- type: {
6735
- type: "text",
6736
- nullable: true
6737
- },
6738
- canonicalName: {
6739
- type: "text",
6740
- nullable: true
6741
- },
6742
- content: {
6743
- type: "text",
6744
- nullable: true
6745
- },
6746
- description: {
6747
- type: "text",
6748
- nullable: true
6749
- },
6750
- scope: {
6751
- type: "jsonb",
6752
- nullable: true
6753
- },
6754
- scopeKey: {
6755
- type: "text",
6756
- nullable: true
6757
- },
6758
- mergedInto: {
6759
- type: "text",
6760
- nullable: true
6761
- }
6762
- };
6763
- const KNOWLEDGE_V2_RECORDS_SCHEMA = {
6764
- id: {
6765
- type: "text",
6766
- nullable: false,
6767
- primaryKey: true
6768
- },
6769
- node: {
6770
- type: "text",
6771
- nullable: false,
6772
- references: {
6773
- table: TABLE_KNOWLEDGE_NODES$1,
6774
- column: "id"
6775
- }
6776
- },
6777
- text: {
6778
- type: "text",
6779
- nullable: false
6780
- },
6781
- metadata: {
6782
- type: "jsonb",
6783
- nullable: true
6784
- },
6785
- version: {
6786
- type: "integer",
6787
- nullable: false
6788
- },
6789
- capturedAt: {
6790
- type: "timestamp",
6791
- nullable: false
6792
- },
6793
- updatedAt: {
6794
- type: "timestamp",
6795
- nullable: false
6796
- },
6797
- deletedAt: {
6798
- type: "timestamp",
6799
- nullable: true
6800
- },
6801
- deletedBy: {
6802
- type: "text",
6803
- nullable: true
6804
- },
6805
- scope: {
6806
- type: "jsonb",
6807
- nullable: true
6808
- },
6809
- scopeKey: {
6810
- type: "text",
6811
- nullable: true
6812
- },
6813
- sourceThreadId: {
6814
- type: "text",
6815
- nullable: true
6816
- },
6817
- when: {
6818
- type: "timestamp",
6819
- nullable: true
6820
- }
6821
- };
6822
- const KNOWLEDGE_V2_MENTIONS_SCHEMA = {
6823
- recordId: {
6824
- type: "text",
6825
- nullable: false,
6826
- references: {
6827
- table: TABLE_KNOWLEDGE_RECORDS$1,
6828
- column: "id"
6829
- }
6830
- },
6831
- targetNodeId: {
6832
- type: "text",
6833
- nullable: true,
6834
- references: {
6835
- table: TABLE_KNOWLEDGE_NODES$1,
6836
- column: "id"
6837
- }
6838
- },
6839
- sourceType: {
6840
- type: "text",
6841
- nullable: true
6842
- },
6843
- sourceId: {
6844
- type: "text",
6845
- nullable: true
6846
- }
6847
- };
6848
- const KNOWLEDGE_NODE_SCOPES_SCHEMA = {
6849
- nodeId: {
6850
- type: "text",
6851
- nullable: false,
6852
- references: {
6853
- table: TABLE_KNOWLEDGE_NODES$1,
6854
- column: "id"
6855
- }
6856
- },
6857
- scopeNodeId: {
6858
- type: "text",
6859
- nullable: false,
6860
- references: {
6861
- table: TABLE_KNOWLEDGE_NODES$1,
6862
- column: "id"
6863
- }
6864
- },
6865
- addedAt: {
6866
- type: "timestamp",
6867
- nullable: false
6868
- }
6869
- };
6870
- const KNOWLEDGE_RECORD_SCOPES_SCHEMA = {
6871
- recordId: {
6872
- type: "text",
6873
- nullable: false,
6874
- references: {
6875
- table: TABLE_KNOWLEDGE_RECORDS$1,
6876
- column: "id"
6877
- }
6878
- },
6879
- scopeNodeId: {
6880
- type: "text",
6881
- nullable: false,
6882
- references: {
6883
- table: TABLE_KNOWLEDGE_NODES$1,
6884
- column: "id"
6885
- }
6886
- },
6887
- addedAt: {
6888
- type: "timestamp",
6889
- nullable: false
6890
- }
6891
- };
6892
- const KNOWLEDGE_SCOPE_GRANTS_SCHEMA = {
6893
- scopeNodeId: {
6894
- type: "text",
6895
- nullable: false,
6896
- references: {
6897
- table: TABLE_KNOWLEDGE_NODES$1,
6898
- column: "id"
6899
- }
6900
- },
6901
- scopeRefId: {
6902
- type: "text",
6903
- nullable: false,
6904
- references: {
6905
- table: TABLE_KNOWLEDGE_NODES$1,
6906
- column: "id"
6907
- }
6908
- },
6909
- role: {
6910
- type: "text",
6911
- nullable: false
6912
- },
6913
- canSuggest: {
6914
- type: "boolean",
6915
- nullable: true
6916
- }
6917
- };
6918
- const KNOWLEDGE_ACCESS_STATE_SCHEMA = {
6919
- id: {
6920
- type: "text",
6921
- nullable: false,
6922
- primaryKey: true
6923
- },
6924
- epoch: {
6925
- type: "integer",
6926
- nullable: false
6927
- },
6928
- schemaVersion: {
6929
- type: "integer",
6930
- nullable: false
6931
- }
6932
- };
6933
- const KNOWLEDGE_SCOPE_ADDRESSES_SCHEMA = {
6934
- address: {
6935
- type: "text",
6936
- nullable: false,
6937
- primaryKey: true
6938
- },
6939
- scopeNodeId: {
6940
- type: "text",
6941
- nullable: false,
6942
- references: {
6943
- table: TABLE_KNOWLEDGE_NODES$1,
6944
- column: "id"
6945
- }
6946
- }
6947
- };
6948
- const KNOWLEDGE_NODE_ADDRESSES_SCHEMA = {
6949
- source: {
6950
- type: "text",
6951
- nullable: false
6952
- },
6953
- address: {
6954
- type: "text",
6955
- nullable: false
6956
- },
6957
- nodeId: {
6958
- type: "text",
6959
- nullable: false,
6960
- references: {
6961
- table: TABLE_KNOWLEDGE_NODES$1,
6962
- column: "id"
6963
- }
6964
- }
6965
- };
6966
- const KNOWLEDGE_IMPORT_STATE_SCHEMA = {
6967
- importerId: {
6968
- type: "text",
6969
- nullable: false
6970
- },
6971
- binding: {
6972
- type: "text",
6973
- nullable: false
6974
- },
6975
- key: {
6976
- type: "text",
6977
- nullable: false
6978
- },
6979
- value: {
6980
- type: "text",
6981
- nullable: false
6982
- }
6983
- };
6984
- const KNOWLEDGE_IMPORT_RUNS_SCHEMA = {
6985
- id: {
6986
- type: "text",
6987
- nullable: false,
6988
- primaryKey: true
6989
- },
6990
- importerId: {
6991
- type: "text",
6992
- nullable: false
6993
- },
6994
- binding: {
6995
- type: "text",
6996
- nullable: false
6997
- },
6998
- importKind: {
6999
- type: "text",
7000
- nullable: false
7001
- },
7002
- triggerKind: {
7003
- type: "text",
7004
- nullable: false
7005
- },
7006
- status: {
7007
- type: "text",
7008
- nullable: false
7009
- },
7010
- error: {
7011
- type: "text",
7012
- nullable: true
7013
- },
7014
- transcriptThreadId: {
7015
- type: "text",
7016
- nullable: true
7017
- },
7018
- traceId: {
7019
- type: "text",
7020
- nullable: true
7021
- },
7022
- queuedAt: {
7023
- type: "timestamp",
7024
- nullable: false
7025
- },
7026
- startedAt: {
7027
- type: "timestamp",
7028
- nullable: true
7029
- },
7030
- completedAt: {
7031
- type: "timestamp",
7032
- nullable: true
7033
- }
7034
- };
7035
- const KNOWLEDGE_V2_ACTIVITY_SCHEMA = {
7036
- id: {
7037
- type: "text",
7038
- nullable: false,
7039
- primaryKey: true
7040
- },
7041
- action: {
7042
- type: "text",
7043
- nullable: false
7044
- },
7045
- targetType: {
7046
- type: "text",
7047
- nullable: true
7048
- },
7049
- targetId: {
7050
- type: "text",
7051
- nullable: true
7052
- },
7053
- contextScopeId: {
7054
- type: "text",
7055
- nullable: true,
7056
- references: {
7057
- table: TABLE_KNOWLEDGE_NODES$1,
7058
- column: "id"
7059
- }
7060
- },
7061
- importRunId: {
7062
- type: "text",
7063
- nullable: true,
7064
- references: {
7065
- table: TABLE_KNOWLEDGE_IMPORT_RUNS,
7066
- column: "id"
7067
- }
7068
- },
7069
- details: {
7070
- type: "jsonb",
7071
- nullable: true
7072
- },
7073
- createdAt: {
7074
- type: "timestamp",
7075
- nullable: false
7076
- },
7077
- recordType: {
7078
- type: "text",
7079
- nullable: true
7080
- },
7081
- recordId: {
7082
- type: "text",
7083
- nullable: true
7084
- },
7085
- scope: {
7086
- type: "jsonb",
7087
- nullable: true
7088
- },
7089
- scopeKey: {
7090
- type: "text",
7091
- nullable: true
7092
- },
7093
- sourceThreadId: {
7094
- type: "text",
7095
- nullable: true
7096
- }
7097
- };
7098
- const KNOWLEDGE_PROPOSALS_SCHEMA = {
7099
- id: {
7100
- type: "text",
7101
- nullable: false,
7102
- primaryKey: true
7103
- },
7104
- targetType: {
7105
- type: "text",
7106
- nullable: false
7107
- },
7108
- targetId: {
7109
- type: "text",
7110
- nullable: false
7111
- },
7112
- action: {
7113
- type: "text",
7114
- nullable: false
7115
- },
7116
- changes: {
7117
- type: "jsonb",
7118
- nullable: false
7119
- },
7120
- reason: {
7121
- type: "text",
7122
- nullable: true
7123
- },
7124
- proposerContextScopeId: {
7125
- type: "text",
7126
- nullable: false
7127
- },
7128
- expectedVersion: {
7129
- type: "integer",
7130
- nullable: false
7131
- },
7132
- status: {
7133
- type: "text",
7134
- nullable: false
7135
- },
7136
- reviewerContextScopeId: {
7137
- type: "text",
7138
- nullable: true
7139
- },
7140
- reviewedAt: {
7141
- type: "timestamp",
7142
- nullable: true
7143
- },
7144
- createdAt: {
7145
- type: "timestamp",
7146
- nullable: false
6582
+ ])];
6583
+ /** Schema-1/2 tables whose presence means the store needs a reset before schema 4 can run. */
6584
+ const LEGACY_KNOWLEDGE_TABLE_NAMES = new Set([...KNOWLEDGE_TABLE_NAMES, ...RETIRED_KNOWLEDGE_TABLE_NAMES].filter((name) => !KNOWLEDGE_PAGES_TABLE_NAMES.includes(name)));
6585
+ /**
6586
+ * Classifies what an adapter found before creating schema-4 tables. `tableNames` is every
6587
+ * `mastra_knowledge_*` table present; `schemaVersion` is the state row's version, if any.
6588
+ */
6589
+ function inspectKnowledgePagesSchema(snapshot) {
6590
+ const legacy = snapshot.tableNames.filter((name) => LEGACY_KNOWLEDGE_TABLE_NAMES.has(name));
6591
+ if (legacy.length > 0) return {
6592
+ status: "incompatible-reset-required",
6593
+ schemaVersion: snapshot.schemaVersion ?? null,
6594
+ reason: `found Knowledge tables from an earlier schema (${legacy.join(", ")})`
6595
+ };
6596
+ if (snapshot.schemaVersion === 4) return {
6597
+ status: "compatible",
6598
+ schemaVersion: 4
6599
+ };
6600
+ if (snapshot.schemaVersion === void 0) {
6601
+ const present = snapshot.tableNames.filter((name) => KNOWLEDGE_PAGES_TABLE_NAMES.includes(name));
6602
+ if (present.length === 0) return {
6603
+ status: "uninitialized",
6604
+ schemaVersion: null
6605
+ };
6606
+ return {
6607
+ status: "incompatible-reset-required",
6608
+ schemaVersion: null,
6609
+ reason: `found Knowledge tables (${present.join(", ")}) without a schema version`
6610
+ };
7147
6611
  }
7148
- };
7149
- function assertKnowledgeV2CoreSupport(features) {
7150
- 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.`);
7151
- }
7152
- function resolveKnowledgeV2Core(storageModule) {
7153
- if (typeof storageModule !== "object" || storageModule === null) throw new Error("@mastra/core advertises Knowledge v2 without the required storage API");
7154
- const { assertKnowledgeDescriptionWithinBound: assertDescription, assertKnowledgeRecordTextWithinBound: assertRecordText, assertKnowledgeSchemaCompatible: assertCompatible, inspectKnowledgeSchema: inspectSchema } = storageModule;
7155
- 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");
7156
6612
  return {
7157
- assertKnowledgeDescriptionWithinBound: (description) => assertDescription(description),
7158
- assertKnowledgeRecordTextWithinBound: (text) => assertRecordText(text),
7159
- assertKnowledgeSchemaCompatible: (inspection) => assertCompatible(inspection),
7160
- inspectKnowledgeSchema: (snapshot) => inspectSchema(snapshot)
6613
+ status: "incompatible-reset-required",
6614
+ schemaVersion: snapshot.schemaVersion,
6615
+ reason: `Knowledge schema version ${snapshot.schemaVersion} is not 4`
7161
6616
  };
7162
6617
  }
7163
- function createKnowledgeV2CoreLoader(features, loadStorageModule) {
7164
- let knowledgeV2Core;
6618
+ /** Schema-2 table names schema 4 reuses with a different shape. */
6619
+ const REUSED_KNOWLEDGE_TABLE_NAMES = KNOWLEDGE_TABLE_NAMES.filter((name) => KNOWLEDGE_PAGES_TABLE_NAMES.includes(name));
6620
+ /**
6621
+ * The old Knowledge tables an adapter drops on init, rows included: Knowledge before schema 4 was an
6622
+ * experimental store with no migration. Every schema-1/2-only table present is dropped. The table
6623
+ * names schema 4 reuses (mentions, activity, the state table) are dropped too, but only when an old
6624
+ * table is present and no schema-4 state row exists, so they are old-shaped. Schema-4-only tables
6625
+ * are never listed. On a schema-4 store this lists only tables an older process recreated during a
6626
+ * rolling deploy. Drop order is safe for adapters that enforce references.
6627
+ */
6628
+ function legacyKnowledgeTablesToDrop(snapshot) {
6629
+ const present = new Set(snapshot.tableNames);
6630
+ const legacy = [...LEGACY_KNOWLEDGE_TABLE_NAMES].filter((name) => present.has(name));
6631
+ if (legacy.length === 0) return [];
6632
+ const reused = snapshot.schemaVersion === 4 ? [] : REUSED_KNOWLEDGE_TABLE_NAMES.filter((name) => present.has(name));
6633
+ const drop = /* @__PURE__ */ new Set([...legacy, ...reused]);
6634
+ return [...RETIRED_KNOWLEDGE_TABLE_NAMES, ...[...KNOWLEDGE_TABLE_NAMES].reverse()].filter((name) => drop.has(name));
6635
+ }
6636
+ const KNOWLEDGE_PAGES_CORE_FUNCTIONS = [
6637
+ "assertKnowledgePageDescriptionWithinBound",
6638
+ "assertKnowledgeNoteTextWithinBound",
6639
+ "canonicalKnowledgeName",
6640
+ "knowledgePositionBetween",
6641
+ "KnowledgeMoveTooLargeError",
6642
+ "KnowledgePageDepthError",
6643
+ "KnowledgePageHasChildrenError",
6644
+ "KnowledgePageKeyConflictError"
6645
+ ];
6646
+ const KNOWLEDGE_PAGES_CORE_NUMBERS = [
6647
+ "MAX_KNOWLEDGE_MOVE_PAGES",
6648
+ "MAX_KNOWLEDGE_PAGE_DEPTH",
6649
+ "MAX_KNOWLEDGE_PAGE_LIST_LIMIT"
6650
+ ];
6651
+ function resolveKnowledgePagesCore(storageModule) {
6652
+ const module = typeof storageModule === "object" && storageModule !== null ? storageModule : {};
6653
+ const missing = [...KNOWLEDGE_PAGES_CORE_FUNCTIONS.filter((name) => typeof module[name] !== "function"), ...KNOWLEDGE_PAGES_CORE_NUMBERS.filter((name) => typeof module[name] !== "number")];
6654
+ if (missing.length > 0) throw new Error(`@mastra/core advertises Knowledge pages without the required storage API (missing ${missing.join(", ")})`);
6655
+ return module;
6656
+ }
6657
+ /** Loads core's page-store runtime once, after checking core advertises `knowledge-pages`. */
6658
+ function createKnowledgePagesCoreLoader(features, loadStorageModule) {
6659
+ let core;
7165
6660
  return async () => {
7166
- assertKnowledgeV2CoreSupport(features);
7167
- knowledgeV2Core ??= loadStorageModule().then(resolveKnowledgeV2Core).catch((error) => {
7168
- knowledgeV2Core = void 0;
6661
+ 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.`);
6662
+ core ??= loadStorageModule().then(resolveKnowledgePagesCore).catch((error) => {
6663
+ core = void 0;
7169
6664
  throw error;
7170
6665
  });
7171
- return knowledgeV2Core;
6666
+ return core;
7172
6667
  };
7173
6668
  }
7174
- // src/storage/domains/knowledge/index.ts
7175
- const loadKnowledgeV2Core = createKnowledgeV2CoreLoader(coreFeatures, () => import("@mastra/core/storage"));
7176
- async function assertKnowledgeDescriptionWithinBoundCompat(description) {
7177
- const { assertKnowledgeDescriptionWithinBound } = await loadKnowledgeV2Core();
7178
- assertKnowledgeDescriptionWithinBound(description);
7179
- }
7180
- async function assertKnowledgeRecordTextWithinBoundCompat(text) {
7181
- const { assertKnowledgeRecordTextWithinBound } = await loadKnowledgeV2Core();
7182
- assertKnowledgeRecordTextWithinBound(text);
7183
- }
7184
- const reconcileChains = /* @__PURE__ */ new Map();
7185
- const unidentifiedClientReconcileKey = {};
7186
- function withReconcileLock(key, operation) {
7187
- const lockKey = typeof key === "string" ? key : unidentifiedClientReconcileKey;
7188
- const result = (reconcileChains.get(lockKey) ?? Promise.resolve()).then(operation, operation);
7189
- const tail = result.then(() => void 0, () => void 0);
7190
- reconcileChains.set(lockKey, tail);
7191
- tail.finally(() => {
7192
- if (reconcileChains.get(lockKey) === tail) reconcileChains.delete(lockKey);
7193
- });
7194
- return result;
7195
- }
7196
6669
  /**
7197
- * Scope keys visible to a caller holding `scope`: a row is visible when its scope is a subset of the
7198
- * caller's (companion entries such as `resource:x:uncurated` make this more than a prefix match).
7199
- * Matching rows by `scopeKey` keeps visibility filters on an index; a caller scope has only a few
7200
- * entries, so the list stays small.
6670
+ * Keyword-search words: the query split on whitespace, lowercased, deduplicated. Every word must
6671
+ * appear (as a case-insensitive substring) in a hit; an empty list means the search returns nothing.
7201
6672
  */
7202
- function visibleScopeKeys(scope) {
7203
- const canonical = canonicalizeKnowledgeScope(scope);
7204
- const keys = /* @__PURE__ */ new Set();
7205
- for (let mask = 1; mask < 1 << canonical.length; mask++) try {
7206
- keys.add(knowledgeScopeKey(canonical.filter((_, index) => mask & 1 << index)));
7207
- } catch {}
7208
- return [...keys];
6673
+ function knowledgeSearchWords(query) {
6674
+ return [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))];
7209
6675
  }
7210
- const visibleSql = (keys, scopeKeyColumn = "scopeKey") => `${scopeKeyColumn} IN (${keys.map(() => "?").join(",")})`;
7211
- function parseJson$3(value) {
7212
- if (typeof value === "string") return JSON.parse(value);
7213
- if (value instanceof Uint8Array) return JSON.parse(new TextDecoder().decode(value));
7214
- if (value instanceof ArrayBuffer) return JSON.parse(new TextDecoder().decode(value));
7215
- return value;
7216
- }
7217
- function toDate(value) {
7218
- return new Date(String(value));
7219
- }
7220
- function optionalDate(value) {
7221
- return value == null ? void 0 : toDate(value);
6676
+ /**
6677
+ * Why `key` can't be a Knowledge page key, or undefined when it can. Keys are one path segment:
6678
+ * non-empty, with no `/` (path separator), `#` (scope/path separator) or `%` (escape character).
6679
+ */
6680
+ function knowledgePageKeyProblem(key) {
6681
+ if (!key) return "Knowledge page key must not be empty";
6682
+ if (/[/#%]/.test(key)) return `Knowledge page key "${key}" must not contain "/", "#" or "%"`;
7222
6683
  }
7223
- function canonicalName(name) {
7224
- return name.trim().toLocaleLowerCase();
6684
+ // src/storage/domains/knowledge/pages.ts
6685
+ const loadPagesCore = createKnowledgePagesCoreLoader(coreFeatures, () => import("@mastra/core/storage"));
6686
+ const assertKnowledgePageDescriptionWithinBound = async (description) => (await loadPagesCore()).assertKnowledgePageDescriptionWithinBound(description);
6687
+ const assertKnowledgeNoteTextWithinBound = async (text) => (await loadPagesCore()).assertKnowledgeNoteTextWithinBound(text);
6688
+ const KNOWLEDGE_PAGE_TABLES = {
6689
+ pages: "mastra_knowledge_pages",
6690
+ notes: "mastra_knowledge_notes",
6691
+ stamps: "mastra_knowledge_note_stamps",
6692
+ mentions: "mastra_knowledge_mentions",
6693
+ pins: "mastra_knowledge_pins",
6694
+ pinAudiences: "mastra_knowledge_pin_audiences",
6695
+ activity: "mastra_knowledge_activity"
6696
+ };
6697
+ const T = KNOWLEDGE_PAGE_TABLES;
6698
+ /** DDL for the schema-4 page tables, in creation order. Every statement is idempotent. */
6699
+ const KNOWLEDGE_PAGE_DDL = [
6700
+ `CREATE TABLE IF NOT EXISTS "mastra_knowledge_access_state" (
6701
+ id TEXT PRIMARY KEY,
6702
+ schemaVersion INTEGER NOT NULL
6703
+ )`,
6704
+ `CREATE TABLE IF NOT EXISTS "${T.pages}" (
6705
+ id TEXT PRIMARY KEY,
6706
+ scopeId TEXT NOT NULL,
6707
+ isScope INTEGER NOT NULL,
6708
+ address TEXT,
6709
+ declaration TEXT,
6710
+ key TEXT,
6711
+ parentId TEXT,
6712
+ position TEXT NOT NULL,
6713
+ path TEXT NOT NULL,
6714
+ depth INTEGER NOT NULL,
6715
+ name TEXT NOT NULL,
6716
+ canonicalName TEXT NOT NULL,
6717
+ description TEXT,
6718
+ body TEXT,
6719
+ version INTEGER NOT NULL,
6720
+ mergedInto TEXT,
6721
+ createdBy TEXT NOT NULL,
6722
+ updatedBy TEXT NOT NULL,
6723
+ createdAt TEXT NOT NULL,
6724
+ updatedAt TEXT NOT NULL,
6725
+ deletedAt TEXT,
6726
+ deletedBy TEXT
6727
+ )`,
6728
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_kpages_address ON "${T.pages}" (address) WHERE isScope = 1`,
6729
+ `DROP INDEX IF EXISTS idx_kpages_key`,
6730
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_kpages_parent_key ON "${T.pages}" (parentId, key) WHERE key IS NOT NULL AND deletedAt IS NULL`,
6731
+ `CREATE INDEX IF NOT EXISTS idx_kpages_scope ON "${T.pages}" (scopeId)`,
6732
+ `CREATE INDEX IF NOT EXISTS idx_kpages_parent ON "${T.pages}" (parentId, position, id)`,
6733
+ `CREATE INDEX IF NOT EXISTS idx_kpages_path ON "${T.pages}" (path)`,
6734
+ `CREATE INDEX IF NOT EXISTS idx_kpages_declaration_parent ON "${T.pages}" (declaration, parentId) WHERE isScope = 1`,
6735
+ `CREATE INDEX IF NOT EXISTS idx_kpages_canonical ON "${T.pages}" (canonicalName)`,
6736
+ `CREATE TABLE IF NOT EXISTS "${T.notes}" (
6737
+ id TEXT PRIMARY KEY,
6738
+ pageId TEXT NOT NULL,
6739
+ text TEXT NOT NULL,
6740
+ "when" TEXT,
6741
+ provenance TEXT NOT NULL,
6742
+ version INTEGER NOT NULL,
6743
+ createdAt TEXT NOT NULL,
6744
+ updatedAt TEXT NOT NULL,
6745
+ deletedAt TEXT,
6746
+ deletedBy TEXT
6747
+ )`,
6748
+ `CREATE INDEX IF NOT EXISTS idx_knotes_page ON "${T.notes}" (pageId, createdAt, id)`,
6749
+ `CREATE TABLE IF NOT EXISTS "${T.stamps}" (
6750
+ noteId TEXT NOT NULL,
6751
+ scopeId TEXT NOT NULL,
6752
+ PRIMARY KEY (noteId, scopeId)
6753
+ )`,
6754
+ `CREATE INDEX IF NOT EXISTS idx_kstamps_scope ON "${T.stamps}" (scopeId)`,
6755
+ `CREATE TABLE IF NOT EXISTS "${T.mentions}" (
6756
+ noteId TEXT NOT NULL,
6757
+ pageId TEXT NOT NULL,
6758
+ PRIMARY KEY (noteId, pageId)
6759
+ )`,
6760
+ `CREATE INDEX IF NOT EXISTS idx_kmentions_page ON "${T.mentions}" (pageId)`,
6761
+ `CREATE TABLE IF NOT EXISTS "${T.pins}" (
6762
+ id TEXT PRIMARY KEY,
6763
+ pageId TEXT NOT NULL UNIQUE,
6764
+ audience TEXT NOT NULL,
6765
+ createdBy TEXT NOT NULL,
6766
+ createdAt TEXT NOT NULL,
6767
+ updatedAt TEXT NOT NULL
6768
+ )`,
6769
+ `CREATE TABLE IF NOT EXISTS "${T.pinAudiences}" (
6770
+ pinId TEXT NOT NULL,
6771
+ audience TEXT NOT NULL,
6772
+ PRIMARY KEY (audience, pinId)
6773
+ ) WITHOUT ROWID`,
6774
+ `CREATE INDEX IF NOT EXISTS idx_kpin_audiences_pin ON "${T.pinAudiences}" (pinId)`,
6775
+ `INSERT OR IGNORE INTO "${T.pinAudiences}" (audience, pinId) SELECT j.value, pin.id FROM "${T.pins}" pin, json_each(pin.audience) j`,
6776
+ `CREATE TABLE IF NOT EXISTS "${T.activity}" (
6777
+ id TEXT PRIMARY KEY,
6778
+ action TEXT NOT NULL,
6779
+ scopeId TEXT NOT NULL,
6780
+ pageId TEXT NOT NULL,
6781
+ noteId TEXT,
6782
+ provenance TEXT NOT NULL,
6783
+ createdAt TEXT NOT NULL
6784
+ )`,
6785
+ `CREATE INDEX IF NOT EXISTS idx_kactivity_page ON "${T.activity}" (pageId, id DESC)`
6786
+ ];
6787
+ function str(value) {
6788
+ return value === null || value === void 0 ? void 0 : String(value);
7225
6789
  }
7226
- function escapeLikePattern(value) {
7227
- return value.replaceAll("=", "==").replaceAll("%", "=%").replaceAll("_", "=_");
6790
+ function date(value) {
6791
+ return value === null || value === void 0 ? void 0 : new Date(String(value));
7228
6792
  }
7229
- function nodeReferenceId(node) {
7230
- return typeof node === "string" ? node : node.id;
6793
+ function provenance(raw) {
6794
+ return JSON.parse(String(raw));
7231
6795
  }
7232
- function parseNode(row) {
6796
+ function toPage(row) {
7233
6797
  return {
7234
6798
  id: String(row.id),
7235
- type: "node",
6799
+ scopeId: String(row.scopeId),
6800
+ parentId: str(row.parentId) ?? null,
6801
+ isScope: Number(row.isScope) === 1,
6802
+ ...row.address !== null && row.address !== void 0 ? { address: String(row.address) } : {},
6803
+ ...row.declaration !== null && row.declaration !== void 0 ? { declaration: String(row.declaration) } : {},
6804
+ ...row.key !== null && row.key !== void 0 ? { key: String(row.key) } : {},
6805
+ position: String(row.position),
7236
6806
  name: String(row.name),
7237
- kind: row.kind == null ? "" : String(row.kind),
7238
- content: row.content == null ? void 0 : String(row.content),
7239
- description: row.description == null ? void 0 : String(row.description),
7240
- isScope: row.isScope === true || row.isScope === 1 ? true : void 0,
7241
- scope: parseJson$3(row.scopeJson ?? row.scope),
6807
+ ...row.description !== null && row.description !== void 0 ? { description: String(row.description) } : {},
6808
+ ...row.body !== null && row.body !== void 0 ? { body: String(row.body) } : {},
7242
6809
  version: Number(row.version),
7243
- mergedInto: row.mergedInto == null ? void 0 : String(row.mergedInto),
7244
- createdAt: toDate(row.createdAt),
7245
- updatedAt: toDate(row.updatedAt)
6810
+ ...row.mergedInto !== null && row.mergedInto !== void 0 ? { mergedInto: String(row.mergedInto) } : {},
6811
+ createdBy: provenance(row.createdBy),
6812
+ updatedBy: provenance(row.updatedBy),
6813
+ createdAt: new Date(String(row.createdAt)),
6814
+ updatedAt: new Date(String(row.updatedAt)),
6815
+ ...row.deletedAt ? { deletedAt: new Date(String(row.deletedAt)) } : {},
6816
+ ...row.deletedBy ? { deletedBy: String(row.deletedBy) } : {}
7246
6817
  };
7247
6818
  }
7248
- function parseKnowledge(row) {
6819
+ function toNote(row, stamps, mentions) {
6820
+ const when = date(row.when);
7249
6821
  return {
7250
6822
  id: String(row.id),
7251
- node: String(row.node),
6823
+ pageId: String(row.pageId),
7252
6824
  text: String(row.text),
7253
- scope: parseJson$3(row.scopeJson ?? row.scope),
7254
- sourceThreadId: String(row.sourceThreadId),
7255
- capturedAt: toDate(row.capturedAt),
7256
- when: optionalDate(row.when),
7257
- metadata: (row.metadataJson ?? row.metadata) == null ? void 0 : parseJson$3(row.metadataJson ?? row.metadata),
7258
- deletedAt: optionalDate(row.deletedAt),
7259
- deletedBy: row.deletedBy == null ? void 0 : String(row.deletedBy)
6825
+ ...when ? { when } : {},
6826
+ stampScopeIds: stamps,
6827
+ mentions,
6828
+ provenance: provenance(row.provenance),
6829
+ version: Number(row.version),
6830
+ createdAt: new Date(String(row.createdAt)),
6831
+ updatedAt: new Date(String(row.updatedAt)),
6832
+ ...row.deletedAt ? { deletedAt: new Date(String(row.deletedAt)) } : {},
6833
+ ...row.deletedBy ? { deletedBy: String(row.deletedBy) } : {}
7260
6834
  };
7261
6835
  }
7262
- function parseOutbox(row) {
6836
+ function toPin(row) {
7263
6837
  return {
7264
6838
  id: String(row.id),
7265
- idempotencyKey: String(row.idempotencyKey),
7266
- documentId: String(row.documentId),
7267
- documentType: String(row.documentType),
7268
- operation: String(row.operation),
7269
- scope: parseJson$3(row.scopeJson ?? row.scope),
7270
- status: String(row.status),
7271
- attempts: Number(row.attempts),
7272
- availableAt: toDate(row.availableAt),
7273
- claimedAt: optionalDate(row.claimedAt),
7274
- claimedBy: row.claimedBy == null ? void 0 : String(row.claimedBy),
7275
- createdAt: toDate(row.createdAt),
7276
- completedAt: optionalDate(row.completedAt)
6839
+ pageId: String(row.pageId),
6840
+ audience: JSON.parse(String(row.audience)),
6841
+ createdBy: String(row.createdBy),
6842
+ createdAt: new Date(String(row.createdAt)),
6843
+ updatedAt: new Date(String(row.updatedAt))
7277
6844
  };
7278
6845
  }
7279
- const KNOWLEDGE_CURATION_CURSOR_REMOVED_MESSAGE = "Knowledge curation cursors were removed: observation-time curate is the only Knowledge writer and needs no cursor.";
7280
- const knowledgeV2TableSchemas = /* @__PURE__ */ new Map([
7281
- [TABLE_KNOWLEDGE_NODES, KNOWLEDGE_V2_NODES_SCHEMA],
7282
- [TABLE_KNOWLEDGE_RECORDS, KNOWLEDGE_V2_RECORDS_SCHEMA],
7283
- [TABLE_KNOWLEDGE_MENTIONS, KNOWLEDGE_V2_MENTIONS_SCHEMA],
7284
- [TABLE_KNOWLEDGE_ACTIVITY, KNOWLEDGE_V2_ACTIVITY_SCHEMA],
7285
- [TABLE_KNOWLEDGE_SEMANTIC_OUTBOX, KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA],
7286
- [TABLE_KNOWLEDGE_NODE_SCOPES, KNOWLEDGE_NODE_SCOPES_SCHEMA],
7287
- [TABLE_KNOWLEDGE_RECORD_SCOPES, KNOWLEDGE_RECORD_SCOPES_SCHEMA],
7288
- [TABLE_KNOWLEDGE_SCOPE_GRANTS, KNOWLEDGE_SCOPE_GRANTS_SCHEMA],
7289
- [TABLE_KNOWLEDGE_ACCESS_STATE, KNOWLEDGE_ACCESS_STATE_SCHEMA],
7290
- [TABLE_KNOWLEDGE_SCOPE_ADDRESSES, KNOWLEDGE_SCOPE_ADDRESSES_SCHEMA],
7291
- [TABLE_KNOWLEDGE_NODE_ADDRESSES, KNOWLEDGE_NODE_ADDRESSES_SCHEMA],
7292
- [TABLE_KNOWLEDGE_IMPORT_STATE, KNOWLEDGE_IMPORT_STATE_SCHEMA],
7293
- [TABLE_KNOWLEDGE_IMPORT_RUNS, KNOWLEDGE_IMPORT_RUNS_SCHEMA],
7294
- [TABLE_KNOWLEDGE_PROPOSALS, KNOWLEDGE_PROPOSALS_SCHEMA]
7295
- ]);
7296
- function canonicalizeLibSQLUrl(url) {
7297
- if (url.includes(":memory:")) return /[?&]cache=shared(?:&|$)/.test(url) ? "file::memory:?cache=shared" : void 0;
7298
- if (url.startsWith("file:")) {
7299
- const [path] = url.slice(5).split("?");
7300
- if (url.startsWith("file://")) {
7301
- const parsed = new URL(url);
7302
- const host = parsed.hostname.toLocaleLowerCase();
7303
- const filePath = host && host !== "localhost" ? `//${host}${parsed.pathname}` : parsed.pathname;
7304
- return `file:${resolve(decodeURIComponent(filePath))}`;
7305
- }
7306
- return `file:${resolve(decodeURIComponent(path))}`;
7307
- }
6846
+ function toListedPin(row) {
6847
+ return {
6848
+ ...toPin(row),
6849
+ pageName: String(row.pageName)
6850
+ };
6851
+ }
6852
+ function limitOf(limit, max) {
6853
+ return Math.max(1, Math.min(limit ?? max, max));
6854
+ }
6855
+ function encodeCursor(value) {
6856
+ return Buffer.from(JSON.stringify(value)).toString("base64url");
6857
+ }
6858
+ function decodeCursor(cursor, length) {
6859
+ if (cursor === void 0) return void 0;
7308
6860
  try {
7309
- const parsed = new URL(url);
7310
- const port = parsed.port || (parsed.protocol === "libsql:" || parsed.protocol === "https:" ? "443" : "80");
7311
- return `${parsed.protocol}//${parsed.hostname.toLocaleLowerCase()}:${port}${parsed.pathname}`;
7312
- } catch {
7313
- return url;
7314
- }
6861
+ const parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
6862
+ if (Array.isArray(parsed) && parsed.length === length && parsed.every((item) => typeof item === "string")) return parsed;
6863
+ } catch {}
6864
+ throw new Error("Invalid Knowledge cursor");
7315
6865
  }
7316
- const unidentifiedClientIsolationKey = {};
7317
- function getLibSQLKnowledgeIsolationKey(config, client) {
7318
- if (config.storageIsolationKey !== void 0) return config.storageIsolationKey;
7319
- if (!config.url) return unidentifiedClientIsolationKey;
7320
- const urlKey = canonicalizeLibSQLUrl(config.url);
7321
- return urlKey ? `libsql:${urlKey}` : client ?? config.client ?? config;
6866
+ function escapeLike(value) {
6867
+ return value.replace(/[=%_]/g, (match) => `=${match}`);
7322
6868
  }
7323
- var KnowledgeLibSQL = class extends KnowledgeStorage {
7324
- #client;
7325
- #db;
7326
- constructor(config) {
7327
- const client = resolveClient(config);
7328
- const storageIsolationKey = config.storageIsolationKey ?? getLibSQLKnowledgeIsolationKey(config, client);
7329
- super({ storageIsolationKey });
7330
- this.#client = client;
7331
- this.#db = new LibSQLDB({
7332
- client: this.#client,
7333
- maxRetries: config.maxRetries,
7334
- initialBackoffMs: config.initialBackoffMs
7335
- });
7336
- }
7337
- getCapabilities() {
7338
- return {
7339
- contractVersion: 2,
7340
- schemaVersion: 2,
7341
- supportsV2: true,
7342
- supportsSchemaInspection: true,
7343
- supportsExplicitReset: true
7344
- };
7345
- }
7346
- async inspectSchema() {
7347
- return this.#inspectSchema(this.#client);
7348
- }
7349
- async #inspectSchema(executor) {
7350
- const { inspectKnowledgeSchema } = await loadKnowledgeV2Core();
7351
- try {
7352
- const placeholders = KNOWLEDGE_TABLE_NAMES.map(() => "?").join(",");
7353
- const tableNames = (await executor.execute({
7354
- sql: `SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (${placeholders})`,
7355
- args: [...KNOWLEDGE_TABLE_NAMES]
7356
- })).rows.map((row) => String(row.name));
7357
- if (tableNames.length === 0) return inspectKnowledgeSchema({
7358
- available: true,
7359
- tableNames
7360
- });
7361
- const missingTables = KNOWLEDGE_TABLE_NAMES.filter((table) => !tableNames.includes(table));
7362
- if (missingTables.length > 0) return inspectKnowledgeSchema({
7363
- available: true,
7364
- tableNames,
7365
- reason: `Missing Knowledge v2 tables: ${missingTables.join(", ")}`
7366
- });
7367
- for (const [table, schema] of knowledgeV2TableSchemas) {
7368
- const columns = await executor.execute(`PRAGMA table_info("${table}")`);
7369
- const actual = new Set(columns.rows.map((row) => String(row.name)));
7370
- const missing = Object.keys(schema).filter((column) => !actual.has(column));
7371
- if (missing.length > 0) return inspectKnowledgeSchema({
7372
- available: true,
7373
- tableNames,
7374
- reason: `Knowledge table ${table} is missing v2 columns: ${missing.join(", ")}`
7375
- });
7376
- }
7377
- const accessState = await executor.execute(`SELECT schemaVersion FROM "${TABLE_KNOWLEDGE_ACCESS_STATE}" WHERE id='global'`);
7378
- if (Number(accessState.rows[0]?.schemaVersion) !== 2) return inspectKnowledgeSchema({
7379
- available: true,
7380
- tableNames,
7381
- reason: "Knowledge schema version marker is missing or incompatible"
7382
- });
7383
- return inspectKnowledgeSchema({
7384
- available: true,
7385
- tableNames,
7386
- schemaVersion: 2
7387
- });
7388
- } catch (error) {
7389
- return inspectKnowledgeSchema({
7390
- available: false,
7391
- tableNames: [],
7392
- reason: error instanceof Error ? error.message : String(error)
7393
- });
6869
+ /**
6870
+ * A string above every string that starts with `prefix`, comparing by code point (which is also
6871
+ * UTF-8 byte order, so it matches SQLite's BINARY collation). `column >= prefix AND column < bound`
6872
+ * is an exact, case-sensitive prefix match that an index range scan can serve, where
6873
+ * `substr(column, 1, length(prefix)) = prefix` cannot. When the last code point cannot be raised
6874
+ * (an empty prefix, or one made only of U+10FFFF), the bound is the prefix plus more U+10FFFF than
6875
+ * any stored column can hold.
6876
+ */
6877
+ function prefixUpperBound(prefix) {
6878
+ const points = Array.from(prefix);
6879
+ while (points.length > 0) {
6880
+ const last = points.pop().codePointAt(0);
6881
+ if (last < 1114111) {
6882
+ const next = last === 55295 ? 57344 : last + 1;
6883
+ return points.join("") + String.fromCodePoint(next);
7394
6884
  }
7395
6885
  }
7396
- async init() {
7397
- await this.#transaction((tx) => this.#initializeSchema(tx));
7398
- }
7399
- async #initializeSchema(tx) {
7400
- const { assertKnowledgeSchemaCompatible } = await loadKnowledgeV2Core();
7401
- let inspection = await this.#inspectSchema(tx);
7402
- if (inspection.status === "incompatible-reset-required" && await this.#isPublishedV1Layout(tx)) {
7403
- for (const table of [...RETIRED_KNOWLEDGE_TABLE_NAMES, ...[...KNOWLEDGE_TABLE_NAMES].reverse()]) await tx.execute(`DROP TABLE IF EXISTS "${table}"`);
7404
- inspection = await this.#inspectSchema(tx);
7405
- }
7406
- assertKnowledgeSchemaCompatible(inspection);
7407
- const createTable = (input) => this.#db.createTable({
7408
- ...input,
7409
- executor: tx
7410
- });
7411
- await createTable({
7412
- tableName: TABLE_KNOWLEDGE_NODES,
7413
- schema: KNOWLEDGE_V2_NODES_SCHEMA
7414
- });
7415
- await createTable({
7416
- tableName: TABLE_KNOWLEDGE_RECORDS,
7417
- schema: KNOWLEDGE_V2_RECORDS_SCHEMA
7418
- });
7419
- await createTable({
7420
- tableName: TABLE_KNOWLEDGE_MENTIONS,
7421
- schema: KNOWLEDGE_V2_MENTIONS_SCHEMA,
7422
- compositePrimaryKey: ["recordId", "sourceId"]
7423
- });
7424
- await createTable({
7425
- tableName: TABLE_KNOWLEDGE_NODE_SCOPES,
7426
- schema: KNOWLEDGE_NODE_SCOPES_SCHEMA,
7427
- compositePrimaryKey: ["nodeId", "scopeNodeId"]
7428
- });
7429
- await createTable({
7430
- tableName: TABLE_KNOWLEDGE_RECORD_SCOPES,
7431
- schema: KNOWLEDGE_RECORD_SCOPES_SCHEMA,
7432
- compositePrimaryKey: ["recordId", "scopeNodeId"]
7433
- });
7434
- await createTable({
7435
- tableName: TABLE_KNOWLEDGE_SCOPE_GRANTS,
7436
- schema: KNOWLEDGE_SCOPE_GRANTS_SCHEMA,
7437
- compositePrimaryKey: ["scopeNodeId", "scopeRefId"]
7438
- });
7439
- await createTable({
7440
- tableName: TABLE_KNOWLEDGE_ACCESS_STATE,
7441
- schema: KNOWLEDGE_ACCESS_STATE_SCHEMA
7442
- });
7443
- await createTable({
7444
- tableName: TABLE_KNOWLEDGE_SCOPE_ADDRESSES,
7445
- schema: KNOWLEDGE_SCOPE_ADDRESSES_SCHEMA
7446
- });
7447
- await createTable({
7448
- tableName: TABLE_KNOWLEDGE_NODE_ADDRESSES,
7449
- schema: KNOWLEDGE_NODE_ADDRESSES_SCHEMA,
7450
- compositePrimaryKey: ["source", "address"]
7451
- });
7452
- await createTable({
7453
- tableName: TABLE_KNOWLEDGE_IMPORT_STATE,
7454
- schema: KNOWLEDGE_IMPORT_STATE_SCHEMA,
7455
- compositePrimaryKey: [
7456
- "importerId",
7457
- "binding",
7458
- "key"
7459
- ]
7460
- });
7461
- await createTable({
7462
- tableName: TABLE_KNOWLEDGE_IMPORT_RUNS,
7463
- schema: KNOWLEDGE_IMPORT_RUNS_SCHEMA
7464
- });
7465
- await createTable({
7466
- tableName: TABLE_KNOWLEDGE_PROPOSALS,
7467
- schema: KNOWLEDGE_PROPOSALS_SCHEMA
7468
- });
7469
- await createTable({
7470
- tableName: TABLE_KNOWLEDGE_ACTIVITY,
7471
- schema: KNOWLEDGE_V2_ACTIVITY_SCHEMA
7472
- });
7473
- await createTable({
7474
- tableName: TABLE_KNOWLEDGE_SEMANTIC_OUTBOX,
7475
- schema: KNOWLEDGE_SEMANTIC_OUTBOX_SCHEMA
7476
- });
7477
- for (const statement of [
7478
- `CREATE UNIQUE INDEX IF NOT EXISTS idx_knowledge_nodes_identity ON "${TABLE_KNOWLEDGE_NODES}" (type, scopeKey, canonicalName)`,
7479
- `CREATE INDEX IF NOT EXISTS idx_knowledge_nodes_scope ON "${TABLE_KNOWLEDGE_NODES}" (scopeKey, type)`,
7480
- `CREATE INDEX IF NOT EXISTS idx_knowledge_nodes_name ON "${TABLE_KNOWLEDGE_NODES}" (type, canonicalName)`,
7481
- `CREATE INDEX IF NOT EXISTS idx_knowledge_records_node_latest ON "${TABLE_KNOWLEDGE_RECORDS}" (node, id DESC)`,
7482
- `CREATE INDEX IF NOT EXISTS idx_knowledge_records_thread_latest ON "${TABLE_KNOWLEDGE_RECORDS}" (sourceThreadId, id DESC)`,
7483
- `CREATE INDEX IF NOT EXISTS idx_knowledge_mentions_record ON "${TABLE_KNOWLEDGE_MENTIONS}" (recordId, sourceType, sourceId)`,
7484
- `CREATE INDEX IF NOT EXISTS idx_knowledge_activity_latest ON "${TABLE_KNOWLEDGE_ACTIVITY}" (id DESC)`,
7485
- `CREATE INDEX IF NOT EXISTS idx_knowledge_records_scope ON "${TABLE_KNOWLEDGE_RECORDS}" (scopeKey, id)`,
7486
- `CREATE INDEX IF NOT EXISTS idx_knowledge_activity_scope ON "${TABLE_KNOWLEDGE_ACTIVITY}" (scopeKey, id DESC)`,
7487
- `CREATE UNIQUE INDEX IF NOT EXISTS idx_knowledge_outbox_idempotency ON "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" (idempotencyKey)`,
7488
- `CREATE INDEX IF NOT EXISTS idx_knowledge_outbox_claim ON "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" (status, availableAt, createdAt)`,
7489
- `CREATE INDEX IF NOT EXISTS idx_knowledge_node_scopes_scope ON "${TABLE_KNOWLEDGE_NODE_SCOPES}" (scopeNodeId, nodeId)`,
7490
- `CREATE INDEX IF NOT EXISTS idx_knowledge_record_scopes_scope ON "${TABLE_KNOWLEDGE_RECORD_SCOPES}" (scopeNodeId, recordId)`,
7491
- `CREATE INDEX IF NOT EXISTS idx_knowledge_scope_grants_ref ON "${TABLE_KNOWLEDGE_SCOPE_GRANTS}" (scopeRefId, scopeNodeId)`,
7492
- `CREATE INDEX IF NOT EXISTS idx_knowledge_node_addresses_node ON "${TABLE_KNOWLEDGE_NODE_ADDRESSES}" (nodeId)`,
7493
- `CREATE INDEX IF NOT EXISTS idx_knowledge_import_runs_lookup ON "${TABLE_KNOWLEDGE_IMPORT_RUNS}" (importerId, binding, queuedAt DESC)`,
7494
- `CREATE INDEX IF NOT EXISTS idx_knowledge_activity_import_run ON "${TABLE_KNOWLEDGE_ACTIVITY}" (importRunId, id DESC)`
7495
- ]) await tx.execute(statement);
7496
- await tx.execute({
7497
- sql: `INSERT OR IGNORE INTO "${TABLE_KNOWLEDGE_ACCESS_STATE}" (id, epoch, schemaVersion) VALUES ('global', 0, ?)`,
7498
- args: [2]
7499
- });
7500
- }
7501
- /**
7502
- * True when the only Knowledge objects are the tables and indexes published v1 adapters created,
7503
- * with or without rows. Anything else (v2 tables, unknown tables, views, triggers) needs an
7504
- * explicit reset.
7505
- */
7506
- async #isPublishedV1Layout(executor) {
7507
- const objects = await executor.execute("SELECT type, name FROM sqlite_master WHERE name LIKE 'mastra\\_knowledge\\_%' ESCAPE '\\' OR tbl_name LIKE 'mastra\\_knowledge\\_%' ESCAPE '\\' OR sql LIKE '%mastra\\_knowledge\\_%' ESCAPE '\\'");
7508
- for (const row of objects.rows) {
7509
- const type = String(row.type);
7510
- const name = String(row.name);
7511
- if (type === "table" && PUBLISHED_KNOWLEDGE_V1_TABLE_NAMES.has(name)) continue;
7512
- const knownIndex = PUBLISHED_KNOWLEDGE_V1_INDEX_NAMES.has(name) || name.startsWith("sqlite_autoindex_");
7513
- if (type !== "index" || !knownIndex) return false;
7514
- }
7515
- return true;
6886
+ return prefix + "􏿿".repeat(4096);
6887
+ }
6888
+ /** `column` starts with `prefix`, as an index-friendly range. */
6889
+ function prefixRange(column, prefix) {
6890
+ return {
6891
+ sql: `(${column} >= ? AND ${column} < ?)`,
6892
+ args: [prefix, prefixUpperBound(prefix)]
6893
+ };
6894
+ }
6895
+ /**
6896
+ * The readable scope page ids as a subquery. The caller's addresses, prefixes and children go in as
6897
+ * JSON arrays so a large read scope never hits a bind-parameter limit. Each kind is its own index
6898
+ * lookup (address equality, address range for a prefix, `(declaration, parentId)` for children),
6899
+ * unioned, so the cost follows the caller's reach rather than the number of scopes in the store.
6900
+ */
6901
+ function readableScopes(read) {
6902
+ if (read === "all") return {
6903
+ sql: `SELECT id FROM "${T.pages}" WHERE isScope = 1`,
6904
+ args: []
6905
+ };
6906
+ const parts = [];
6907
+ const args = [];
6908
+ if (read.addresses.length > 0) {
6909
+ parts.push(`SELECT id FROM "${T.pages}" WHERE isScope = 1 AND address IN (SELECT value FROM json_each(?))`);
6910
+ args.push(JSON.stringify(read.addresses));
6911
+ }
6912
+ if (read.prefixes.length > 0) {
6913
+ parts.push(`SELECT sp.id FROM json_each(?) j CROSS JOIN "${T.pages}" sp ON sp.isScope = 1 AND sp.address >= json_extract(j.value, '$.lo') AND sp.address < json_extract(j.value, '$.hi') AND +sp.declaration = json_extract(j.value, '$.declaration')`);
6914
+ args.push(JSON.stringify(read.prefixes.map((entry) => ({
6915
+ declaration: entry.declaration,
6916
+ lo: entry.prefix,
6917
+ hi: prefixUpperBound(entry.prefix)
6918
+ }))));
6919
+ }
6920
+ if (read.children.length > 0) {
6921
+ parts.push(`SELECT sp.id FROM json_each(?) j CROSS JOIN "${T.pages}" sp ON sp.isScope = 1 AND sp.declaration = json_extract(j.value, '$.declaration') AND sp.parentId IS json_extract(j.value, '$.parentId')`);
6922
+ args.push(JSON.stringify(read.children));
6923
+ }
6924
+ if (parts.length === 0) return {
6925
+ sql: `SELECT id FROM "${T.pages}" WHERE 0`,
6926
+ args: []
6927
+ };
6928
+ return {
6929
+ sql: parts.join(" UNION "),
6930
+ args
6931
+ };
6932
+ }
6933
+ /** `alias.scopeId` is readable. */
6934
+ function pageReadable(alias, read) {
6935
+ const scopes = readableScopes(read);
6936
+ return {
6937
+ sql: `${alias}.scopeId IN (${scopes.sql})`,
6938
+ args: scopes.args
6939
+ };
6940
+ }
6941
+ /**
6942
+ * Note `alias` is visible: its page's scope is readable, a stamp is readable, and every resolved
6943
+ * mention's page sits in a readable scope.
6944
+ */
6945
+ function noteReadable(alias, read) {
6946
+ const scopes = readableScopes(read);
6947
+ return {
6948
+ sql: `EXISTS (SELECT 1 FROM "${T.pages}" vp WHERE vp.id = ${alias}.pageId AND vp.scopeId IN (${scopes.sql}))
6949
+ AND EXISTS (SELECT 1 FROM "${T.stamps}" vs WHERE vs.noteId = ${alias}.id AND vs.scopeId IN (${scopes.sql}))
6950
+ AND NOT EXISTS (SELECT 1 FROM "${T.mentions}" vm JOIN "${T.pages}" vmp ON vmp.id = vm.pageId WHERE vm.noteId = ${alias}.id AND vmp.scopeId NOT IN (${scopes.sql}))`,
6951
+ args: [
6952
+ ...scopes.args,
6953
+ ...scopes.args,
6954
+ ...scopes.args
6955
+ ]
6956
+ };
6957
+ }
6958
+ function jsonList(values) {
6959
+ return JSON.stringify(values);
6960
+ }
6961
+ var LibSQLKnowledgePages = class {
6962
+ #read;
6963
+ #transaction;
6964
+ constructor(config) {
6965
+ this.#read = config.read;
6966
+ this.#transaction = config.transaction;
7516
6967
  }
7517
- async dangerouslyClearAll() {
6968
+ /** Deletes every row from the page tables (scopes, pages, notes, pins, activity). */
6969
+ async clearAll() {
7518
6970
  await this.#transaction(async (tx) => {
7519
6971
  for (const table of [
7520
- TABLE_KNOWLEDGE_RECORD_SCOPES,
7521
- TABLE_KNOWLEDGE_NODE_SCOPES,
7522
- TABLE_KNOWLEDGE_SCOPE_GRANTS,
7523
- TABLE_KNOWLEDGE_SCOPE_ADDRESSES,
7524
- TABLE_KNOWLEDGE_NODE_ADDRESSES,
7525
- TABLE_KNOWLEDGE_MENTIONS,
7526
- TABLE_KNOWLEDGE_PROPOSALS,
7527
- TABLE_KNOWLEDGE_ACTIVITY,
7528
- TABLE_KNOWLEDGE_IMPORT_STATE,
7529
- TABLE_KNOWLEDGE_IMPORT_RUNS,
7530
- TABLE_KNOWLEDGE_SEMANTIC_OUTBOX,
7531
- TABLE_KNOWLEDGE_RECORDS,
7532
- TABLE_KNOWLEDGE_NODES
7533
- ]) await tx.execute(`DELETE FROM "${table}"`);
7534
- await tx.execute(`UPDATE "${TABLE_KNOWLEDGE_ACCESS_STATE}" SET epoch = 0 WHERE id = 'global'`);
6972
+ T.activity,
6973
+ T.pinAudiences,
6974
+ T.pins,
6975
+ T.mentions,
6976
+ T.stamps,
6977
+ T.notes,
6978
+ T.pages
6979
+ ]) await tx.execute({
6980
+ sql: `DELETE FROM ${table}`,
6981
+ args: []
6982
+ });
7535
6983
  });
7536
6984
  }
7537
- async dangerouslyReset() {
7538
- await withClientWriteLock(this.#client, async () => {
7539
- await this.#client.batch([...RETIRED_KNOWLEDGE_TABLE_NAMES, ...[...KNOWLEDGE_TABLE_NAMES].reverse()].map((table) => ({
7540
- sql: `DROP TABLE IF EXISTS "${table}"`,
7541
- args: []
7542
- })), "write");
6985
+ async #query(executor, sql, args = []) {
6986
+ return (await executor.execute({
6987
+ sql,
6988
+ args
6989
+ })).rows;
6990
+ }
6991
+ async #pageRow(executor, id) {
6992
+ return (await this.#query(executor, `SELECT * FROM "${T.pages}" WHERE id = ?`, [id]))[0];
6993
+ }
6994
+ async #livePage(executor, id) {
6995
+ const row = await this.#pageRow(executor, id);
6996
+ if (!row || row.deletedAt) throw new KnowledgeNotFoundError("page", id);
6997
+ return row;
6998
+ }
6999
+ async #logActivity(tx, action, event, now) {
7000
+ await tx.execute({
7001
+ sql: `INSERT INTO "${T.activity}" (id, action, scopeId, pageId, noteId, provenance, createdAt) VALUES (?, ?, ?, ?, ?, ?, ?)`,
7002
+ args: [
7003
+ createKnowledgeUlid(),
7004
+ action,
7005
+ event.scopeId,
7006
+ event.pageId,
7007
+ event.noteId ?? null,
7008
+ JSON.stringify(event.provenance),
7009
+ now
7010
+ ]
7543
7011
  });
7544
- await this.init();
7545
7012
  }
7546
- async reconcileStructure(plan) {
7547
- return withReconcileLock(this.getStorageIsolationKey(), () => this.#transaction(async (tx) => {
7548
- await tx.execute(`UPDATE "${TABLE_KNOWLEDGE_ACCESS_STATE}" SET epoch=epoch WHERE id='global'`);
7549
- const scopes = {};
7550
- const createdScopeIds = [];
7551
- const createdAddresses = /* @__PURE__ */ new Set();
7552
- const retrofit = plan.retrofit ?? true;
7553
- let structureChanged = false;
7554
- const deletedScopeAddresses = /* @__PURE__ */ new Set();
7555
- const resolveAddress = async (address) => {
7556
- if (scopes[address]) return scopes[address];
7557
- const row = (await tx.execute({
7558
- 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=?`,
7559
- args: [address]
7560
- })).rows[0];
7561
- if (!row) return void 0;
7562
- if (!row.isScope) throw new Error(`Knowledge address ${address} does not reference a scope`);
7563
- if (row.deletedAt) deletedScopeAddresses.add(address);
7564
- scopes[address] = String(row.scopeNodeId);
7565
- return scopes[address];
7566
- };
7567
- for (const scope of plan.scopes) {
7568
- if (await resolveAddress(scope.address)) continue;
7569
- const id = randomUUID();
7570
- const now = (/* @__PURE__ */ new Date()).toISOString();
7013
+ async #lastPosition(tx, parentId, scopesOnly) {
7014
+ const rows = await this.#query(tx, `SELECT position FROM "${T.pages}" WHERE parentId IS ? AND isScope = ? AND deletedAt IS NULL ORDER BY position DESC, id DESC LIMIT 1`, [parentId, scopesOnly ? 1 : 0]);
7015
+ return rows[0] ? String(rows[0].position) : void 0;
7016
+ }
7017
+ async materializeScope(input) {
7018
+ const core = await loadPagesCore();
7019
+ await assertKnowledgePageDescriptionWithinBound(input.description);
7020
+ return this.#transaction(async (tx) => {
7021
+ const now = (/* @__PURE__ */ new Date()).toISOString();
7022
+ const ensureScope = async (spec, parentId) => {
7023
+ await assertKnowledgePageDescriptionWithinBound(spec.description);
7024
+ const existing = (await this.#query(tx, `SELECT * FROM "${T.pages}" WHERE isScope = 1 AND address = ?`, [spec.address]))[0];
7025
+ if (existing) return {
7026
+ row: existing,
7027
+ created: false
7028
+ };
7029
+ if (parentId !== null) await this.#livePage(tx, parentId);
7030
+ const id = createKnowledgeUlid();
7031
+ const position = core.knowledgePositionBetween(await this.#lastPosition(tx, parentId, true));
7032
+ const who = JSON.stringify(input.provenance);
7571
7033
  await tx.execute({
7572
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_NODES}" (id,type,name,canonicalName,kind,description,isScope,metadata,version,createdAt,updatedAt) VALUES (?,'node',?,?,?,?,TRUE,jsonb(?),1,?,?)`,
7034
+ sql: `INSERT INTO "${T.pages}" (id, scopeId, isScope, address, declaration, parentId, position, path, depth, name, canonicalName, description, version, createdBy, updatedBy, createdAt, updatedAt) VALUES (?, ?, 1, ?, ?, ?, ?, ?, 0, ?, ?, ?, 1, ?, ?, ?, ?)`,
7573
7035
  args: [
7574
7036
  id,
7575
- scope.name,
7576
- canonicalName(scope.name),
7577
- scope.kind ?? null,
7578
- scope.description ?? null,
7579
- scope.metadata ? JSON.stringify(scope.metadata) : null,
7037
+ id,
7038
+ spec.address,
7039
+ spec.declaration,
7040
+ parentId,
7041
+ position,
7042
+ `/${id}/`,
7043
+ spec.name,
7044
+ core.canonicalKnowledgeName(spec.name),
7045
+ spec.description ?? null,
7046
+ who,
7047
+ who,
7580
7048
  now,
7581
7049
  now
7582
7050
  ]
7583
7051
  });
7052
+ await this.#logActivity(tx, "scope-created", {
7053
+ scopeId: id,
7054
+ pageId: id,
7055
+ provenance: input.provenance
7056
+ }, now);
7057
+ return {
7058
+ row: await this.#pageRow(tx, id),
7059
+ created: true
7060
+ };
7061
+ };
7062
+ const ensured = await ensureScope(input, input.parentId ?? null);
7063
+ let row = ensured.row;
7064
+ const created = ensured.created;
7065
+ const scopeId = String(row.id);
7066
+ if (!created && input.parentId != null && str(row.parentId) === void 0) {
7067
+ await this.#livePage(tx, input.parentId);
7068
+ if (input.parentId === scopeId) throw new Error(`Scope ${scopeId} cannot be its own parent`);
7069
+ let ancestor = input.parentId;
7070
+ while (ancestor) {
7071
+ const up = await this.#pageRow(tx, ancestor);
7072
+ if (String(up.id) === scopeId) throw new Error(`Scope ${scopeId} cannot be linked under its own descendant`);
7073
+ ancestor = str(up.parentId);
7074
+ }
7584
7075
  await tx.execute({
7585
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_SCOPE_ADDRESSES}" (address,scopeNodeId) VALUES (?,?)`,
7586
- args: [scope.address, id]
7076
+ sql: `UPDATE "${T.pages}" SET parentId = ?, position = ?, version = version + 1, updatedAt = ? WHERE id = ? AND parentId IS NULL`,
7077
+ args: [
7078
+ input.parentId,
7079
+ core.knowledgePositionBetween(await this.#lastPosition(tx, input.parentId, true)),
7080
+ now,
7081
+ scopeId
7082
+ ]
7587
7083
  });
7588
- scopes[scope.address] = id;
7589
- createdAddresses.add(scope.address);
7590
- createdScopeIds.push(id);
7591
- structureChanged = true;
7084
+ row = await this.#pageRow(tx, scopeId);
7592
7085
  }
7593
- for (const scope of plan.scopes) {
7594
- if (!createdAddresses.has(scope.address) && (!retrofit || deletedScopeAddresses.has(scope.address))) continue;
7595
- const scopeNodeId = scopes[scope.address];
7596
- for (const parentAddress of scope.parentAddresses ?? []) {
7597
- const parentId = await resolveAddress(parentAddress);
7598
- if (!parentId || deletedScopeAddresses.has(parentAddress)) {
7599
- const deletedParentId = scopes[parentAddress];
7600
- if ((deletedParentId ? await tx.execute({
7601
- sql: `SELECT 1 FROM "mastra_knowledge_node_scopes" WHERE nodeId=? AND scopeNodeId=?`,
7602
- args: [scopeNodeId, deletedParentId]
7603
- }) : void 0)?.rows.length) continue;
7604
- throw new Error(`Knowledge parent scope does not exist: ${parentAddress}`);
7605
- }
7606
- if ((await tx.execute({
7607
- sql: `SELECT 1 FROM "mastra_knowledge_node_scopes" WHERE nodeId=? AND scopeNodeId=?`,
7608
- args: [scopeNodeId, parentId]
7609
- })).rows.length) continue;
7610
- if ((await tx.execute({
7611
- 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`,
7612
- args: [
7613
- parentId,
7614
- canonicalName(scope.name),
7615
- scopeNodeId
7616
- ]
7617
- })).rows.length) throw new Error(`Knowledge scope name ${scope.name} already exists under ${parentAddress}`);
7618
- const inserted = await tx.execute({
7619
- sql: `INSERT OR IGNORE INTO "${TABLE_KNOWLEDGE_NODE_SCOPES}" (nodeId,scopeNodeId,addedAt) VALUES (?,?,?)`,
7620
- args: [
7621
- scopeNodeId,
7622
- parentId,
7623
- (/* @__PURE__ */ new Date()).toISOString()
7624
- ]
7625
- });
7626
- structureChanged ||= inserted.rowsAffected > 0;
7627
- }
7628
- for (const grant of scope.grants ?? []) {
7629
- const scopeRefId = await resolveAddress(grant.scopeRefAddress);
7630
- if (!scopeRefId || deletedScopeAddresses.has(grant.scopeRefAddress)) {
7631
- const deletedScopeRefId = scopes[grant.scopeRefAddress];
7632
- if ((deletedScopeRefId ? await tx.execute({
7633
- sql: `SELECT 1 FROM "mastra_knowledge_scope_grants" WHERE scopeNodeId=? AND scopeRefId=?`,
7634
- args: [scopeNodeId, deletedScopeRefId]
7635
- }) : void 0)?.rows.length) continue;
7636
- throw new Error(`Knowledge grant scope does not exist: ${grant.scopeRefAddress}`);
7637
- }
7638
- const inserted = await tx.execute({
7639
- sql: `INSERT OR IGNORE INTO "${TABLE_KNOWLEDGE_SCOPE_GRANTS}" (scopeNodeId,scopeRefId,role,canSuggest) VALUES (?,?,?,?)`,
7640
- args: [
7641
- scopeNodeId,
7642
- scopeRefId,
7643
- grant.role,
7644
- grant.canSuggest ?? null
7645
- ]
7646
- });
7647
- structureChanged ||= inserted.rowsAffected > 0;
7086
+ let parentConflict;
7087
+ if (!created && input.parentId !== void 0 && (str(row.parentId) ?? null) !== input.parentId) parentConflict = {
7088
+ existingParentId: str(row.parentId) ?? null,
7089
+ requestedParentId: input.parentId
7090
+ };
7091
+ for (const child of input.children ?? []) await ensureScope(child, scopeId);
7092
+ const ensureTemplates = async (templates, parentId) => {
7093
+ for (const template of templates) {
7094
+ const problem = knowledgePageKeyProblem(template.key);
7095
+ if (problem) throw new Error(problem);
7096
+ const existing = (await this.#query(tx, `SELECT id FROM "${T.pages}" WHERE parentId = ? AND isScope = 0 AND key = ? AND deletedAt IS NULL`, [parentId, template.key]))[0];
7097
+ const id = existing ? String(existing.id) : (await this.#insertPage(tx, {
7098
+ parentId,
7099
+ key: template.key,
7100
+ name: template.name,
7101
+ description: template.description,
7102
+ provenance: input.provenance
7103
+ })).id;
7104
+ if (template.pages?.length) await ensureTemplates(template.pages, id);
7648
7105
  }
7649
- }
7650
- if (structureChanged) await tx.execute(`UPDATE "${TABLE_KNOWLEDGE_ACCESS_STATE}" SET epoch=epoch+1 WHERE id='global'`);
7651
- const state = await tx.execute(`SELECT epoch FROM "${TABLE_KNOWLEDGE_ACCESS_STATE}" WHERE id='global'`);
7106
+ };
7107
+ await ensureTemplates(input.pages ?? [], scopeId);
7652
7108
  return {
7653
- scopes,
7654
- createdScopeIds,
7655
- deletedScopeAddresses: [...deletedScopeAddresses],
7656
- changed: structureChanged,
7657
- accessEpoch: Number(state.rows[0]?.epoch ?? 0)
7109
+ scope: toPage(await this.#pageRow(tx, scopeId)),
7110
+ created,
7111
+ ...parentConflict ? { parentConflict } : {}
7658
7112
  };
7113
+ });
7114
+ }
7115
+ async listScopeDeclarations() {
7116
+ return (await this.#query(this.#read, `SELECT declaration, COUNT(*) AS scopes FROM "${T.pages}" WHERE isScope = 1 AND declaration IS NOT NULL GROUP BY declaration ORDER BY declaration`)).map((row) => ({
7117
+ declaration: String(row.declaration),
7118
+ scopes: Number(row.scopes)
7659
7119
  }));
7660
7120
  }
7661
- async listScopeNodes(input = {}) {
7662
- const { limit, after } = parseListKnowledgeScopeNodesInput(input);
7663
- if (input.addresses?.length === 0 || input.ids?.length === 0) return {
7664
- scopes: [],
7665
- nextCursor: null
7121
+ async renameScopeDeclaration(input) {
7122
+ return this.#transaction(async (tx) => {
7123
+ const within = prefixRange("declaration", `${input.from}/`);
7124
+ const affected = (await this.#query(tx, `SELECT id, address, declaration FROM "${T.pages}" WHERE isScope = 1 AND (declaration = ? OR ${within.sql})`, [input.from, ...within.args])).map((row) => ({
7125
+ id: String(row.id),
7126
+ address: String(row.address),
7127
+ from: String(row.declaration)
7128
+ })).filter((row) => row.from === input.from || row.from.startsWith(`${input.from}/`)).map((row) => ({
7129
+ ...row,
7130
+ to: input.to + row.from.slice(input.from.length)
7131
+ }));
7132
+ input.check(affected.map(({ address, from, to }) => ({
7133
+ address,
7134
+ from,
7135
+ to
7136
+ })));
7137
+ for (const row of affected) await tx.execute({
7138
+ sql: `UPDATE "${T.pages}" SET declaration = ? WHERE id = ?`,
7139
+ args: [row.to, row.id]
7140
+ });
7141
+ return affected.length;
7142
+ });
7143
+ }
7144
+ async getScopesByAddress(addresses) {
7145
+ if (addresses.length === 0) return [];
7146
+ return (await this.#query(this.#read, `SELECT * FROM "${T.pages}" WHERE isScope = 1 AND address IN (SELECT value FROM json_each(?))`, [jsonList(addresses)])).map(toPage);
7147
+ }
7148
+ async listChildScopes(input) {
7149
+ const core = await loadPagesCore();
7150
+ const limit = limitOf(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
7151
+ const cursor = decodeCursor(input.cursor, 2);
7152
+ const args = [input.parentId];
7153
+ let after = "";
7154
+ if (cursor) {
7155
+ after = ` AND (position > ? OR (position = ? AND id > ?))`;
7156
+ args.push(cursor[0], cursor[0], cursor[1]);
7157
+ }
7158
+ args.push(limit + 1);
7159
+ const rows = await this.#query(this.#read, `SELECT * FROM "${T.pages}" WHERE isScope = 1 AND parentId IS ?${after} ORDER BY position, id LIMIT ?`, args);
7160
+ return this.#pageOutput(rows, limit, (row) => [String(row.position), String(row.id)]);
7161
+ }
7162
+ #pageOutput(rows, limit, cursorOf) {
7163
+ const page = rows.slice(0, limit);
7164
+ return {
7165
+ pages: page.map(toPage),
7166
+ ...rows.length > limit ? { nextCursor: encodeCursor(cursorOf(page[page.length - 1])) } : {}
7666
7167
  };
7667
- const args = [];
7668
- const where = [`n.isScope`, `n.deletedAt IS NULL`];
7669
- let within = "";
7670
- if (input.withinAddress !== void 0) {
7671
- 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) `;
7672
- args.push(input.withinAddress);
7673
- where.push("n.id IN (SELECT id FROM within_scope)");
7168
+ }
7169
+ async getPage(input) {
7170
+ const readable = pageReadable("p", input.read);
7171
+ const rows = await this.#query(this.#read, `SELECT p.* FROM "${T.pages}" p WHERE p.id = ? AND ${readable.sql}`, [input.id, ...readable.args]);
7172
+ return rows[0] ? toPage(rows[0]) : null;
7173
+ }
7174
+ async getPages(input) {
7175
+ const ids = [...new Set(input.ids)];
7176
+ if (ids.length === 0) return [];
7177
+ const readable = pageReadable("p", input.read);
7178
+ return (await this.#query(this.#read, `SELECT p.* FROM "${T.pages}" p WHERE p.deletedAt IS NULL AND p.id IN (SELECT value FROM json_each(?)) AND ${readable.sql}`, [jsonList(ids), ...readable.args])).map(toPage);
7179
+ }
7180
+ async getPageByPath(input) {
7181
+ const readable = pageReadable("p", input.read);
7182
+ let parentId = input.scopeId;
7183
+ let row;
7184
+ for (const key of input.path) {
7185
+ row = (await this.#query(this.#read, `SELECT p.* FROM "${T.pages}" p WHERE p.parentId = ? AND p.isScope = 0 AND p.key = ? AND p.deletedAt IS NULL AND ${readable.sql}`, [
7186
+ parentId,
7187
+ key,
7188
+ ...readable.args
7189
+ ]))[0];
7190
+ if (!row) return null;
7191
+ parentId = String(row.id);
7192
+ }
7193
+ return row ? toPage(row) : null;
7194
+ }
7195
+ async findPagesByName(input) {
7196
+ const core = await loadPagesCore();
7197
+ const readable = pageReadable("p", input.read);
7198
+ const args = [core.canonicalKnowledgeName(input.name), ...readable.args];
7199
+ let scope = "";
7200
+ if (input.scopeId !== void 0) {
7201
+ scope = ` AND p.scopeId = ?`;
7202
+ args.push(input.scopeId);
7203
+ }
7204
+ args.push(limitOf(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT));
7205
+ return (await this.#query(this.#read, `SELECT p.* FROM "${T.pages}" p WHERE p.canonicalName = ? AND p.deletedAt IS NULL AND ${readable.sql}${scope} ORDER BY p.createdAt DESC, p.id DESC LIMIT ?`, args)).map(toPage);
7206
+ }
7207
+ async listChildPages(input) {
7208
+ const core = await loadPagesCore();
7209
+ const limit = limitOf(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
7210
+ const cursor = decodeCursor(input.cursor, 2);
7211
+ const readable = pageReadable("p", input.read);
7212
+ const args = [input.parentId, ...readable.args];
7213
+ let after = "";
7214
+ if (cursor) {
7215
+ after = ` AND (p.position > ? OR (p.position = ? AND p.id > ?))`;
7216
+ args.push(cursor[0], cursor[0], cursor[1]);
7674
7217
  }
7675
- if (input.addresses) {
7676
- where.push(`a.address IN (${input.addresses.map(() => "?").join(",")})`);
7677
- args.push(...input.addresses);
7218
+ args.push(limit + 1);
7219
+ const rows = await this.#query(this.#read, `SELECT p.* FROM "${T.pages}" p WHERE p.parentId = ? AND p.isScope = 0 AND p.deletedAt IS NULL AND ${readable.sql}${after} ORDER BY p.position, p.id LIMIT ?`, args);
7220
+ return this.#pageOutput(rows, limit, (row) => [String(row.position), String(row.id)]);
7221
+ }
7222
+ async listPages(input) {
7223
+ const core = await loadPagesCore();
7224
+ const limit = limitOf(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
7225
+ const cursor = decodeCursor(input.cursor, 2);
7226
+ const readable = pageReadable("p", input.read);
7227
+ const args = [...readable.args];
7228
+ let filters = "";
7229
+ if (input.scopeId !== void 0) {
7230
+ filters += ` AND p.scopeId = ?`;
7231
+ args.push(input.scopeId);
7678
7232
  }
7679
- if (input.ids) {
7680
- where.push(`n.id IN (${input.ids.map(() => "?").join(",")})`);
7681
- args.push(...input.ids);
7233
+ if (input.namePrefix) {
7234
+ const prefix = core.canonicalKnowledgeName(input.namePrefix);
7235
+ filters += ` AND substr(p.canonicalName, 1, length(?)) = ?`;
7236
+ args.push(prefix, prefix);
7682
7237
  }
7683
- if (after) {
7684
- where.push("(n.name > ? OR (n.name = ? AND n.id > ?))");
7685
- args.push(after.name, after.name, after.id);
7238
+ if (cursor) {
7239
+ filters += ` AND (p.name > ? OR (p.name = ? AND p.id > ?))`;
7240
+ args.push(cursor[0], cursor[0], cursor[1]);
7686
7241
  }
7687
7242
  args.push(limit + 1);
7688
- const rows = (await this.#client.execute({
7689
- 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, n.id LIMIT ?`,
7690
- args
7691
- })).rows;
7692
- if (rows.length === 0) return {
7693
- scopes: [],
7694
- nextCursor: null
7695
- };
7696
- const parents = await this.#client.execute({
7697
- sql: `SELECT ns.nodeId,ns.scopeNodeId FROM "${TABLE_KNOWLEDGE_NODE_SCOPES}" ns WHERE ns.nodeId IN (${rows.map(() => "?").join(",")}) ORDER BY ns.scopeNodeId`,
7698
- args: rows.map((row) => String(row.id))
7243
+ const rows = await this.#query(this.#read, `SELECT p.* FROM "${T.pages}" p WHERE p.isScope = 0 AND p.deletedAt IS NULL AND ${readable.sql}${filters} ORDER BY p.name, p.id LIMIT ?`, args);
7244
+ return this.#pageOutput(rows, limit, (row) => [String(row.name), String(row.id)]);
7245
+ }
7246
+ async #insertPage(tx, input) {
7247
+ const core = await loadPagesCore();
7248
+ await assertKnowledgePageDescriptionWithinBound(input.description);
7249
+ const parent = await this.#livePage(tx, input.parentId);
7250
+ const isScopeParent = Number(parent.isScope) === 1;
7251
+ const scopeId = isScopeParent ? String(parent.id) : String(parent.scopeId);
7252
+ const depth = isScopeParent ? 1 : Number(parent.depth) + 1;
7253
+ if (depth > core.MAX_KNOWLEDGE_PAGE_DEPTH) throw new core.KnowledgePageDepthError(input.parentId);
7254
+ const id = input.id ?? createKnowledgeUlid();
7255
+ if (await this.#pageRow(tx, id)) throw new KnowledgeConflictError(id);
7256
+ if (input.key !== void 0) {
7257
+ const problem = knowledgePageKeyProblem(input.key);
7258
+ if (problem) throw new Error(problem);
7259
+ if ((await this.#query(tx, `SELECT id FROM "${T.pages}" WHERE parentId = ? AND isScope = 0 AND key = ? AND deletedAt IS NULL`, [String(parent.id), input.key])).length > 0) throw new core.KnowledgePageKeyConflictError(input.key, String(parent.id));
7260
+ }
7261
+ const position = input.position ?? core.knowledgePositionBetween(await this.#lastPosition(tx, String(parent.id), false));
7262
+ const now = (/* @__PURE__ */ new Date()).toISOString();
7263
+ const who = JSON.stringify(input.provenance);
7264
+ await tx.execute({
7265
+ sql: `INSERT INTO "${T.pages}" (id, scopeId, isScope, key, parentId, position, path, depth, name, canonicalName, description, body, version, createdBy, updatedBy, createdAt, updatedAt) VALUES (?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?)`,
7266
+ args: [
7267
+ id,
7268
+ scopeId,
7269
+ input.key ?? null,
7270
+ String(parent.id),
7271
+ position,
7272
+ `${String(parent.path)}${id}/`,
7273
+ depth,
7274
+ input.name,
7275
+ core.canonicalKnowledgeName(input.name),
7276
+ input.description || null,
7277
+ input.body ?? null,
7278
+ who,
7279
+ who,
7280
+ now,
7281
+ now
7282
+ ]
7699
7283
  });
7700
- const parentsByScopeId = /* @__PURE__ */ new Map();
7701
- for (const row of parents.rows) {
7702
- const scopeId = String(row.nodeId);
7703
- const parentId = String(row.scopeNodeId);
7704
- const existing = parentsByScopeId.get(scopeId);
7705
- if (existing) existing.push(parentId);
7706
- else parentsByScopeId.set(scopeId, [parentId]);
7707
- }
7708
- return pageKnowledgeScopeNodes(rows.map((row) => ({
7709
- id: String(row.id),
7710
- address: String(row.address),
7711
- name: String(row.name),
7712
- ...row.kind == null ? {} : { kind: String(row.kind) },
7713
- ...row.description == null ? {} : { description: String(row.description) },
7714
- parentIds: parentsByScopeId.get(String(row.id)) ?? []
7715
- })), limit, input);
7716
- }
7717
- async listScopeMembers(input) {
7718
- const { limit, after } = parseListKnowledgeScopeMembersInput(input);
7719
- const args = [input.scopeNodeId];
7720
- let keyset = "";
7721
- if (after) {
7722
- const updatedAt = after.updatedAt.toISOString();
7723
- keyset = ` AND (n.updatedAt < ? OR (n.updatedAt = ? AND (n.name > ? OR (n.name = ? AND n.id > ?))))`;
7724
- args.push(updatedAt, updatedAt, after.name, after.name, after.id);
7725
- }
7726
- args.push(limit + 1);
7727
- return pageKnowledgeScopeMembers((await this.#client.execute({
7728
- sql: `SELECT *, json(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 ?`,
7729
- args
7730
- })).rows.map(parseNode), limit, input);
7731
- }
7732
- async createNode(input) {
7733
- await assertKnowledgeDescriptionWithinBoundCompat(input.description);
7734
- const scope = canonicalizeKnowledgeScope(input.scope);
7284
+ await this.#logActivity(tx, "page-created", {
7285
+ scopeId,
7286
+ pageId: id,
7287
+ provenance: input.provenance
7288
+ }, now);
7289
+ return toPage(await this.#pageRow(tx, id));
7290
+ }
7291
+ async createPage(input) {
7292
+ await assertKnowledgePageDescriptionWithinBound(input.description);
7293
+ return this.#transaction((tx) => this.#insertPage(tx, input));
7294
+ }
7295
+ async updatePage(input) {
7296
+ const core = await loadPagesCore();
7297
+ await assertKnowledgePageDescriptionWithinBound(input.description);
7735
7298
  return this.#transaction(async (tx) => {
7736
- const existing = await this.#getNodeByName(tx, input.name, scope);
7737
- if (existing) {
7738
- const terminal = await this.#resolveTerminalNode(tx, existing.id);
7739
- if (!isKnowledgeScopeVisible(terminal.scope, scope)) throw new Error(`Merged knowledge node is not visible from scope: ${input.name}`);
7740
- await this.#placeNodeInScopes(tx, terminal.id, input.scopeAddresses, /* @__PURE__ */ new Date());
7741
- return terminal;
7742
- }
7743
- const now = /* @__PURE__ */ new Date();
7744
- const node = {
7745
- id: input.id ?? crypto.randomUUID(),
7746
- type: "node",
7747
- name: input.name.trim(),
7748
- kind: input.kind,
7749
- content: input.content,
7750
- description: input.description,
7751
- scope,
7752
- version: 1,
7753
- createdAt: now,
7754
- updatedAt: now
7755
- };
7299
+ const row = await this.#livePage(tx, input.id);
7300
+ if (Number(row.version) !== input.expectedVersion) throw new KnowledgeConflictError(input.id);
7301
+ const now = (/* @__PURE__ */ new Date()).toISOString();
7302
+ const name = input.name ?? String(row.name);
7303
+ const description = input.description === void 0 ? row.description ?? null : input.description || null;
7304
+ const body = input.body === void 0 ? row.body ?? null : input.body;
7756
7305
  await tx.execute({
7757
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_NODES}" (id,type,name,canonicalName,kind,content,description,isScope,scope,scopeKey,version,mergedInto,createdAt,updatedAt) VALUES (?,?,?,?,?,?,?,FALSE,jsonb(?),?,?,NULL,?,?)`,
7306
+ sql: `UPDATE "${T.pages}" SET name = ?, canonicalName = ?, description = ?, body = ?, version = version + 1, updatedBy = ?, updatedAt = ? WHERE id = ?`,
7758
7307
  args: [
7759
- node.id,
7760
- "node",
7761
- node.name,
7762
- canonicalName(node.name),
7763
- node.kind,
7764
- node.content ?? null,
7765
- node.description ?? null,
7766
- JSON.stringify(scope),
7767
- knowledgeScopeKey(scope),
7768
- node.version,
7769
- now.toISOString(),
7770
- now.toISOString()
7308
+ name,
7309
+ core.canonicalKnowledgeName(name),
7310
+ description,
7311
+ body,
7312
+ JSON.stringify(input.provenance),
7313
+ now,
7314
+ input.id
7771
7315
  ]
7772
7316
  });
7773
- await this.#replaceNodeScopes(tx, node.id, scope, now);
7774
- await this.#placeNodeInScopes(tx, node.id, input.scopeAddresses, now);
7775
- await this.#replaceMentions(tx, "node", node.id, node.content ?? "", input.resolutionScope ?? scope, scope);
7776
- await this.#activity(tx, "node-created", "node", node.id, scope);
7777
- await this.#outbox(tx, "node", node.id, "upsert", node.version, scope);
7778
- return node;
7317
+ await this.#logActivity(tx, "page-updated", {
7318
+ scopeId: String(row.scopeId),
7319
+ pageId: input.id,
7320
+ provenance: input.provenance
7321
+ }, now);
7322
+ return toPage(await this.#pageRow(tx, input.id));
7779
7323
  });
7780
7324
  }
7781
- async getNode(id) {
7782
- return this.#getNode(this.#client, id);
7783
- }
7784
- async getNodeByName(input) {
7785
- return this.#getNodeByName(this.#client, input.name, canonicalizeKnowledgeScope(input.scope));
7786
- }
7787
- async resolveNode(input) {
7788
- return this.#resolveNode(this.#client, input.name, canonicalizeKnowledgeScope(input.scope));
7789
- }
7790
- async listNodes(input) {
7791
- const keys = visibleScopeKeys(canonicalizeKnowledgeScope(input.scope));
7792
- const clauses = [
7793
- `type = 'node'`,
7794
- "mergedInto IS NULL",
7795
- visibleSql(keys)
7796
- ];
7797
- const args = [...keys];
7798
- if (input.namePrefix) {
7799
- clauses.push("canonicalName LIKE ? ESCAPE '='");
7800
- args.push(`${escapeLikePattern(canonicalName(input.namePrefix))}%`);
7801
- }
7802
- if (input.kind) {
7803
- clauses.push("kind = ?");
7804
- args.push(input.kind);
7805
- }
7806
- if (input.hasContent !== void 0) clauses.push(input.hasContent ? "content IS NOT NULL AND content <> ''" : "(content IS NULL OR content = '')");
7807
- if (input.cursor) {
7808
- const cursor = parseKnowledgeNodeCursor(input.cursor, {
7809
- namePrefix: input.namePrefix,
7810
- kind: input.kind,
7811
- hasContent: input.hasContent
7812
- });
7813
- clauses.push("(updatedAt < ? OR (updatedAt = ? AND (name > ? OR (name = ? AND id > ?))))");
7814
- const updatedAt = cursor.updatedAt.toISOString();
7815
- args.push(updatedAt, updatedAt, cursor.name, cursor.name, cursor.id);
7816
- }
7817
- args.push(input.limit ?? 100);
7818
- return (await this.#client.execute({
7819
- sql: `SELECT *, json(scope) AS scopeJson FROM "${TABLE_KNOWLEDGE_NODES}" WHERE ${clauses.join(" AND ")} ORDER BY updatedAt DESC, name ASC, id ASC LIMIT ?`,
7820
- args
7821
- })).rows.map(parseNode);
7325
+ /**
7326
+ * Rehomes `root` (and its subtree) under `parent`: new path prefix, scope and depth in one go.
7327
+ * Throws when the subtree is too large, too deep, or the root's key clashes with a live child of `parent`.
7328
+ */
7329
+ async #rehome(tx, root, parent, options) {
7330
+ const core = await loadPagesCore();
7331
+ const isScopeParent = Number(parent.isScope) === 1;
7332
+ const newScopeId = isScopeParent ? String(parent.id) : String(parent.scopeId);
7333
+ const newDepth = isScopeParent ? 1 : Number(parent.depth) + 1;
7334
+ const oldPath = String(root.path);
7335
+ const within = prefixRange("path", oldPath);
7336
+ const live = (await this.#query(tx, `SELECT id, key, depth, deletedAt FROM "${T.pages}" WHERE ${within.sql}`, within.args)).filter((row) => !row.deletedAt);
7337
+ if (live.length > core.MAX_KNOWLEDGE_MOVE_PAGES) throw new core.KnowledgeMoveTooLargeError(options.countLimitId, live.length);
7338
+ const shift = newDepth - Number(root.depth);
7339
+ if (Math.max(...live.map((row) => Number(row.depth))) + shift > core.MAX_KNOWLEDGE_PAGE_DEPTH) throw new core.KnowledgePageDepthError(String(root.id));
7340
+ if (!root.deletedAt && root.key !== null) {
7341
+ if ((await this.#query(tx, `SELECT id FROM "${T.pages}" WHERE parentId = ? AND isScope = 0 AND key = ? AND deletedAt IS NULL AND id <> ?`, [
7342
+ String(parent.id),
7343
+ String(root.key),
7344
+ String(root.id)
7345
+ ])).length > 0) throw new core.KnowledgePageKeyConflictError(String(root.key), String(parent.id));
7346
+ }
7347
+ const newPath = `${String(parent.path)}${String(root.id)}/`;
7348
+ const position = options.position ?? core.knowledgePositionBetween(await this.#lastPosition(tx, String(parent.id), false));
7349
+ await tx.execute({
7350
+ sql: `UPDATE "${T.pages}" SET path = ? || substr(path, length(?) + 1), depth = depth + ?, scopeId = ? WHERE ${within.sql}`,
7351
+ args: [
7352
+ newPath,
7353
+ oldPath,
7354
+ shift,
7355
+ newScopeId,
7356
+ ...within.args
7357
+ ]
7358
+ });
7359
+ await tx.execute({
7360
+ sql: `UPDATE "${T.pages}" SET parentId = ?, position = ? WHERE id = ?`,
7361
+ args: [
7362
+ String(parent.id),
7363
+ position,
7364
+ String(root.id)
7365
+ ]
7366
+ });
7367
+ return {
7368
+ moved: live.length,
7369
+ scopeId: newScopeId
7370
+ };
7822
7371
  }
7823
- async updateNode(input) {
7824
- await assertKnowledgeDescriptionWithinBoundCompat(input.description);
7372
+ movePage(input) {
7825
7373
  return this.#transaction(async (tx) => {
7826
- const existing = await this.#getNode(tx, input.id);
7827
- if (!existing) throw new KnowledgeNotFoundError("node", input.id);
7828
- if (existing.mergedInto) throw new Error(`Cannot update merged knowledge node: ${input.id}`);
7829
- const scope = canonicalizeKnowledgeScope(input.scope ?? existing.scope);
7830
- const name = (input.name ?? existing.name).trim();
7831
- const content = input.content ?? existing.content;
7832
- const description = input.description ?? existing.description;
7833
- const now = /* @__PURE__ */ new Date();
7834
- if ((await tx.execute({
7835
- 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=?`,
7374
+ const row = await this.#livePage(tx, input.id);
7375
+ if (Number(row.isScope) === 1) throw new Error(`Cannot move ${input.id}: it is a scope page`);
7376
+ if (Number(row.version) !== input.expectedVersion) throw new KnowledgeConflictError(input.id);
7377
+ const parent = await this.#livePage(tx, input.parentId);
7378
+ const path = String(row.path);
7379
+ if (String(parent.id) === input.id || String(parent.path).startsWith(path)) throw new Error(`Cannot move ${input.id} into its own subtree`);
7380
+ const now = (/* @__PURE__ */ new Date()).toISOString();
7381
+ const { scopeId } = await this.#rehome(tx, row, parent, {
7382
+ position: input.position,
7383
+ countLimitId: input.id
7384
+ });
7385
+ await tx.execute({
7386
+ sql: `UPDATE "${T.pages}" SET version = version + 1, updatedBy = ?, updatedAt = ? WHERE id = ?`,
7836
7387
  args: [
7837
- name,
7838
- canonicalName(name),
7839
- input.kind ?? existing.kind,
7840
- content ?? null,
7841
- description ?? null,
7842
- JSON.stringify(scope),
7843
- knowledgeScopeKey(scope),
7844
- now.toISOString(),
7845
- input.id,
7846
- input.version
7388
+ JSON.stringify(input.provenance),
7389
+ now,
7390
+ input.id
7847
7391
  ]
7848
- })).rowsAffected === 0) throw new KnowledgeConflictError(input.id);
7849
- if (knowledgeScopeKey(existing.scope) !== knowledgeScopeKey(scope)) await this.#swapIdentityScopes(tx, input.id, existing.scope, scope, now);
7850
- 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);
7851
- await this.#activity(tx, "node-updated", "node", input.id, scope);
7852
- if (knowledgeScopeKey(existing.scope) !== knowledgeScopeKey(scope)) {
7853
- await this.#outbox(tx, "node", input.id, "delete", createKnowledgeUlid(), existing.scope);
7854
- const knowledge = await tx.execute({
7855
- sql: `SELECT id,json(scope) AS scopeJson,deletedAt FROM "${TABLE_KNOWLEDGE_RECORDS}" WHERE node=?`,
7856
- args: [input.id]
7857
- });
7858
- for (const row of knowledge.rows) {
7859
- const recordScope = parseJson$3(row.scopeJson);
7860
- await this.#outbox(tx, "record", String(row.id), "delete", createKnowledgeUlid(), recordScope);
7861
- if (row.deletedAt == null) await this.#outbox(tx, "record", String(row.id), "upsert", createKnowledgeUlid(), recordScope);
7862
- }
7863
- }
7864
- await this.#outbox(tx, "node", input.id, "upsert", input.version + 1, scope);
7865
- return {
7866
- ...existing,
7867
- name,
7868
- kind: input.kind ?? existing.kind,
7869
- content,
7870
- description,
7871
- scope,
7872
- version: input.version + 1,
7873
- updatedAt: now
7874
- };
7392
+ });
7393
+ await this.#logActivity(tx, "page-moved", {
7394
+ scopeId,
7395
+ pageId: input.id,
7396
+ provenance: input.provenance
7397
+ }, now);
7398
+ return toPage(await this.#pageRow(tx, input.id));
7875
7399
  });
7876
7400
  }
7877
- async mergeNodes(input) {
7878
- if (input.sourceId === input.targetId) throw new Error("Cannot merge a knowledge node into itself");
7401
+ async mergePages(input) {
7402
+ const core = await loadPagesCore();
7879
7403
  return this.#transaction(async (tx) => {
7880
- const source = await this.#getNode(tx, input.sourceId);
7881
- if (!source) throw new KnowledgeNotFoundError("node", input.sourceId);
7882
- const target = await this.#resolveTerminalNode(tx, input.targetId);
7883
- if (!target) throw new KnowledgeNotFoundError("node", input.targetId);
7884
- if (target.id === source.id) throw new Error("Cannot create a knowledge merge cycle");
7885
- if (!isKnowledgeScopeVisible(target.scope, source.scope)) throw new Error("Cannot merge a knowledge node into a target that is narrower than its source scope");
7886
- const affected = await tx.execute({
7887
- sql: `SELECT DISTINCT m.sourceType,m.sourceId,json(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=?`,
7888
- args: [source.id]
7889
- });
7890
- const movedKnowledge = await tx.execute({
7891
- sql: `SELECT id,json(scope) AS scopeJson,deletedAt FROM "${TABLE_KNOWLEDGE_RECORDS}" WHERE node=?`,
7892
- args: [source.id]
7893
- });
7894
- if ((await tx.execute({
7895
- sql: `UPDATE "${TABLE_KNOWLEDGE_NODES}" SET mergedInto=?,version=version+1,updatedAt=? WHERE id=? AND type='node' AND version=? AND mergedInto IS NULL`,
7896
- args: [
7897
- target.id,
7898
- (/* @__PURE__ */ new Date()).toISOString(),
7899
- source.id,
7900
- input.sourceVersion
7901
- ]
7902
- })).rowsAffected === 0) throw new KnowledgeConflictError(source.id);
7404
+ const source = await this.#livePage(tx, input.sourceId);
7405
+ const target = await this.#livePage(tx, input.targetId);
7406
+ if (Number(source.isScope) === 1 || Number(target.isScope) === 1) throw new Error("Cannot merge a scope page: merging applies to non-scope pages only");
7407
+ if (Number(source.version) !== input.sourceVersion) throw new KnowledgeConflictError(input.sourceId);
7408
+ const sourcePath = String(source.path);
7409
+ if (input.sourceId === input.targetId || String(target.path).startsWith(sourcePath)) throw new Error(`Page ${input.targetId} is inside page ${input.sourceId}; it cannot be the merge target (subtree)`);
7410
+ const within = prefixRange("path", sourcePath);
7411
+ const carried = await this.#query(tx, `SELECT COUNT(*) AS n FROM "${T.pages}" WHERE ${within.sql} AND id <> ? AND deletedAt IS NULL`, [...within.args, input.sourceId]);
7412
+ if (Number(carried[0].n) > core.MAX_KNOWLEDGE_MOVE_PAGES) throw new core.KnowledgeMoveTooLargeError(input.sourceId, Number(carried[0].n));
7413
+ const now = (/* @__PURE__ */ new Date()).toISOString();
7903
7414
  await tx.execute({
7904
- sql: `UPDATE "${TABLE_KNOWLEDGE_RECORDS}" SET node=?,version=version+1,updatedAt=? WHERE node=?`,
7415
+ sql: `UPDATE "${T.pages}" SET deletedAt = ?, deletedBy = ?, mergedInto = ?, scopeId = ?, version = version + 1, updatedBy = ?, updatedAt = ? WHERE id = ?`,
7905
7416
  args: [
7906
- target.id,
7907
- (/* @__PURE__ */ new Date()).toISOString(),
7908
- source.id
7417
+ now,
7418
+ input.provenance.author,
7419
+ input.targetId,
7420
+ String(target.scopeId),
7421
+ JSON.stringify(input.provenance),
7422
+ now,
7423
+ input.sourceId
7909
7424
  ]
7910
7425
  });
7426
+ const children = await this.#query(tx, `SELECT * FROM "${T.pages}" WHERE parentId = ? AND isScope = 0`, [input.sourceId]);
7427
+ for (const child of children) await this.#rehome(tx, child, target, {
7428
+ position: String(child.position),
7429
+ countLimitId: input.sourceId
7430
+ });
7911
7431
  await tx.execute({
7912
- 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=?)`,
7913
- args: [source.id, target.id]
7432
+ sql: `UPDATE "${T.notes}" SET pageId = ? WHERE pageId = ?`,
7433
+ args: [input.targetId, input.sourceId]
7914
7434
  });
7915
7435
  await tx.execute({
7916
- sql: `UPDATE "${TABLE_KNOWLEDGE_MENTIONS}" SET recordId=? WHERE recordId=?`,
7917
- args: [target.id, source.id]
7436
+ sql: `UPDATE OR IGNORE "${T.mentions}" SET pageId = ? WHERE pageId = ?`,
7437
+ args: [input.targetId, input.sourceId]
7918
7438
  });
7919
- for (const row of movedKnowledge.rows) await this.#outbox(tx, "record", String(row.id), row.deletedAt == null ? "upsert" : "delete", createKnowledgeUlid(), parseJson$3(row.scopeJson));
7920
- for (const row of affected.rows) await this.#outbox(tx, String(row.sourceType), String(row.sourceId), Number(row.deleted) ? "delete" : "upsert", createKnowledgeUlid(), parseJson$3(row.scopeJson));
7921
- let mergedTarget = target;
7922
- if (target.description === void 0 && source.description) {
7923
- const adoptedAt = /* @__PURE__ */ new Date();
7924
- if ((await tx.execute({
7925
- sql: `UPDATE "${TABLE_KNOWLEDGE_NODES}" SET description=?,version=version+1,updatedAt=? WHERE id=? AND type='node' AND version=? AND description IS NULL`,
7439
+ await tx.execute({
7440
+ sql: `DELETE FROM "${T.mentions}" WHERE pageId = ?`,
7441
+ args: [input.sourceId]
7442
+ });
7443
+ const pins = await this.#query(tx, `SELECT * FROM "${T.pins}" WHERE pageId IN (?, ?)`, [input.sourceId, input.targetId]);
7444
+ const sourcePin = pins.find((pin) => String(pin.pageId) === input.sourceId);
7445
+ if (sourcePin) {
7446
+ const targetPin = pins.find((pin) => String(pin.pageId) === input.targetId);
7447
+ const audience = JSON.parse(String(sourcePin.audience));
7448
+ if (targetPin) {
7449
+ const merged = [.../* @__PURE__ */ new Set([...JSON.parse(String(targetPin.audience)), ...audience])];
7450
+ await tx.execute({
7451
+ sql: `UPDATE "${T.pins}" SET audience = ?, updatedAt = ? WHERE id = ?`,
7452
+ args: [
7453
+ JSON.stringify(merged),
7454
+ now,
7455
+ String(targetPin.id)
7456
+ ]
7457
+ });
7458
+ await this.#indexAudience(tx, String(targetPin.id), merged);
7459
+ await this.#indexAudience(tx, String(sourcePin.id), []);
7460
+ await tx.execute({
7461
+ sql: `DELETE FROM "${T.pins}" WHERE id = ?`,
7462
+ args: [String(sourcePin.id)]
7463
+ });
7464
+ } else await tx.execute({
7465
+ sql: `UPDATE "${T.pins}" SET pageId = ?, updatedAt = ? WHERE id = ?`,
7926
7466
  args: [
7927
- source.description,
7928
- adoptedAt.toISOString(),
7929
- target.id,
7930
- target.version
7467
+ input.targetId,
7468
+ now,
7469
+ String(sourcePin.id)
7931
7470
  ]
7932
- })).rowsAffected > 0) {
7933
- mergedTarget = {
7934
- ...target,
7935
- description: source.description,
7936
- version: target.version + 1,
7937
- updatedAt: adoptedAt
7938
- };
7939
- await this.#activity(tx, "node-updated", "node", target.id, target.scope);
7940
- }
7471
+ });
7941
7472
  }
7942
- await this.#activity(tx, "node-merged", "node", source.id, source.scope);
7943
- await this.#outbox(tx, "node", source.id, "delete", input.sourceVersion + 1, source.scope);
7944
- await this.#outbox(tx, "node", target.id, "upsert", createKnowledgeUlid(), mergedTarget.scope);
7945
- return mergedTarget;
7473
+ await this.#logActivity(tx, "page-merged", {
7474
+ scopeId: String(target.scopeId),
7475
+ pageId: input.sourceId,
7476
+ provenance: input.provenance
7477
+ }, now);
7478
+ return toPage(await this.#pageRow(tx, input.targetId));
7946
7479
  });
7947
7480
  }
7948
- async appendKnowledge(input) {
7949
- await assertKnowledgeRecordTextWithinBoundCompat(input.text);
7950
- const scope = canonicalizeKnowledgeScope(input.scope);
7951
- const resolutionScope = canonicalizeKnowledgeScope(input.resolutionScope);
7952
- const defaultScope = canonicalizeKnowledgeScope(input.defaultScope);
7481
+ async deletePage(input) {
7482
+ const core = await loadPagesCore();
7953
7483
  return this.#transaction(async (tx) => {
7954
- const node = nodeReferenceId(input.node);
7955
- const parent = await this.#resolveTerminalNode(tx, node);
7956
- if (!parent) throw new KnowledgeNotFoundError("node", node);
7957
- const record = {
7958
- id: input.id ?? createKnowledgeUlid(),
7959
- node: parent.id,
7960
- text: input.text,
7961
- scope,
7962
- sourceThreadId: input.sourceThreadId,
7963
- capturedAt: /* @__PURE__ */ new Date(),
7964
- when: input.when ? new Date(input.when) : void 0,
7965
- metadata: input.metadata
7966
- };
7484
+ const row = await this.#livePage(tx, input.id);
7485
+ if (Number(row.isScope) === 1) throw new Error(`Cannot delete ${input.id}: it is a scope page`);
7486
+ if (Number(row.version) !== input.expectedVersion) throw new KnowledgeConflictError(input.id);
7487
+ if ((await this.#query(tx, `SELECT 1 FROM "${T.pages}" WHERE parentId = ? AND deletedAt IS NULL LIMIT 1`, [input.id])).length > 0) throw new core.KnowledgePageHasChildrenError(input.id);
7488
+ const now = (/* @__PURE__ */ new Date()).toISOString();
7967
7489
  await tx.execute({
7968
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_RECORDS}" (id,node,text,scope,scopeKey,sourceThreadId,capturedAt,"when",metadata,version,updatedAt,deletedAt,deletedBy) VALUES (?,?,?,jsonb(?),?,?,?,?,jsonb(?),?,?,NULL,NULL)`,
7490
+ sql: `UPDATE "${T.pages}" SET deletedAt = ?, deletedBy = ?, version = version + 1, updatedBy = ?, updatedAt = ? WHERE id = ?`,
7969
7491
  args: [
7970
- record.id,
7971
- record.node,
7972
- record.text,
7973
- JSON.stringify(scope),
7974
- knowledgeScopeKey(scope),
7975
- record.sourceThreadId,
7976
- record.capturedAt.toISOString(),
7977
- record.when?.toISOString() ?? null,
7978
- record.metadata ? JSON.stringify(record.metadata) : null,
7979
- 1,
7980
- record.capturedAt.toISOString()
7492
+ now,
7493
+ input.deletedBy,
7494
+ JSON.stringify({ author: input.deletedBy }),
7495
+ now,
7496
+ input.id
7981
7497
  ]
7982
7498
  });
7983
- await this.#replaceRecordScopes(tx, record.id, scope, record.capturedAt);
7984
- await this.#replaceMentions(tx, "record", record.id, record.text, resolutionScope, defaultScope);
7985
- await this.#activity(tx, "record-created", "record", record.id, scope, record.sourceThreadId);
7986
- await this.#outbox(tx, "record", record.id, "upsert", record.id, scope);
7987
- return record;
7988
- });
7989
- }
7990
- async getKnowledge(input) {
7991
- const result = await this.#client.execute({
7992
- sql: `SELECT *,json(scope) AS scopeJson,json(metadata) AS metadataJson FROM "${TABLE_KNOWLEDGE_RECORDS}" WHERE id=?${input.includeDeleted ? "" : " AND deletedAt IS NULL"}`,
7993
- args: [input.id]
7499
+ await tx.execute({
7500
+ sql: `DELETE FROM "${T.pinAudiences}" WHERE pinId IN (SELECT id FROM "${T.pins}" WHERE pageId = ?)`,
7501
+ args: [input.id]
7502
+ });
7503
+ await tx.execute({
7504
+ sql: `DELETE FROM "${T.pins}" WHERE pageId = ?`,
7505
+ args: [input.id]
7506
+ });
7507
+ await this.#logActivity(tx, "page-deleted", {
7508
+ scopeId: String(row.scopeId),
7509
+ pageId: input.id,
7510
+ provenance: { author: input.deletedBy }
7511
+ }, now);
7512
+ return toPage(await this.#pageRow(tx, input.id));
7994
7513
  });
7995
- return result.rows[0] ? parseKnowledge(result.rows[0]) : null;
7996
- }
7997
- async listKnowledgeAbout(input) {
7998
- return this.#queryKnowledge(input, "about");
7999
- }
8000
- async listKnowledgeMentioning(input) {
8001
- return this.#queryKnowledge(input, "mentioning");
8002
7514
  }
8003
- async listKnowledgeRelatedTo(input) {
8004
- return this.#queryKnowledge(input, "related");
8005
- }
8006
- async knowledgeBySource(input) {
8007
- const keys = visibleScopeKeys(canonicalizeKnowledgeScope(input.scope));
8008
- const args = [input.sourceThreadId, ...keys];
8009
- if (input.after) args.push(input.after);
8010
- const limit = input.limit ?? 100;
7515
+ async #hydrateNotes(executor, rows) {
7516
+ if (rows.length === 0) return [];
7517
+ const ids = jsonList(rows.map((row) => String(row.id)));
7518
+ const stamps = await this.#query(executor, `SELECT noteId, scopeId FROM "${T.stamps}" WHERE noteId IN (SELECT value FROM json_each(?)) ORDER BY scopeId`, [ids]);
7519
+ const mentions = await this.#query(executor, `SELECT noteId, pageId FROM "${T.mentions}" WHERE noteId IN (SELECT value FROM json_each(?)) ORDER BY pageId`, [ids]);
7520
+ return rows.map((row) => toNote(row, stamps.filter((stamp) => String(stamp.noteId) === String(row.id)).map((stamp) => String(stamp.scopeId)), mentions.filter((mention) => String(mention.noteId) === String(row.id)).map((mention) => String(mention.pageId))));
7521
+ }
7522
+ async #noteById(executor, id) {
7523
+ const rows = await this.#query(executor, `SELECT * FROM "${T.notes}" WHERE id = ?`, [id]);
7524
+ return (await this.#hydrateNotes(executor, rows))[0] ?? null;
7525
+ }
7526
+ async getNote(input) {
7527
+ const readable = noteReadable("n", input.read);
7528
+ const rows = await this.#query(this.#read, `SELECT n.* FROM "${T.notes}" n WHERE n.id = ?${input.includeDeleted ? "" : " AND n.deletedAt IS NULL"} AND ${readable.sql}`, [input.id, ...readable.args]);
7529
+ return (await this.#hydrateNotes(this.#read, rows))[0] ?? null;
7530
+ }
7531
+ async listNotes(input) {
7532
+ const core = await loadPagesCore();
7533
+ const limit = limitOf(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
7534
+ const cursor = decodeCursor(input.cursor, 2);
7535
+ const readable = noteReadable("n", input.read);
7536
+ const args = [input.pageId, ...readable.args];
7537
+ let after = "";
7538
+ if (cursor) {
7539
+ after = ` AND (n.createdAt > ? OR (n.createdAt = ? AND n.id > ?))`;
7540
+ args.push(cursor[0], cursor[0], cursor[1]);
7541
+ }
8011
7542
  args.push(limit + 1);
8012
- const records = (await this.#client.execute({
8013
- sql: `SELECT *,json(scope) AS scopeJson,json(metadata) AS metadataJson FROM "${TABLE_KNOWLEDGE_RECORDS}" WHERE sourceThreadId=? AND ${visibleSql(keys)}${input.includeDeleted ? "" : " AND deletedAt IS NULL"}${input.after ? " AND id > ?" : ""} ORDER BY id ASC LIMIT ?`,
8014
- args
8015
- })).rows.map(parseKnowledge);
7543
+ const rows = await this.#query(this.#read, `SELECT n.* FROM "${T.notes}" n WHERE n.pageId = ?${input.includeDeleted ? "" : " AND n.deletedAt IS NULL"} AND ${readable.sql}${after} ORDER BY n.createdAt, n.id LIMIT ?`, args);
7544
+ return this.#noteOutput(rows, limit);
7545
+ }
7546
+ async countNotes(input) {
7547
+ const ids = [...new Set(input.pageIds)];
7548
+ const counts = Object.fromEntries(ids.map((id) => [id, 0]));
7549
+ if (ids.length === 0) return counts;
7550
+ const readable = noteReadable("n", input.read);
7551
+ const rows = await this.#query(this.#read, `SELECT n.pageId AS pageId, COUNT(*) AS total FROM "${T.notes}" n WHERE n.pageId IN (SELECT value FROM json_each(?)) AND n.deletedAt IS NULL AND ${readable.sql} GROUP BY n.pageId`, [jsonList(ids), ...readable.args]);
7552
+ for (const row of rows) counts[String(row.pageId)] = Number(row.total);
7553
+ return counts;
7554
+ }
7555
+ async listNotesMentioning(input) {
7556
+ const core = await loadPagesCore();
7557
+ const limit = limitOf(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
7558
+ const cursor = decodeCursor(input.cursor, 2);
7559
+ const readable = noteReadable("n", input.read);
7560
+ const args = [
7561
+ input.pageId,
7562
+ input.pageId,
7563
+ ...readable.args
7564
+ ];
7565
+ let after = "";
7566
+ if (cursor) {
7567
+ after = ` AND (n.createdAt < ? OR (n.createdAt = ? AND n.id < ?))`;
7568
+ args.push(cursor[0], cursor[0], cursor[1]);
7569
+ }
7570
+ args.push(limit + 1);
7571
+ const rows = await this.#query(this.#read, `SELECT n.* FROM "${T.notes}" n WHERE n.pageId <> ? AND n.deletedAt IS NULL AND EXISTS (SELECT 1 FROM "${T.mentions}" m WHERE m.noteId = n.id AND m.pageId = ?) AND ${readable.sql}${after} ORDER BY n.createdAt DESC, n.id DESC LIMIT ?`, args);
7572
+ return this.#noteOutput(rows, limit);
7573
+ }
7574
+ async #noteOutput(rows, limit) {
7575
+ const page = rows.slice(0, limit);
8016
7576
  return {
8017
- records: records.slice(0, limit),
8018
- nextCursor: records.length > limit ? records[limit - 1]?.id : void 0
7577
+ notes: await this.#hydrateNotes(this.#read, page),
7578
+ ...rows.length > limit ? { nextCursor: encodeCursor([String(page[page.length - 1].createdAt), String(page[page.length - 1].id)]) } : {}
8019
7579
  };
8020
7580
  }
8021
- async removeKnowledge(input) {
7581
+ async #assertScopes(tx, ids) {
7582
+ if (ids.length === 0) throw new Error("A note needs at least one stamp scope");
7583
+ const found = await this.#query(tx, `SELECT id FROM "${T.pages}" WHERE isScope = 1 AND id IN (SELECT value FROM json_each(?))`, [jsonList(ids)]);
7584
+ const known = new Set(found.map((row) => String(row.id)));
7585
+ const missing = ids.find((id) => !known.has(id));
7586
+ if (missing) throw new Error(`Note stamp ${missing} is not a scope page`);
7587
+ }
7588
+ async addNote(input) {
7589
+ await assertKnowledgeNoteTextWithinBound(input.text);
8022
7590
  return this.#transaction(async (tx) => {
8023
- const record = await this.#getKnowledge(tx, input.id, true);
8024
- if (!record) throw new KnowledgeNotFoundError("record", input.id);
8025
- if (record.deletedAt) return record;
8026
- const deletedAt = /* @__PURE__ */ new Date();
7591
+ const page = await this.#livePage(tx, input.pageId);
7592
+ const stamps = [...new Set(input.stampScopeIds)];
7593
+ await this.#assertScopes(tx, stamps);
7594
+ const mentions = [...new Set(input.mentions)];
7595
+ for (const mention of mentions) await this.#livePage(tx, mention);
7596
+ const id = input.id ?? createKnowledgeUlid();
7597
+ if ((await this.#query(tx, `SELECT 1 FROM "${T.notes}" WHERE id = ?`, [id])).length > 0) throw new KnowledgeConflictError(id);
7598
+ const now = (/* @__PURE__ */ new Date()).toISOString();
8027
7599
  await tx.execute({
8028
- sql: `UPDATE "${TABLE_KNOWLEDGE_RECORDS}" SET deletedAt=?,deletedBy=?,version=version+1,updatedAt=? WHERE id=? AND deletedAt IS NULL`,
7600
+ sql: `INSERT INTO "${T.notes}" (id, pageId, text, "when", provenance, version, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, 1, ?, ?)`,
8029
7601
  args: [
8030
- deletedAt.toISOString(),
8031
- input.deletedBy,
8032
- deletedAt.toISOString(),
8033
- input.id
7602
+ id,
7603
+ input.pageId,
7604
+ input.text,
7605
+ input.when ? input.when.toISOString() : null,
7606
+ JSON.stringify(input.provenance),
7607
+ now,
7608
+ now
8034
7609
  ]
8035
7610
  });
8036
- await this.#activity(tx, "record-deleted", "record", input.id, record.scope, record.sourceThreadId);
8037
- await this.#outbox(tx, "record", input.id, "delete", deletedAt.toISOString(), record.scope);
8038
- return {
8039
- ...record,
8040
- deletedAt,
8041
- deletedBy: input.deletedBy
8042
- };
7611
+ for (const stamp of stamps) await tx.execute({
7612
+ sql: `INSERT INTO "${T.stamps}" (noteId, scopeId) VALUES (?, ?)`,
7613
+ args: [id, stamp]
7614
+ });
7615
+ for (const mention of mentions) await tx.execute({
7616
+ sql: `INSERT INTO "${T.mentions}" (noteId, pageId) VALUES (?, ?)`,
7617
+ args: [id, mention]
7618
+ });
7619
+ await this.#logActivity(tx, "note-added", {
7620
+ scopeId: String(page.scopeId),
7621
+ pageId: input.pageId,
7622
+ noteId: id,
7623
+ provenance: input.provenance
7624
+ }, now);
7625
+ return await this.#noteById(tx, id);
8043
7626
  });
8044
7627
  }
8045
- async restoreKnowledge(input) {
7628
+ async #noteWithPage(tx, id) {
7629
+ const note = (await this.#query(tx, `SELECT * FROM "${T.notes}" WHERE id = ?`, [id]))[0];
7630
+ if (!note) throw new KnowledgeNotFoundError("note", id);
7631
+ const page = await this.#pageRow(tx, String(note.pageId));
7632
+ if (!page) throw new KnowledgeNotFoundError("page", String(note.pageId));
7633
+ return {
7634
+ note,
7635
+ page
7636
+ };
7637
+ }
7638
+ restampNote(input) {
8046
7639
  return this.#transaction(async (tx) => {
8047
- const record = await this.#getKnowledge(tx, input.id, true);
8048
- if (!record) throw new KnowledgeNotFoundError("record", input.id);
8049
- if (!record.deletedAt) return record;
7640
+ const { note, page } = await this.#noteWithPage(tx, input.id);
7641
+ if (note.deletedAt) throw new KnowledgeNotFoundError("note", input.id);
7642
+ if (Number(note.version) !== input.expectedVersion) throw new KnowledgeConflictError(input.id);
7643
+ const stamps = [...new Set(input.stampScopeIds)];
7644
+ await this.#assertScopes(tx, stamps);
7645
+ const now = (/* @__PURE__ */ new Date()).toISOString();
8050
7646
  await tx.execute({
8051
- sql: `UPDATE "${TABLE_KNOWLEDGE_RECORDS}" SET deletedAt=NULL,deletedBy=NULL,version=version+1,updatedAt=? WHERE id=?`,
8052
- args: [(/* @__PURE__ */ new Date()).toISOString(), input.id]
7647
+ sql: `DELETE FROM "${T.stamps}" WHERE noteId = ?`,
7648
+ args: [input.id]
8053
7649
  });
8054
- await this.#activity(tx, "record-restored", "record", input.id, record.scope, record.sourceThreadId);
8055
- await this.#outbox(tx, "record", input.id, "upsert", createKnowledgeUlid(), record.scope);
8056
- return {
8057
- ...record,
8058
- deletedAt: void 0,
8059
- deletedBy: void 0
8060
- };
7650
+ for (const stamp of stamps) await tx.execute({
7651
+ sql: `INSERT INTO "${T.stamps}" (noteId, scopeId) VALUES (?, ?)`,
7652
+ args: [input.id, stamp]
7653
+ });
7654
+ await tx.execute({
7655
+ sql: `UPDATE "${T.notes}" SET version = version + 1, updatedAt = ? WHERE id = ?`,
7656
+ args: [now, input.id]
7657
+ });
7658
+ await this.#logActivity(tx, "note-restamped", {
7659
+ scopeId: String(page.scopeId),
7660
+ pageId: String(page.id),
7661
+ noteId: input.id,
7662
+ provenance: input.provenance
7663
+ }, now);
7664
+ return await this.#noteById(tx, input.id);
8061
7665
  });
8062
7666
  }
8063
- async rescopeKnowledge(input) {
8064
- const scope = canonicalizeKnowledgeScope(input.scope);
7667
+ removeNote(input) {
8065
7668
  return this.#transaction(async (tx) => {
8066
- const record = await this.#getKnowledge(tx, input.id, true);
8067
- if (!record) throw new KnowledgeNotFoundError("record", input.id);
8068
- const updatedAt = /* @__PURE__ */ new Date();
7669
+ const { note, page } = await this.#noteWithPage(tx, input.id);
7670
+ if (note.deletedAt) throw new KnowledgeNotFoundError("note", input.id);
7671
+ const now = (/* @__PURE__ */ new Date()).toISOString();
8069
7672
  await tx.execute({
8070
- sql: `UPDATE "${TABLE_KNOWLEDGE_RECORDS}" SET scope=jsonb(?),scopeKey=?,version=version+1,updatedAt=? WHERE id=?`,
7673
+ sql: `UPDATE "${T.notes}" SET deletedAt = ?, deletedBy = ?, version = version + 1, updatedAt = ? WHERE id = ?`,
8071
7674
  args: [
8072
- JSON.stringify(scope),
8073
- knowledgeScopeKey(scope),
8074
- updatedAt.toISOString(),
7675
+ now,
7676
+ input.deletedBy,
7677
+ now,
8075
7678
  input.id
8076
7679
  ]
8077
7680
  });
8078
- await this.#replaceRecordScopes(tx, input.id, scope, updatedAt);
8079
- await this.#activity(tx, "record-rescoped", "record", input.id, scope, record.sourceThreadId);
8080
- if (knowledgeScopeKey(record.scope) !== knowledgeScopeKey(scope)) await this.#outbox(tx, "record", input.id, "delete", createKnowledgeUlid(), record.scope);
8081
- if (!record.deletedAt) await this.#outbox(tx, "record", input.id, "upsert", createKnowledgeUlid(), scope);
8082
- return {
8083
- ...record,
8084
- scope
8085
- };
7681
+ await this.#logActivity(tx, "note-removed", {
7682
+ scopeId: String(page.scopeId),
7683
+ pageId: String(page.id),
7684
+ noteId: input.id,
7685
+ provenance: input.provenance
7686
+ }, now);
7687
+ return await this.#noteById(tx, input.id);
8086
7688
  });
8087
7689
  }
8088
- async search(input) {
8089
- const scope = canonicalizeKnowledgeScope(input.scope);
8090
- const keys = visibleScopeKeys(scope);
8091
- const normalizedQuery = input.query.trim().toLocaleLowerCase();
8092
- if (!normalizedQuery) return [];
8093
- const query = `%${escapeLikePattern(normalizedQuery)}%`;
8094
- const results = (await this.#client.execute({
8095
- sql: `SELECT *,json(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 ?`,
8096
- args: [
8097
- ...keys,
8098
- query,
8099
- query,
8100
- query,
8101
- query,
8102
- input.limit ?? 20
8103
- ]
8104
- })).rows.map((row) => ({
8105
- type: String(row.type),
8106
- id: String(row.id),
8107
- recordId: String(row.id),
8108
- name: String(row.name),
8109
- text: [
8110
- String(row.name),
8111
- ...row.description ? [String(row.description)] : [],
8112
- ...row.content ? [String(row.content)] : []
8113
- ].join("\n"),
8114
- scope: parseJson$3(row.scopeJson)
8115
- }));
8116
- if (results.length < (input.limit ?? 20)) {
8117
- const knowledge = await this.#client.execute({
8118
- sql: `SELECT k.*,json(k.scope) AS scopeJson,json(k.metadata) AS metadataJson,n.name,json(n.scope) AS parentScopeJson FROM "${TABLE_KNOWLEDGE_RECORDS}" k CROSS JOIN "${TABLE_KNOWLEDGE_NODES}" n ON n.id=k.node AND n.type='node' AND n.mergedInto IS NULL WHERE k.deletedAt IS NULL AND ${visibleSql(keys, "k.scopeKey")} AND lower(k.text) LIKE ? ESCAPE '=' ORDER BY k.id DESC LIMIT ?`,
8119
- args: [
8120
- ...keys,
8121
- query,
8122
- (input.limit ?? 20) - results.length
8123
- ]
7690
+ restoreNote(input) {
7691
+ return this.#transaction(async (tx) => {
7692
+ const { note, page } = await this.#noteWithPage(tx, input.id);
7693
+ if (!note.deletedAt) throw new KnowledgeNotFoundError("note", input.id);
7694
+ const now = (/* @__PURE__ */ new Date()).toISOString();
7695
+ await tx.execute({
7696
+ sql: `UPDATE "${T.notes}" SET deletedAt = NULL, deletedBy = NULL, version = version + 1, updatedAt = ? WHERE id = ?`,
7697
+ args: [now, input.id]
8124
7698
  });
8125
- results.push(...knowledge.rows.map((row) => {
8126
- const parentVisible = isKnowledgeScopeVisible(parseJson$3(row.parentScopeJson), scope);
8127
- return {
8128
- type: "record",
8129
- id: String(row.id),
8130
- recordId: parentVisible ? String(row.node) : String(row.id),
8131
- name: parentVisible ? String(row.name) : "(private node)",
8132
- text: String(row.text),
8133
- scope: parseJson$3(row.scopeJson)
8134
- };
8135
- }));
8136
- }
8137
- return results;
8138
- }
8139
- /**
8140
- * @deprecated Curation cursors were removed. Observation-time curate is the only Knowledge writer and needs no
8141
- * cursor. Always throws.
8142
- */
8143
- async getCurationCursor(_input) {
8144
- throw new Error(KNOWLEDGE_CURATION_CURSOR_REMOVED_MESSAGE);
8145
- }
8146
- /**
8147
- * @deprecated Curation cursors were removed. Observation-time curate is the only Knowledge writer and needs no
8148
- * cursor. Always throws.
8149
- */
8150
- async advanceCurationCursor(_input) {
8151
- throw new Error(KNOWLEDGE_CURATION_CURSOR_REMOVED_MESSAGE);
7699
+ await this.#logActivity(tx, "note-restored", {
7700
+ scopeId: String(page.scopeId),
7701
+ pageId: String(page.id),
7702
+ noteId: input.id,
7703
+ provenance: input.provenance
7704
+ }, now);
7705
+ return await this.#noteById(tx, input.id);
7706
+ });
8152
7707
  }
8153
- async listActivity(input) {
8154
- const keys = visibleScopeKeys(canonicalizeKnowledgeScope(input.scope));
8155
- return (await this.#client.execute({
8156
- sql: `SELECT *,json(scope) AS scopeJson FROM "${TABLE_KNOWLEDGE_ACTIVITY}" WHERE ${visibleSql(keys)}${input.after ? " AND id < ?" : ""} ORDER BY id DESC LIMIT ?`,
8157
- args: [
8158
- ...keys,
8159
- ...input.after ? [input.after] : [],
8160
- input.limit ?? 100
8161
- ]
8162
- })).rows.map((row) => ({
8163
- id: String(row.id),
8164
- action: String(row.action),
8165
- recordType: String(row.recordType),
8166
- recordId: String(row.recordId),
8167
- scope: parseJson$3(row.scopeJson),
8168
- sourceThreadId: row.sourceThreadId == null ? void 0 : String(row.sourceThreadId),
8169
- createdAt: toDate(row.createdAt)
7708
+ async searchPages(input) {
7709
+ const words = knowledgeSearchWords(input.query);
7710
+ if (!words.length) return [];
7711
+ const phrase = input.query.trim().toLowerCase().replace(/\s+/g, " ");
7712
+ const limit = Math.max(1, input.limit ?? 20);
7713
+ const likes = words.map((word) => `%${escapeLike(word)}%`);
7714
+ const readable = pageReadable("p", input.read);
7715
+ const scopeFilter = input.scopeIds ? ` AND p.scopeId IN (SELECT value FROM json_each(?))` : "";
7716
+ const scopeArgs = input.scopeIds ? [jsonList(input.scopeIds)] : [];
7717
+ const pageMatch = words.map(() => `(lower(p.name) LIKE ? ESCAPE '=' OR lower(COALESCE(p.description, '')) LIKE ? ESCAPE '=' OR lower(COALESCE(p.body, '')) LIKE ? ESCAPE '=')`).join(" AND ");
7718
+ const nameMatch = words.map(() => `lower(p.name) LIKE ? ESCAPE '='`).join(" AND ");
7719
+ const hits = (await this.#query(this.#read, `SELECT p.* FROM "${T.pages}" p WHERE p.deletedAt IS NULL AND p.isScope = 0 AND ${readable.sql}${scopeFilter} AND ${pageMatch} ORDER BY CASE WHEN instr(p.canonicalName, ?) > 0 THEN 0 WHEN ${nameMatch} THEN 1 ELSE 2 END, p.updatedAt DESC, p.id ASC LIMIT ?`, [
7720
+ ...readable.args,
7721
+ ...scopeArgs,
7722
+ ...likes.flatMap((like) => [
7723
+ like,
7724
+ like,
7725
+ like
7726
+ ]),
7727
+ phrase,
7728
+ ...likes,
7729
+ limit
7730
+ ])).map((row) => ({
7731
+ type: "page",
7732
+ page: toPage(row)
8170
7733
  }));
8171
- }
8172
- async listSemanticOutbox(input = {}) {
8173
- const clauses = [];
8174
- const args = [];
8175
- if (input.status) {
8176
- clauses.push("status=?");
8177
- args.push(input.status);
8178
- }
8179
- if (input.scope) {
8180
- const keys = visibleScopeKeys(input.scope);
8181
- clauses.push(visibleSql(keys));
8182
- args.push(...keys);
7734
+ if (hits.length >= limit) return hits;
7735
+ const noteVisible = noteReadable("n", input.read);
7736
+ const noteMatch = words.map(() => `lower(n.text) LIKE ? ESCAPE '='`).join(" AND ");
7737
+ const noteRows = await this.#query(this.#read, `SELECT n.* FROM "${T.notes}" n JOIN "${T.pages}" p ON p.id = n.pageId WHERE n.deletedAt IS NULL AND p.deletedAt IS NULL${scopeFilter} AND ${noteMatch} AND ${noteVisible.sql} ORDER BY n.updatedAt DESC, n.id DESC LIMIT ?`, [
7738
+ ...scopeArgs,
7739
+ ...likes,
7740
+ ...noteVisible.args,
7741
+ limit - hits.length
7742
+ ]);
7743
+ const notes = await this.#hydrateNotes(this.#read, noteRows);
7744
+ for (const note of notes) {
7745
+ const page = await this.#pageRow(this.#read, note.pageId);
7746
+ if (page) hits.push({
7747
+ type: "note",
7748
+ note,
7749
+ page: toPage(page)
7750
+ });
8183
7751
  }
8184
- args.push(input.limit ?? 100);
8185
- return (await this.#client.execute({
8186
- sql: `SELECT *,json(scope) AS scopeJson FROM "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}"${clauses.length ? ` WHERE ${clauses.join(" AND ")}` : ""} ORDER BY createdAt ASC,id ASC LIMIT ?`,
8187
- args
8188
- })).rows.map(parseOutbox);
7752
+ return hits;
7753
+ }
7754
+ async listPageActivity(input) {
7755
+ const core = await loadPagesCore();
7756
+ const limit = limitOf(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
7757
+ const cursor = decodeCursor(input.cursor, 1);
7758
+ const readable = pageReadable("p", input.read);
7759
+ const noteVisible = noteReadable("n", input.read);
7760
+ const args = [...readable.args];
7761
+ let filters = "";
7762
+ if (input.scopeId !== void 0) {
7763
+ filters += ` AND p.scopeId = ?`;
7764
+ args.push(input.scopeId);
7765
+ }
7766
+ if (input.pageId !== void 0) {
7767
+ filters += ` AND e.pageId = ?`;
7768
+ args.push(input.pageId);
7769
+ }
7770
+ if (cursor) {
7771
+ filters += ` AND e.id < ?`;
7772
+ args.push(cursor[0]);
7773
+ }
7774
+ args.push(...noteVisible.args, limit + 1);
7775
+ const rows = await this.#query(this.#read, `SELECT e.* FROM "${T.activity}" e JOIN "${T.pages}" p ON p.id = e.pageId WHERE ${readable.sql}${filters} AND (e.noteId IS NULL OR EXISTS (SELECT 1 FROM "${T.notes}" n WHERE n.id = e.noteId AND ${noteVisible.sql})) ORDER BY e.id DESC LIMIT ?`, args);
7776
+ const page = rows.slice(0, limit);
7777
+ return {
7778
+ events: page.map((row) => ({
7779
+ id: String(row.id),
7780
+ action: String(row.action),
7781
+ scopeId: String(row.scopeId),
7782
+ pageId: String(row.pageId),
7783
+ ...row.noteId ? { noteId: String(row.noteId) } : {},
7784
+ provenance: provenance(row.provenance),
7785
+ createdAt: new Date(String(row.createdAt))
7786
+ })),
7787
+ ...rows.length > limit ? { nextCursor: encodeCursor([String(page[page.length - 1].id)]) } : {}
7788
+ };
7789
+ }
7790
+ /** Rewrites the audience index rows of one pin to match `audience`. */
7791
+ async #indexAudience(tx, pinId, audience) {
7792
+ await tx.execute({
7793
+ sql: `DELETE FROM "${T.pinAudiences}" WHERE pinId = ?`,
7794
+ args: [pinId]
7795
+ });
7796
+ for (const entry of audience) await tx.execute({
7797
+ sql: `INSERT OR IGNORE INTO "${T.pinAudiences}" (pinId, audience) VALUES (?, ?)`,
7798
+ args: [pinId, entry]
7799
+ });
8189
7800
  }
8190
- async claimSemanticOutbox(input) {
8191
- const now = input.now ?? /* @__PURE__ */ new Date();
8192
- const stale = new Date(now.getTime() - (input.claimTimeoutMs ?? 6e4));
7801
+ addPinAudience(input) {
8193
7802
  return this.#transaction(async (tx) => {
8194
- const clauses = [
8195
- `availableAt <= ?`,
8196
- `(status='pending' OR (status='processing' AND claimedAt <= ?))`,
8197
- `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)))`
8198
- ];
8199
- const args = [now.toISOString(), stale.toISOString()];
8200
- if (input.scope) {
8201
- const keys = visibleScopeKeys(input.scope);
8202
- clauses.push(visibleSql(keys));
8203
- args.push(...keys);
7803
+ const page = await this.#livePage(tx, input.pageId);
7804
+ const now = (/* @__PURE__ */ new Date()).toISOString();
7805
+ const existing = (await this.#query(tx, `SELECT * FROM "${T.pins}" WHERE pageId = ?`, [input.pageId]))[0];
7806
+ if (!existing) {
7807
+ const id = createKnowledgeUlid();
7808
+ await tx.execute({
7809
+ sql: `INSERT INTO "${T.pins}" (id, pageId, audience, createdBy, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)`,
7810
+ args: [
7811
+ id,
7812
+ input.pageId,
7813
+ JSON.stringify([...new Set(input.audience)]),
7814
+ input.createdBy,
7815
+ now,
7816
+ now
7817
+ ]
7818
+ });
7819
+ await this.#indexAudience(tx, id, [...new Set(input.audience)]);
7820
+ await this.#logActivity(tx, "pin-added", {
7821
+ scopeId: String(page.scopeId),
7822
+ pageId: input.pageId,
7823
+ provenance: { author: input.createdBy }
7824
+ }, now);
7825
+ return toPin((await this.#query(tx, `SELECT * FROM "${T.pins}" WHERE id = ?`, [id]))[0]);
8204
7826
  }
8205
- args.push(input.limit ?? 100);
8206
- const ids = (await tx.execute({
8207
- sql: `SELECT id FROM "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" WHERE ${clauses.join(" AND ")} ORDER BY createdAt ASC,id ASC LIMIT ?`,
8208
- args
8209
- })).rows.map((row) => String(row.id));
8210
- for (const id of ids) await tx.execute({
8211
- sql: `UPDATE "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" SET status='processing',attempts=attempts+1,claimedAt=?,claimedBy=? WHERE id=?`,
8212
- args: [
8213
- now.toISOString(),
8214
- input.workerId,
8215
- id
8216
- ]
8217
- });
8218
- if (!ids.length) return [];
8219
- return (await tx.execute({
8220
- sql: `SELECT *,json(scope) AS scopeJson FROM "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" WHERE id IN (${ids.map(() => "?").join(",")}) ORDER BY createdAt ASC,id ASC`,
8221
- args: ids
8222
- })).rows.map(parseOutbox);
7827
+ const current = JSON.parse(String(existing.audience));
7828
+ const merged = [.../* @__PURE__ */ new Set([...current, ...input.audience])];
7829
+ if (merged.length !== current.length) {
7830
+ await tx.execute({
7831
+ sql: `UPDATE "${T.pins}" SET audience = ?, updatedAt = ? WHERE id = ?`,
7832
+ args: [
7833
+ JSON.stringify(merged),
7834
+ now,
7835
+ String(existing.id)
7836
+ ]
7837
+ });
7838
+ await this.#indexAudience(tx, String(existing.id), merged);
7839
+ await this.#logActivity(tx, "pin-added", {
7840
+ scopeId: String(page.scopeId),
7841
+ pageId: input.pageId,
7842
+ provenance: { author: input.createdBy }
7843
+ }, now);
7844
+ }
7845
+ return toPin((await this.#query(tx, `SELECT * FROM "${T.pins}" WHERE id = ?`, [String(existing.id)]))[0]);
8223
7846
  });
8224
7847
  }
8225
- async completeSemanticOutbox(input) {
8226
- if (!input.ids.length) return;
8227
- const now = (/* @__PURE__ */ new Date()).toISOString();
8228
- await this.#transaction(async (tx) => {
8229
- for (const id of input.ids) await tx.execute({
8230
- sql: `UPDATE "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" SET status='completed',completedAt=? WHERE id=? AND status='processing' AND claimedBy=?`,
7848
+ removePinAudience(input) {
7849
+ return this.#transaction(async (tx) => {
7850
+ const existing = (await this.#query(tx, `SELECT * FROM "${T.pins}" WHERE pageId = ?`, [input.pageId]))[0];
7851
+ if (!existing) return null;
7852
+ const current = JSON.parse(String(existing.audience));
7853
+ const remove = new Set(input.audience);
7854
+ const remaining = current.filter((entry) => !remove.has(entry));
7855
+ if (remaining.length === current.length) return toPin(existing);
7856
+ const page = await this.#pageRow(tx, input.pageId);
7857
+ const now = (/* @__PURE__ */ new Date()).toISOString();
7858
+ if (page) await this.#logActivity(tx, "pin-removed", {
7859
+ scopeId: String(page.scopeId),
7860
+ pageId: input.pageId,
7861
+ provenance: { author: input.removedBy }
7862
+ }, now);
7863
+ if (remaining.length === 0) {
7864
+ await this.#indexAudience(tx, String(existing.id), []);
7865
+ await tx.execute({
7866
+ sql: `DELETE FROM "${T.pins}" WHERE id = ?`,
7867
+ args: [String(existing.id)]
7868
+ });
7869
+ return null;
7870
+ }
7871
+ await tx.execute({
7872
+ sql: `UPDATE "${T.pins}" SET audience = ?, updatedAt = ? WHERE id = ?`,
8231
7873
  args: [
7874
+ JSON.stringify(remaining),
8232
7875
  now,
8233
- id,
8234
- input.workerId
8235
- ]
8236
- });
8237
- });
8238
- }
8239
- async releaseSemanticOutbox(input) {
8240
- if (!input.ids.length) return;
8241
- await this.#transaction(async (tx) => {
8242
- for (const id of input.ids) await tx.execute({
8243
- sql: `UPDATE "${TABLE_KNOWLEDGE_SEMANTIC_OUTBOX}" SET status='pending',availableAt=?,claimedAt=NULL,claimedBy=NULL WHERE id=? AND status='processing' AND claimedBy=?`,
8244
- args: [
8245
- (input.retryAt ?? /* @__PURE__ */ new Date()).toISOString(),
8246
- id,
8247
- input.workerId
7876
+ String(existing.id)
8248
7877
  ]
8249
7878
  });
7879
+ await this.#indexAudience(tx, String(existing.id), remaining);
7880
+ return toPin((await this.#query(tx, `SELECT * FROM "${T.pins}" WHERE id = ?`, [String(existing.id)]))[0]);
8250
7881
  });
8251
7882
  }
8252
- async #transaction(operation) {
8253
- return this.#db.executeWriteOperationWithRetry(() => withClientWriteLock(this.#client, async () => {
8254
- const tx = await this.#client.transaction("write");
8255
- try {
8256
- const result = await operation(tx);
8257
- await tx.commit();
8258
- return result;
8259
- } catch (error) {
8260
- if (!tx.closed) await tx.rollback();
8261
- throw error;
8262
- }
8263
- }), "write knowledge state");
8264
- }
8265
- async #getNode(executor, id) {
8266
- const result = await executor.execute({
8267
- sql: `SELECT *,json(scope) AS scopeJson FROM "${TABLE_KNOWLEDGE_NODES}" WHERE id=? AND type='node'`,
8268
- args: [id]
8269
- });
8270
- return result.rows[0] ? parseNode(result.rows[0]) : null;
7883
+ async listPins(input) {
7884
+ const core = await loadPagesCore();
7885
+ const limit = limitOf(input.limit, core.MAX_KNOWLEDGE_PAGE_LIST_LIMIT);
7886
+ const cursor = decodeCursor(input.cursor, 2);
7887
+ const readable = pageReadable("p", input.read);
7888
+ const args = [...readable.args];
7889
+ let filters = "";
7890
+ if (input.audience !== "all") {
7891
+ filters += ` AND pin.id IN (SELECT pa.pinId FROM json_each(?) a JOIN "${T.pinAudiences}" pa ON pa.audience = a.value)`;
7892
+ args.push(jsonList(input.audience));
7893
+ }
7894
+ if (input.pageIds) {
7895
+ filters += ` AND pin.pageId IN (SELECT value FROM json_each(?))`;
7896
+ args.push(jsonList(input.pageIds));
7897
+ }
7898
+ if (input.excludePageIds?.length) {
7899
+ filters += ` AND pin.pageId NOT IN (SELECT value FROM json_each(?))`;
7900
+ args.push(jsonList(input.excludePageIds));
7901
+ }
7902
+ if (input.withBody) filters += ` AND p.body IS NOT NULL AND trim(p.body, char(32, 9, 10, 11, 12, 13)) <> ''`;
7903
+ const from = `FROM "${T.pins}" pin JOIN "${T.pages}" p ON p.id = pin.pageId WHERE p.deletedAt IS NULL AND ${readable.sql}${filters}`;
7904
+ let total;
7905
+ if (input.count) total = Number((await this.#query(this.#read, `SELECT COUNT(*) AS n ${from}`, args))[0].n);
7906
+ const pageArgs = [...args];
7907
+ let cursorFilter = "";
7908
+ if (cursor) {
7909
+ cursorFilter = ` AND (pin.createdAt < ? OR (pin.createdAt = ? AND pin.id < ?))`;
7910
+ pageArgs.push(cursor[0], cursor[0], cursor[1]);
7911
+ }
7912
+ pageArgs.push(limit + 1);
7913
+ const rows = await this.#query(this.#read, `SELECT pin.*, p.name AS pageName ${from}${cursorFilter} ORDER BY pin.createdAt DESC, pin.id DESC LIMIT ?`, pageArgs);
7914
+ const page = rows.slice(0, limit);
7915
+ return {
7916
+ pins: page.map(toListedPin),
7917
+ ...rows.length > limit ? { nextCursor: encodeCursor([String(page[page.length - 1].createdAt), String(page[page.length - 1].id)]) } : {},
7918
+ ...total === void 0 ? {} : { total }
7919
+ };
8271
7920
  }
8272
- async #getNodeByName(executor, name, scope) {
8273
- const result = await executor.execute({
8274
- sql: `SELECT *,json(scope) AS scopeJson FROM "${TABLE_KNOWLEDGE_NODES}" WHERE type='node' AND scopeKey=? AND canonicalName=?`,
8275
- args: [knowledgeScopeKey(scope), canonicalName(name)]
8276
- });
8277
- return result.rows[0] ? parseNode(result.rows[0]) : null;
8278
- }
8279
- async #resolveNode(executor, name, scope) {
8280
- const keys = visibleScopeKeys(scope);
8281
- const candidates = (await executor.execute({
8282
- sql: `SELECT *,json(scope) AS scopeJson FROM "${TABLE_KNOWLEDGE_NODES}" WHERE type='node' AND canonicalName=? AND (scopeKey IN (${keys.map(() => "?").join(",")}) OR mergedInto IS NOT NULL)`,
8283
- args: [canonicalName(name), ...keys]
8284
- })).rows.map(parseNode).sort((left, right) => right.scope.length - left.scope.length);
8285
- for (const candidate of candidates) {
8286
- const terminal = await this.#resolveTerminalNode(executor, candidate.id);
8287
- if (terminal && isKnowledgeScopeVisible(terminal.scope, scope)) return terminal;
8288
- }
8289
- return null;
8290
- }
8291
- async #resolveTerminalNode(executor, id) {
8292
- let node = await this.#getNode(executor, id);
8293
- const seen = /* @__PURE__ */ new Set();
8294
- while (node?.mergedInto) {
8295
- if (seen.has(node.id)) throw new Error(`Knowledge merge cycle detected at ${node.id}`);
8296
- seen.add(node.id);
8297
- node = await this.#getNode(executor, node.mergedInto);
7921
+ };
7922
+ // src/storage/domains/knowledge/index.ts
7923
+ function canonicalizeLibSQLUrl(url) {
7924
+ if (url.includes(":memory:")) return /[?&]cache=shared(?:&|$)/.test(url) ? "file::memory:?cache=shared" : void 0;
7925
+ if (url.startsWith("file:")) {
7926
+ const [path] = url.slice(5).split("?");
7927
+ if (url.startsWith("file://")) {
7928
+ const parsed = new URL(url);
7929
+ const host = parsed.hostname.toLocaleLowerCase();
7930
+ const filePath = host && host !== "localhost" ? `//${host}${parsed.pathname}` : parsed.pathname;
7931
+ return `file:${resolve(decodeURIComponent(filePath))}`;
8298
7932
  }
8299
- return node;
7933
+ return `file:${resolve(decodeURIComponent(path))}`;
8300
7934
  }
8301
- async #getKnowledge(executor, id, includeDeleted) {
8302
- const result = await executor.execute({
8303
- sql: `SELECT *,json(scope) AS scopeJson,json(metadata) AS metadataJson FROM "${TABLE_KNOWLEDGE_RECORDS}" WHERE id=?${includeDeleted ? "" : " AND deletedAt IS NULL"}`,
8304
- args: [id]
7935
+ try {
7936
+ const parsed = new URL(url);
7937
+ const port = parsed.port || (parsed.protocol === "libsql:" || parsed.protocol === "https:" ? "443" : "80");
7938
+ return `${parsed.protocol}//${parsed.hostname.toLocaleLowerCase()}:${port}${parsed.pathname}`;
7939
+ } catch {
7940
+ return url;
7941
+ }
7942
+ }
7943
+ const unidentifiedClientIsolationKey = {};
7944
+ function getLibSQLKnowledgeIsolationKey(config, client) {
7945
+ if (config.storageIsolationKey !== void 0) return config.storageIsolationKey;
7946
+ if (!config.url) return unidentifiedClientIsolationKey;
7947
+ const urlKey = canonicalizeLibSQLUrl(config.url);
7948
+ return urlKey ? `libsql:${urlKey}` : client ?? config.client ?? config;
7949
+ }
7950
+ var KnowledgeLibSQL = class extends KnowledgeStorage {
7951
+ #client;
7952
+ #db;
7953
+ #pages;
7954
+ constructor(config) {
7955
+ const client = resolveClient(config);
7956
+ const storageIsolationKey = config.storageIsolationKey ?? getLibSQLKnowledgeIsolationKey(config, client);
7957
+ super({ storageIsolationKey });
7958
+ this.#client = client;
7959
+ this.#db = new LibSQLDB({
7960
+ client: this.#client,
7961
+ maxRetries: config.maxRetries,
7962
+ initialBackoffMs: config.initialBackoffMs
8305
7963
  });
8306
- return result.rows[0] ? parseKnowledge(result.rows[0]) : null;
8307
- }
8308
- async #queryKnowledge(input, relationship) {
8309
- const scope = canonicalizeKnowledgeScope(input.scope);
8310
- const node = await this.#resolveTerminalNode(this.#client, nodeReferenceId(input.node));
8311
- if (!node) return { records: [] };
8312
- const keys = visibleScopeKeys(scope);
8313
- const includesMentions = relationship !== "about";
8314
- const relationSql = relationship === "about" ? "k.node=?" : relationship === "mentioning" ? "m.recordId=?" : "(k.node=? OR m.recordId=?)";
8315
- const args = [
8316
- node.id,
8317
- ...relationship === "related" ? [node.id] : [],
8318
- ...keys
8319
- ];
8320
- if (input.after) args.push(input.after);
8321
- args.push((input.limit ?? 100) + 1);
8322
- const result = await this.#client.execute({
8323
- sql: `SELECT DISTINCT k.*,json(k.scope) AS scopeJson,json(k.metadata) AS metadataJson FROM "${TABLE_KNOWLEDGE_RECORDS}" k${includesMentions ? ` LEFT JOIN "${TABLE_KNOWLEDGE_MENTIONS}" m ON m.sourceType='record' AND m.sourceId=k.id` : ""} WHERE ${relationSql} AND ${visibleSql(keys, "k.scopeKey")}${input.includeDeleted ? "" : " AND k.deletedAt IS NULL"}${input.after ? " AND k.id < ?" : ""} ORDER BY k.id DESC LIMIT ?`,
8324
- args
7964
+ this.#pages = new LibSQLKnowledgePages({
7965
+ read: this.#client,
7966
+ transaction: (operation) => this.#transaction(operation)
8325
7967
  });
8326
- const limit = input.limit ?? 100;
8327
- const rows = result.rows.slice(0, limit);
7968
+ }
7969
+ getCapabilities() {
8328
7970
  return {
8329
- records: rows.map(parseKnowledge),
8330
- nextCursor: result.rows.length > limit ? String(rows.at(-1)?.id) : void 0
7971
+ contractVersion: 4,
7972
+ schemaVersion: 4,
7973
+ supportsSchemaInspection: true,
7974
+ supportsExplicitReset: true
8331
7975
  };
8332
7976
  }
8333
- async #resolveScopeNodeIds(executor, addresses) {
8334
- const scopeNodeIds = /* @__PURE__ */ new Set();
8335
- for (const address of addresses) {
8336
- const result = await executor.execute({
8337
- sql: `SELECT scopeNodeId FROM "${TABLE_KNOWLEDGE_SCOPE_ADDRESSES}" WHERE address=?`,
8338
- args: [address]
8339
- });
8340
- if (result.rows[0]?.scopeNodeId != null) scopeNodeIds.add(String(result.rows[0].scopeNodeId));
8341
- }
8342
- return [...scopeNodeIds];
8343
- }
8344
- async #replaceNodeScopes(executor, nodeId, addresses, addedAt) {
8345
- await executor.execute({
8346
- sql: `DELETE FROM "${TABLE_KNOWLEDGE_NODE_SCOPES}" WHERE nodeId=?`,
8347
- args: [nodeId]
8348
- });
8349
- for (const scopeNodeId of await this.#resolveScopeNodeIds(executor, addresses)) await executor.execute({
8350
- sql: `INSERT OR IGNORE INTO "${TABLE_KNOWLEDGE_NODE_SCOPES}" (nodeId,scopeNodeId,addedAt) VALUES (?,?,?)`,
8351
- args: [
8352
- nodeId,
8353
- scopeNodeId,
8354
- addedAt.toISOString()
8355
- ]
8356
- });
7977
+ async dangerouslyClearAll() {
7978
+ await this.#pages.clearAll();
8357
7979
  }
8358
- /**
8359
- * Move a node's identity memberships from `from` to `to` without touching structural
8360
- * placements added by `#placeNodeInScopes`, which a scope change must not erase.
8361
- */
8362
- async #swapIdentityScopes(executor, nodeId, from, to, addedAt) {
8363
- const next = await this.#resolveScopeNodeIds(executor, to);
8364
- for (const scopeNodeId of await this.#resolveScopeNodeIds(executor, from)) {
8365
- if (next.includes(scopeNodeId)) continue;
8366
- await executor.execute({
8367
- sql: `DELETE FROM "${TABLE_KNOWLEDGE_NODE_SCOPES}" WHERE nodeId=? AND scopeNodeId=?`,
8368
- args: [nodeId, scopeNodeId]
8369
- });
8370
- }
8371
- for (const scopeNodeId of next) await executor.execute({
8372
- sql: `INSERT OR IGNORE INTO "${TABLE_KNOWLEDGE_NODE_SCOPES}" (nodeId,scopeNodeId,addedAt) VALUES (?,?,?)`,
8373
- args: [
8374
- nodeId,
8375
- scopeNodeId,
8376
- addedAt.toISOString()
8377
- ]
8378
- });
7980
+ async #inspectPages(tx) {
7981
+ return inspectKnowledgePagesSchema(await this.#pagesSnapshot(tx));
8379
7982
  }
8380
- /**
8381
- * Additive structural placement: every address must resolve to a live scope node
8382
- * (unlike identity membership, an unknown address is a caller error, not a lazy
8383
- * materialization miss). Runs inside the caller's transaction, so a throw aborts
8384
- * the whole mutation.
8385
- */
8386
- async #placeNodeInScopes(executor, nodeId, addresses, addedAt) {
8387
- for (const address of addresses ?? []) {
8388
- const scopeNodeId = (await executor.execute({
8389
- 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`,
8390
- args: [address]
8391
- })).rows[0]?.scopeNodeId;
8392
- if (scopeNodeId == null) throw new KnowledgeNotFoundError("scope", address);
8393
- await executor.execute({
8394
- sql: `INSERT OR IGNORE INTO "${TABLE_KNOWLEDGE_NODE_SCOPES}" (nodeId,scopeNodeId,addedAt) VALUES (?,?,?)`,
8395
- args: [
8396
- nodeId,
8397
- String(scopeNodeId),
8398
- addedAt.toISOString()
8399
- ]
8400
- });
7983
+ async #pagesSnapshot(tx) {
7984
+ const tableNames = (await tx.execute({ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'mastra\\_knowledge\\_%' ESCAPE '\\'" })).rows.map((row) => String(row.name));
7985
+ let schemaVersion;
7986
+ if (tableNames.includes("mastra_knowledge_access_state")) {
7987
+ const state = await tx.execute({ sql: `SELECT schemaVersion FROM "${TABLE_KNOWLEDGE_PAGES_STATE}" WHERE id = 'knowledge'` });
7988
+ if (state.rows[0]) schemaVersion = Number(state.rows[0].schemaVersion);
8401
7989
  }
7990
+ return {
7991
+ tableNames,
7992
+ schemaVersion
7993
+ };
8402
7994
  }
8403
- async #replaceRecordScopes(executor, recordId, addresses, addedAt) {
8404
- await executor.execute({
8405
- sql: `DELETE FROM "${TABLE_KNOWLEDGE_RECORD_SCOPES}" WHERE recordId=?`,
8406
- args: [recordId]
8407
- });
8408
- for (const scopeNodeId of await this.#resolveScopeNodeIds(executor, addresses)) await executor.execute({
8409
- sql: `INSERT OR IGNORE INTO "${TABLE_KNOWLEDGE_RECORD_SCOPES}" (recordId,scopeNodeId,addedAt) VALUES (?,?,?)`,
8410
- args: [
8411
- recordId,
8412
- scopeNodeId,
8413
- addedAt.toISOString()
8414
- ]
8415
- });
7995
+ async inspectSchema() {
7996
+ return this.#inspectPages(this.#client);
8416
7997
  }
8417
- async #replaceMentions(tx, sourceType, sourceId, text, resolutionScope, defaultScope) {
8418
- await tx.execute({
8419
- sql: `DELETE FROM "${TABLE_KNOWLEDGE_MENTIONS}" WHERE sourceType=? AND sourceId=?`,
8420
- args: [sourceType, sourceId]
8421
- });
8422
- for (const name of parseKnowledgeWikilinks(text)) {
8423
- let node = await this.#resolveNode(tx, name, resolutionScope);
8424
- if (!node) {
8425
- node = await this.#getNodeByName(tx, name, defaultScope);
8426
- if (node) node = await this.#resolveTerminalNode(tx, node.id);
8427
- if (!node) {
8428
- const now = /* @__PURE__ */ new Date();
8429
- node = {
8430
- id: crypto.randomUUID(),
8431
- type: "node",
8432
- name,
8433
- kind: "node",
8434
- scope: defaultScope,
8435
- version: 1,
8436
- createdAt: now,
8437
- updatedAt: now
8438
- };
8439
- await tx.execute({
8440
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_NODES}" (id,type,name,canonicalName,kind,content,isScope,scope,scopeKey,version,mergedInto,createdAt,updatedAt) VALUES (?,?,?,?,?,NULL,FALSE,jsonb(?),?,?,NULL,?,?)`,
8441
- args: [
8442
- node.id,
8443
- "node",
8444
- node.name,
8445
- canonicalName(node.name),
8446
- node.kind,
8447
- JSON.stringify(defaultScope),
8448
- knowledgeScopeKey(defaultScope),
8449
- 1,
8450
- now.toISOString(),
8451
- now.toISOString()
8452
- ]
8453
- });
8454
- await this.#replaceNodeScopes(tx, node.id, defaultScope, now);
8455
- await this.#activity(tx, "node-created", "node", node.id, defaultScope);
8456
- await this.#outbox(tx, "node", node.id, "upsert", 1, defaultScope);
8457
- }
8458
- }
7998
+ async init() {
7999
+ await this.#transaction(async (tx) => {
8000
+ for (const table of legacyKnowledgeTablesToDrop(await this.#pagesSnapshot(tx))) await tx.execute(`DROP TABLE IF EXISTS "${table}"`);
8001
+ const inspection = await this.#inspectPages(tx);
8002
+ if (inspection.status === "incompatible-reset-required") throw new KnowledgeSchemaResetRequiredError(inspection);
8003
+ for (const statement of KNOWLEDGE_PAGE_DDL) await tx.execute(statement);
8459
8004
  await tx.execute({
8460
- sql: `INSERT OR IGNORE INTO "${TABLE_KNOWLEDGE_MENTIONS}" (sourceType,sourceId,recordId) VALUES (?,?,?)`,
8461
- args: [
8462
- sourceType,
8463
- sourceId,
8464
- node.id
8465
- ]
8005
+ sql: `INSERT OR IGNORE INTO "${TABLE_KNOWLEDGE_PAGES_STATE}" (id, schemaVersion) VALUES ('knowledge', ?)`,
8006
+ args: [4]
8466
8007
  });
8467
- }
8468
- }
8469
- async #activity(executor, action, recordType, recordId, scope, sourceThreadId) {
8470
- const now = /* @__PURE__ */ new Date();
8471
- const [contextScopeId] = await this.#resolveScopeNodeIds(executor, scope);
8472
- await executor.execute({
8473
- sql: `INSERT INTO "${TABLE_KNOWLEDGE_ACTIVITY}" (id,action,targetType,targetId,contextScopeId,recordType,recordId,scope,scopeKey,sourceThreadId,createdAt) VALUES (?,?,?,?,?,?,?,jsonb(?),?,?,?)`,
8474
- args: [
8475
- createKnowledgeUlid(),
8476
- action,
8477
- recordType,
8478
- recordId,
8479
- contextScopeId ?? null,
8480
- recordType,
8481
- recordId,
8482
- JSON.stringify(scope),
8483
- knowledgeScopeKey(scope),
8484
- sourceThreadId ?? null,
8485
- now.toISOString()
8486
- ]
8487
8008
  });
8488
8009
  }
8489
- async #outbox(executor, documentType, id, operation, version, scope) {
8490
- const documentId = knowledgeSemanticDocumentId(documentType, id);
8491
- const idempotencyKey = knowledgeSemanticIdempotencyKey(documentId, operation, version);
8492
- const now = /* @__PURE__ */ new Date();
8493
- await executor.execute({
8494
- sql: `INSERT OR IGNORE 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)`,
8495
- args: [
8496
- createKnowledgeUlid(),
8497
- idempotencyKey,
8498
- documentId,
8499
- documentType,
8500
- operation,
8501
- JSON.stringify(scope),
8502
- knowledgeScopeKey(scope),
8503
- now.toISOString(),
8504
- now.toISOString()
8505
- ]
8010
+ async dangerouslyReset() {
8011
+ await withClientWriteLock(this.#client, async () => {
8012
+ await this.#client.batch([...KNOWLEDGE_RESETTABLE_TABLE_NAMES, KNOWLEDGE_PAGE_TABLES.pinAudiences].map((table) => ({
8013
+ sql: `DROP TABLE IF EXISTS "${table}"`,
8014
+ args: []
8015
+ })), "write");
8506
8016
  });
8017
+ await this.init();
8018
+ }
8019
+ materializeScope(input) {
8020
+ return this.#pages.materializeScope(input);
8021
+ }
8022
+ listScopeDeclarations() {
8023
+ return this.#pages.listScopeDeclarations();
8024
+ }
8025
+ renameScopeDeclaration(input) {
8026
+ return this.#pages.renameScopeDeclaration(input);
8027
+ }
8028
+ getScopesByAddress(input) {
8029
+ return this.#pages.getScopesByAddress(input);
8030
+ }
8031
+ listChildScopes(input) {
8032
+ return this.#pages.listChildScopes(input);
8033
+ }
8034
+ getPage(input) {
8035
+ return this.#pages.getPage(input);
8036
+ }
8037
+ getPageByPath(input) {
8038
+ return this.#pages.getPageByPath(input);
8039
+ }
8040
+ findPagesByName(input) {
8041
+ return this.#pages.findPagesByName(input);
8042
+ }
8043
+ listChildPages(input) {
8044
+ return this.#pages.listChildPages(input);
8045
+ }
8046
+ listPages(input) {
8047
+ return this.#pages.listPages(input);
8048
+ }
8049
+ createPage(input) {
8050
+ return this.#pages.createPage(input);
8051
+ }
8052
+ updatePage(input) {
8053
+ return this.#pages.updatePage(input);
8054
+ }
8055
+ movePage(input) {
8056
+ return this.#pages.movePage(input);
8057
+ }
8058
+ mergePages(input) {
8059
+ return this.#pages.mergePages(input);
8060
+ }
8061
+ deletePage(input) {
8062
+ return this.#pages.deletePage(input);
8063
+ }
8064
+ getNote(input) {
8065
+ return this.#pages.getNote(input);
8066
+ }
8067
+ listNotes(input) {
8068
+ return this.#pages.listNotes(input);
8069
+ }
8070
+ countNotes(input) {
8071
+ return this.#pages.countNotes(input);
8072
+ }
8073
+ listNotesMentioning(input) {
8074
+ return this.#pages.listNotesMentioning(input);
8075
+ }
8076
+ addNote(input) {
8077
+ return this.#pages.addNote(input);
8078
+ }
8079
+ restampNote(input) {
8080
+ return this.#pages.restampNote(input);
8081
+ }
8082
+ removeNote(input) {
8083
+ return this.#pages.removeNote(input);
8084
+ }
8085
+ restoreNote(input) {
8086
+ return this.#pages.restoreNote(input);
8087
+ }
8088
+ searchPages(input) {
8089
+ return this.#pages.searchPages(input);
8090
+ }
8091
+ listPageActivity(input) {
8092
+ return this.#pages.listPageActivity(input);
8093
+ }
8094
+ addPinAudience(input) {
8095
+ return this.#pages.addPinAudience(input);
8096
+ }
8097
+ removePinAudience(input) {
8098
+ return this.#pages.removePinAudience(input);
8099
+ }
8100
+ getPages(input) {
8101
+ return this.#pages.getPages(input);
8102
+ }
8103
+ listPins(input) {
8104
+ return this.#pages.listPins(input);
8105
+ }
8106
+ async #transaction(operation) {
8107
+ return this.#db.executeWriteOperationWithRetry(() => withClientWriteLock(this.#client, async () => {
8108
+ const tx = await this.#client.transaction("write");
8109
+ try {
8110
+ const result = await operation(tx);
8111
+ await tx.commit();
8112
+ return result;
8113
+ } catch (error) {
8114
+ if (!tx.closed) await tx.rollback();
8115
+ throw error;
8116
+ }
8117
+ }), "write knowledge state");
8507
8118
  }
8508
8119
  };
8509
8120
  // src/storage/domains/mcp-clients/index.ts