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