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