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