import { createHash, randomUUID } from "node:crypto"; import { FileAsset, KnowledgeFilePreparationResult, AgentLearningDefaults, AgentLearningOverridePatch, AgentInstructionSaveRequest, AgentInstructionReviewRequest, AgentInstructionReceipt, AgentInstructionReviewItem, WorkspaceInstructionPolicyTarget, KnowledgeEntryListRequest, KnowledgeReviewBatch, KnowledgeReviewBatchListRequest, KnowledgeEntryBatchReviewRequest, KnowledgeTaskNotePromotionRequest, KnowledgeEntryRecord, KnowledgeEntryReach, KnowledgeEntryReachRecord, KnowledgeEntryReviewRequest, KnowledgeEntryRestoreRequest, KnowledgeEntrySaveRequest, KnowledgeEntrySummary, KnowledgeIndexStatus, KnowledgeEntryWriteReceipt, type AgentLearningContext, type KnowledgeEntryScope, } from "@opengeni/contracts"; import { sql } from "drizzle-orm"; import { z } from "zod"; import { nestedPostgresSqlState, safeDatabaseErrorFacts } from "./persistence-errors"; import { isKnowledgeLearningScopeGuardError, KnowledgeLearningScopeChangedError, } from "./knowledge-learning-errors"; export { KnowledgeLearningScopeChangedError } from "./knowledge-learning-errors"; import { rawRows, withWorkspaceRls, withWorkspaceSubjectRls, type Database } from "./database"; import { fromPostgresLosslessJson, fromPostgresLosslessText, LOSSLESS_CONTENT_CODEC_VERSION, toPostgresLosslessJson, toPostgresLosslessText, } from "./lossless-json"; /** Trusted host claims. Never deserialize this context from tool/request input. */ export type KnowledgeActor = | { kind: "service"; principalKind: "service" | "api_key" | "configured_key" | "mcp_gateway"; subjectId: string; writeScopes: Array<"workspace" | "organization">; review: false; settingsScopes: []; } | { kind: "human"; principalKind: "human_session"; subjectId: string; writeScopes: KnowledgeEntryScope[]; settingsScopes: Array<"workspace" | "personal">; review: boolean; } | { kind: "agent"; sessionId: string; turnId: string; attemptId: string; executionGeneration: number; }; export type KnowledgeContext = { accountId: string; workspaceId: string; actor: KnowledgeActor }; async function inKnowledgeContext( db: Database, context: KnowledgeContext, fn: (tx: Database) => Promise, ) { if (context.actor.kind === "agent") return withWorkspaceRls(db, context.workspaceId, fn); return withWorkspaceSubjectRls(db, context.workspaceId, context.actor.subjectId, async (tx) => { await tx.execute( sql`SELECT set_config('opengeni.principal_kind', ${context.actor.kind === "agent" ? "agent_attempt" : context.actor.principalKind}, true)`, ); return fn(tx); }); } /** The supplied entry id belongs to an entry this caller cannot see or did not mean. */ export class KnowledgeEntryIdTakenError extends Error { readonly code = "knowledge_entry_id_taken"; constructor() { super( "This entryId already belongs to another Knowledge entry. Omit entryId to create a new entry, or pass an existing entry's id and current version to correct it.", ); this.name = "KnowledgeEntryIdTakenError"; } } /** A correction must name its entry; only a create may leave the id to the host. */ export class KnowledgeEntryIdRequiredError extends Error { readonly code = "knowledge_entry_id_required"; constructor() { super("entryId is required when expectedVersion is above 0. Omit it only to create an entry."); this.name = "KnowledgeEntryIdRequiredError"; } } /** * Stable per operation, so an exact retry of a create resolves the same entry and * replays its receipt instead of creating a duplicate. */ export function knowledgeEntryIdForOperation(accountId: string, operationId: string): string { const bytes = createHash("sha256") .update(`opengeni:knowledge-entry:${accountId}:${operationId}`) .digest() .subarray(0, 16); bytes[6] = (bytes[6]! & 0x0f) | 0x80; // RFC 9562 version 8 (custom) bytes[8] = (bytes[8]! & 0x3f) | 0x80; // RFC 9562 variant const hex = bytes.toString("hex"); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; } function resolveWriteEntryId( context: KnowledgeContext, request: { operationId: string; entryId?: string | undefined; expectedVersion: number }, ): string { if (request.entryId) return request.entryId; if (request.expectedVersion !== 0) throw new KnowledgeEntryIdRequiredError(); return knowledgeEntryIdForOperation(context.accountId, request.operationId); } async function apply(db: Database, context: KnowledgeContext, request: Record) { try { return await inKnowledgeContext(db, context, (tx) => applyIn(tx, context, request)); } catch (error) { // An entry outside the caller's RLS scope still owns its primary key, so a // colliding create surfaces as this unique violation, not as operation reuse. if (safeDatabaseErrorFacts(error).constraint === "knowledge_entries_pkey") { throw new KnowledgeEntryIdTakenError(); } throw error; } } async function applyIn(tx: Database, context: KnowledgeContext, request: Record) { const [row] = await rawRows<{ receipt: unknown }>( tx, sql` SELECT knowledge_entry_apply(${context.accountId}::uuid,${context.workspaceId}::uuid, ${JSON.stringify(context.actor)}::jsonb,${JSON.stringify(request)}::jsonb) AS receipt`, ); return KnowledgeEntryWriteReceipt.parse(row?.receipt); } /** Freeze before model execution; retries of the logical turn recover the same policy. */ export async function freezeAgentLearningPolicy(db: Database, context: KnowledgeContext) { if (context.actor.kind !== "agent") throw new Error("Learning snapshots require an exact agent attempt"); return inKnowledgeContext(db, context, async (tx) => { const [row] = await rawRows<{ policy: unknown }>( tx, sql`SELECT knowledge_entry_read(${context.accountId}::uuid, ${context.workspaceId}::uuid,${JSON.stringify(context.actor)}::jsonb,'{"operation":"policy"}'::jsonb) AS policy`, ); return z .object({ defaultScope: z.enum(["workspace", "personal"]), subjectId: z.string().nullable(), effective: AgentLearningDefaults, }) .passthrough() .parse(row?.policy); }).catch((error: unknown) => { if (isKnowledgeLearningScopeGuardError(error)) throw new KnowledgeLearningScopeChangedError(error); throw error; }); } export async function saveKnowledgeEntry( db: Database, context: KnowledgeContext, input: KnowledgeEntrySaveRequest, ) { const request = KnowledgeEntrySaveRequest.parse(input); return apply(db, context, { ...request, entryId: resolveWriteEntryId(context, request), operation: "save", entry: toPostgresLosslessJson(request.entry), codecVersion: LOSSLESS_CONTENT_CODEC_VERSION, preview: toPostgresLosslessText(request.entry.content.slice(0, 512)), searchText: toPostgresLosslessText(`${request.entry.title}\n${request.entry.content}`), }); } export async function promoteTaskNoteToKnowledge( db: Database, context: KnowledgeContext, input: KnowledgeTaskNotePromotionRequest, ) { const request = KnowledgeTaskNotePromotionRequest.parse(input); return apply(db, context, { ...request, entryId: resolveWriteEntryId(context, request), operation: "promote_note", }); } export async function reviewKnowledgeEntry( db: Database, context: KnowledgeContext, input: KnowledgeEntryReviewRequest, ) { const { decision, entry, ...request } = KnowledgeEntryReviewRequest.parse(input); return apply(db, context, { ...request, operation: entry ? "approve_edit" : decision, ...(entry ? { entry: toPostgresLosslessJson(entry), codecVersion: LOSSLESS_CONTENT_CODEC_VERSION, preview: toPostgresLosslessText(entry.content.slice(0, 512)), searchText: toPostgresLosslessText(`${entry.title}\n${entry.content}`), } : {}), }); } /** Atomic review of exact revisions; dependencies publish before their findings. */ export async function reviewKnowledgeEntries( db: Database, context: KnowledgeContext, input: KnowledgeEntryBatchReviewRequest, ) { const request = KnowledgeEntryBatchReviewRequest.parse(input); return inKnowledgeContext(db, context, async (tx) => { // Same lock/order as individual publication. No unrelated reviewer can // change a selected revision between ordering, validation and application. await tx.execute( sql`SELECT 1 FROM workspaces WHERE id=${context.workspaceId}::uuid AND account_id=${context.accountId}::uuid FOR KEY SHARE`, ); await tx.execute( sql`SELECT pg_advisory_xact_lock(hashtextextended(${`knowledge-publication:${context.accountId}`},0))`, ); const remaining = new Map(request.entries.map((entry) => [entry.entryId, entry])); const pending = new Map(); for (const entry of request.entries) { const record = await getKnowledgeEntry(tx, context, entry.entryId, { view: "needs_review" }); if (record) pending.set(entry.entryId, record); } const receipts: KnowledgeEntryWriteReceipt[] = []; while (remaining.size) { let advanced = false; for (const [id, entry] of remaining) { const record = pending.get(id); const content = entry.entry ?? record?.revision.entry; const dependencies = entry.decision === "approve" && record?.revision.change !== "archive" && content ? [ ...(content.evidence ?? []) .filter( (evidence) => pending.get(evidence.entryId)?.revision.id === evidence.revisionId, ) .map((evidence) => evidence.entryId), ...[ ...(content.groupIds ?? []), ...(content.relationships ?? []).map((relation) => relation.entryId), ].filter( (dependency) => pending.has(dependency) && !pending.get(dependency)?.publishedRevisionId, ), ] : []; if ( dependencies.some( (dependency) => remaining.has(dependency) && remaining.get(dependency)?.decision === "approve", ) ) continue; receipts.push(await reviewKnowledgeEntry(tx, context, entry)); remaining.delete(id); advanced = true; } if (!advanced) throw new z.ZodError([ { code: "custom", path: ["entries"], message: "Review contains a dependency cycle; review the linked entries first", }, ]); } return { receipts }; }); } export async function restoreKnowledgeEntry( db: Database, context: KnowledgeContext, input: KnowledgeEntryRestoreRequest, ) { const request = KnowledgeEntryRestoreRequest.parse(input); return inKnowledgeContext(db, context, async (tx) => { await lockKnowledgePublication(tx, context); // Read before the restore: what the archive this restore undoes took along. const cascade = RestoreCascade.safeParse( await cascadeRead(tx, context, request.entryId, "restore"), ); const receipt = await applyIn(tx, context, { ...request, operation: "restore" }); if (!cascade.success || receipt.outcome !== "published" || receipt.replayed) return receipt; // Parents first; a member whose collection or evidence isn't back yet waits a round. let pending = cascade.data.members; while (pending.length) { const left: typeof pending = []; for (const member of pending) { const restored = await skipUnavailable(tx, (savepoint) => applyIn(savepoint, context, { operationId: archivedWithOperationId(request.operationId, member.entryId), entryId: member.entryId, revisionId: member.publishedRevisionId, expectedVersion: member.version, operation: "restore", }), ); if (!restored) left.push(member); } if (left.length === pending.length) break; pending = left; } return receipt; }); } /** * Archiving a collection also archives what is only inside it: its * sub-collections and the entries that no live collection or entry outside it * holds or cites. Otherwise they surface at the top level and stay in use, so * the collection seems to come back. Undo and restore bring the same set back. */ export async function archiveKnowledgeEntry( db: Database, context: KnowledgeContext, input: { operationId: string; entryId: string; expectedVersion: number; }, ) { const request = z .object({ operationId: z.uuid(), entryId: z.uuid(), expectedVersion: z.number().int().positive(), }) .strict() .parse(input); return inKnowledgeContext(db, context, async (tx) => { // Lock before reading the tree, so no publication changes it meanwhile. await lockKnowledgePublication(tx, context); const cascade = ArchiveCascade.safeParse( await cascadeRead(tx, context, request.entryId, "archive"), ); const receipt = await applyIn(tx, context, { ...request, operation: "archive" }); if (!cascade.success || receipt.outcome !== "archived" || receipt.replayed) return receipt; const archived = new Set([request.entryId]); const kept = new Set(); for (const member of onlyInside(request.entryId, cascade.data.members)) { // A collection or citing entry that stayed live keeps what it holds. const taken = member.parentIds.every((id) => archived.has(id)) && !member.citedByIds.some((id) => kept.has(id)) && (await skipUnavailable(tx, (savepoint) => applyIn(savepoint, context, { operationId: archivedWithOperationId(request.operationId, member.entryId), entryId: member.entryId, expectedVersion: member.version, operation: "archive", }), )); if (taken && taken.outcome === "archived") archived.add(member.entryId); else kept.add(member.entryId); } return receipt; }); } const ArchiveCascade = z.object({ members: z.array( z.object({ entryId: z.uuid(), version: z.number().int().positive(), parentIds: z.array(z.uuid()), citedByIds: z.array(z.uuid()), heldElsewhere: z.boolean(), }), ), }); type CascadeMember = z.infer["members"][number]; const RestoreCascade = z.object({ members: z.array( z.object({ entryId: z.uuid(), version: z.number().int().positive(), publishedRevisionId: z.uuid(), }), ), }); /** Same lock and order as a single publication (knowledge_entry_apply). */ async function lockKnowledgePublication(tx: Database, context: KnowledgeContext) { await tx.execute( sql`SELECT 1 FROM workspaces WHERE id=${context.workspaceId}::uuid AND account_id=${context.accountId}::uuid FOR KEY SHARE`, ); await tx.execute( sql`SELECT pg_advisory_xact_lock(hashtextextended(${`knowledge-publication:${context.accountId}`},0))`, ); } /** * What a collection's archive or restore takes along (migration 1378), read * through the authorization seam. Null before that migration: no cascade. */ async function cascadeRead( tx: Database, context: KnowledgeContext, entryId: string, mode: "archive" | "restore", ) { return skipUnavailable(tx, async (savepoint) => { const [row] = await rawRows<{ result: unknown }>( savepoint, sql`SELECT knowledge_entry_read(${context.accountId}::uuid,${context.workspaceId}::uuid, ${JSON.stringify(context.actor)}::jsonb, ${JSON.stringify({ operation: "collection_cascade", mode, entryId })}::jsonb) AS result`, ); return row?.result ?? null; }); } /** * Members no live collection or entry outside the archived set holds or * cites, ordered so collections and citing entries come before what they hold. */ function onlyInside(collectionId: string, members: CascadeMember[]): CascadeMember[] { const inside = new Map( members.filter((member) => !member.heldElsewhere).map((member) => [member.entryId, member]), ); const archiving = (id: string) => id === collectionId || inside.has(id); for (let changed = true; changed;) { changed = false; for (const member of inside.values()) { if (![...member.parentIds, ...member.citedByIds].every(archiving)) { inside.delete(member.entryId); changed = true; } } } const ordered: CascadeMember[] = []; const placed = new Set([collectionId]); while (ordered.length < inside.size) { const before = ordered.length; for (const member of inside.values()) { if (placed.has(member.entryId)) continue; if ([...member.parentIds, ...member.citedByIds].every((id) => placed.has(id))) { ordered.push(member); placed.add(member.entryId); } } // Entries that cite each other: the rest in any order. if (ordered.length === before) { ordered.push(...[...inside.values()].filter((member) => !placed.has(member.entryId))); break; } } return ordered; } /** * A member's operation in an archive or restore that takes it along. Migration * 1378 derives the same id in SQL to find what an archive took along. */ function archivedWithOperationId(operationId: string, entryId: string) { const hex = createHash("md5") .update(`opengeni:knowledge-archived-with:${operationId}:${entryId}`) .digest("hex"); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-8${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20)}`; } /** Members the caller can't change, or that changed meanwhile, keep their state. */ async function skipUnavailable( tx: Database, run: (savepoint: Database) => Promise, ): Promise { try { return await tx.transaction((savepoint) => run(savepoint)); } catch (error) { const state = nestedPostgresSqlState(error); if (state === "42501" || state === "40001" || state === "22023") return null; throw error; } } /** * Where an entry this workspace has works, and whether the person asking may * change it (migration 1196). Null when this workspace doesn't have the entry. * People and services only: agents use the entries their workspace has. */ export async function getKnowledgeEntryReach( db: Database, context: KnowledgeContext, entryId: string, ): Promise { const request = { operation: "reach", entryId: z.uuid().parse(entryId) }; return inKnowledgeContext(db, context, async (tx) => { const [row] = await rawRows<{ result: unknown }>( tx, sql` SELECT knowledge_entry_read(${context.accountId}::uuid,${context.workspaceId}::uuid, ${JSON.stringify(context.actor)}::jsonb,${JSON.stringify(request)}::jsonb) AS result`, ); return row?.result == null ? null : KnowledgeEntryReachRecord.parse(row.result); }); } const KnowledgeEntryReachChange = z .object({ entryId: z.uuid(), scope: z.enum(["organization", "personal"]), originWorkspaceId: z.uuid(), reach: KnowledgeEntryReach, previous: KnowledgeEntryReach, }) .strict(); /** * Change where an organization or personal entry works. The caller has * checked the listed workspaces: shared workspaces of the organization for an * organization entry, the owner's own workspaces for a personal one. The * workspace it was added in always has it and is never stored. It is not a * revision, so the entry keeps its version; the change is audited in the same * transaction. People and services with write access to the entry's scope. */ export async function setKnowledgeEntryReach( db: Database, context: KnowledgeContext, input: { entryId: string; reach: KnowledgeEntryReach }, ): Promise { const request = { operation: "reach", operationId: randomUUID(), entryId: z.uuid().parse(input.entryId), reach: KnowledgeEntryReach.parse(input.reach), }; return inKnowledgeContext(db, context, async (tx) => { const [row] = await rawRows<{ receipt: unknown }>( tx, sql` SELECT knowledge_entry_apply(${context.accountId}::uuid,${context.workspaceId}::uuid, ${JSON.stringify(context.actor)}::jsonb,${JSON.stringify(request)}::jsonb) AS receipt`, ); const change = KnowledgeEntryReachChange.parse(row?.receipt); await rawRows( tx, sql`INSERT INTO audit_events(account_id, workspace_id, subject_id, action, target_type, target_id, metadata) VALUES (${context.accountId}::uuid, ${context.workspaceId}::uuid, ${context.actor.kind === "agent" ? null : context.actor.subjectId}, 'knowledge.reach.changed', 'knowledge_entry', ${change.entryId}, ${JSON.stringify({ scope: change.scope, from: change.previous, to: change.reach })}::jsonb)`, ); return { entryId: change.entryId, scope: change.scope, originWorkspaceId: change.originWorkspaceId, reach: change.reach, canChange: true, }; }); } const StoredProjection = z .object({ revision: z .object({ entry: z.unknown().nullable(), title: z.string(), preview: z.string(), bodyCodecVersion: z.number().nullable(), previewCodecVersion: z.number().nullable(), }) .passthrough(), }) .passthrough(); function decodeProjection(value: unknown, full: true): KnowledgeEntryRecord; function decodeProjection(value: unknown, full: false): KnowledgeEntrySummary; function decodeProjection(value: unknown, full: boolean) { const stored = StoredProjection.parse(value); const { bodyCodecVersion, previewCodecVersion, entry, title, preview, kind, groupIds, sourceKind, ...revision } = stored.revision; const { revision: _storedRevision, score, excerpts, ...record } = stored; const decodedExcerpts = z .array( z.object({ field: z.enum(["title", "content"]), start: z.number().int().nonnegative(), end: z.number().int().nonnegative(), text: z.string(), codecVersion: z.number().nullable(), }), ) .parse(excerpts ?? []) .map(({ codecVersion, text, ...excerpt }) => ({ ...excerpt, text: fromPostgresLosslessText(text, codecVersion), })); return full ? KnowledgeEntryRecord.parse({ ...record, revision: { ...revision, entry: fromPostgresLosslessJson(entry, bodyCodecVersion) }, }) : KnowledgeEntrySummary.parse({ ...record, score, excerpts: decodedExcerpts, revision: { ...revision, kind, groupIds, sourceKind, title: fromPostgresLosslessJson(title, bodyCodecVersion), preview: fromPostgresLosslessText(preview, previewCodecVersion), }, }); } /** The owner-definer seam rechecks canonical visibility for every exact revision. */ async function withIndexStatus( db: Database, context: KnowledgeContext, entries: T[], view: "published" | "needs_review" | "archived" | "rejected", ): Promise { if (view === "archived" || view === "rejected") return entries; const items = entries .filter( (entry) => ("entry" in entry.revision ? entry.revision.entry.kind : entry.revision.kind) === "source", ) .map((entry) => ({ entryId: entry.id, revisionId: entry.revision.id })); if (!items.length) return entries; const statuses = await inKnowledgeContext(db, context, async (tx) => { const [row] = await rawRows<{ result: unknown }>( tx, sql`SELECT knowledge_visible_index_status(${context.accountId}::uuid, ${context.workspaceId}::uuid,${JSON.stringify(context.actor)}::jsonb, ${JSON.stringify(items)}::jsonb,${view}) AS result`, ); return z .array(z.object({ entryId: z.uuid(), revisionId: z.uuid(), status: KnowledgeIndexStatus })) .parse(row?.result); }); const byRevision = new Map(statuses.map((item) => [item.revisionId, item.status])); return entries.map((entry) => { const indexStatus = byRevision.get(entry.revision.id); return indexStatus ? { ...entry, indexStatus } : entry; }); } async function read( db: Database, context: KnowledgeContext, request: Record, ): Promise { return inKnowledgeContext(db, context, async (tx) => { const [row] = await rawRows<{ result: unknown }>( tx, sql` SELECT knowledge_entry_read(${context.accountId}::uuid,${context.workspaceId}::uuid, ${JSON.stringify(context.actor)}::jsonb,${JSON.stringify(request)}::jsonb) AS result`, ); return z.array(z.unknown()).parse(row?.result); }); } export async function getKnowledgeEntry( db: Database, context: KnowledgeContext, entryId: string, options: { revisionId?: string | undefined; view?: "published" | "needs_review" | "archived" | "rejected" | undefined; } = {}, ): Promise { const request = z .object({ entryId: z.uuid(), revisionId: z.uuid().optional(), view: z.enum(["published", "needs_review", "archived", "rejected"]).optional(), }) .strict() .parse({ entryId, ...options }); const rows = await read(db, context, { ...request, operation: "get", limit: 1 }); if (!rows[0]) return null; const record = decodeProjection(rows[0], true); return (await withIndexStatus(db, context, [record], request.view ?? "published"))[0]!; } /** * Read a bounded set of current entries in input order. Every entry still goes * through the native actor, scope and transitive-evidence authorization seam; * only the transaction setup and round trips are shared. Missing or no longer * visible entries retain their null slot. This is not a historical revision read. */ export async function getKnowledgeEntries( db: Database, context: KnowledgeContext, entryIds: string[], options: { view?: "published" | "needs_review" | "archived" | "rejected" | undefined; } = {}, ): Promise> { const { entryIds: ids, ...request } = z .object({ entryIds: z.array(z.uuid()).max(50), view: z.enum(["published", "needs_review", "archived", "rejected"]).optional(), }) .strict() .parse({ entryIds, ...options }); if (!ids.length) return []; const records = await inKnowledgeContext(db, context, async (tx) => { const rows = await rawRows<{ result: unknown }>( tx, sql`SELECT knowledge_entry_read(${context.accountId}::uuid,${context.workspaceId}::uuid, ${JSON.stringify(context.actor)}::jsonb, jsonb_build_object('operation','get','limit',1,'entryId',entry.id) || ${JSON.stringify(request)}::jsonb) AS result FROM jsonb_array_elements_text(${JSON.stringify(ids)}::jsonb) WITH ORDINALITY AS entry(id,position) ORDER BY entry.position`, ); return rows.map((row) => { const values = z.array(z.unknown()).parse(row.result); return values[0] ? decodeProjection(values[0], true) : null; }); }); const decorated = await withIndexStatus( db, context, records.filter((record) => record !== null), request.view ?? "published", ); let index = 0; return records.map((record) => (record ? decorated[index++]! : null)); } const Cursor = z .object({ v: z.literal(3), afterId: z.uuid(), afterScore: z.number().finite(), /** The order key of the last row: latest change, or creation. A function * from before the order key returns none; its pages continue in id order. */ afterOrderedAt: z.iso.datetime({ offset: true }).optional(), queryHash: z.string().length(64), }) .strict(); /** The order key a list read returns beside each row; not part of the projection. */ const OrderedRow = z .object({ orderedAt: z.iso.datetime({ offset: true }).optional() }) .passthrough(); function splitOrderedRow(row: unknown): { orderedAt: string | undefined; row: unknown } { const { orderedAt, ...rest } = OrderedRow.parse(row); return { orderedAt, row: rest }; } function encodeCursor(cursor: z.infer): string { return Buffer.from(JSON.stringify(cursor)).toString("base64url"); } export async function listKnowledgeEntries( db: Database, context: KnowledgeContext, input: KnowledgeEntryListRequest = {}, embedding?: { model: string; values: number[] } | undefined, ) { const { cursor, ...request } = KnowledgeEntryListRequest.parse(input); // Newest first: by latest change, or by creation inside an Added window. A // query still ranks by relevance first; the order only breaks ties. const order = request.createdSince ? "created" : "updated"; const queryHash = createHash("sha256") .update(JSON.stringify({ context, request, order, embeddingModel: embedding?.model ?? null })) .digest("hex"); let position: z.infer | null = null; try { position = cursor ? Cursor.parse(JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"))) : null; if (position && position.queryHash !== queryHash) throw new Error("Changed query"); } catch { throw new z.ZodError([ { code: "custom", path: ["cursor"], message: "This search changed. Refresh the results to continue.", }, ]); } // A page that began without an order key continues in its original order. const ordered = !position || position.afterOrderedAt !== undefined; const rows = await read(db, context, { ...request, operation: "list", ...(ordered ? { order } : {}), ...(position ? { afterId: position.afterId, afterScore: position.afterScore, ...(position.afterOrderedAt ? { afterOrderedAt: position.afterOrderedAt } : {}), } : {}), ...(embedding ? { embedding: z.array(z.number().finite()).min(1).max(4096).parse(embedding.values), embeddingModel: embedding.model, } : {}), }); const page = rows.slice(0, request.limit).map(splitOrderedRow); const entries = await withIndexStatus( db, context, page.map(({ orderedAt, row }) => { const entry = decodeProjection(row, false); return order === "updated" && orderedAt ? { ...entry, lastChangedAt: orderedAt } : entry; }), request.view, ); const last = page.at(-1); return { entries, nextCursor: rows.length > request.limit && entries.length && last ? encodeCursor({ v: 3, afterId: entries.at(-1)!.id, afterScore: entries.at(-1)!.score ?? 0, ...(last.orderedAt ? { afterOrderedAt: last.orderedAt } : {}), queryHash, }) : null, }; } export async function listKnowledgeReviewBatches( db: Database, context: KnowledgeContext, input: KnowledgeReviewBatchListRequest = {}, ) { const { cursor, ...request } = KnowledgeReviewBatchListRequest.parse(input); const queryHash = createHash("sha256") .update(JSON.stringify({ context, request, operation: "review_batches", order: "updated" })) .digest("hex"); let position: z.infer | null = null; try { position = cursor ? Cursor.parse(JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"))) : null; if (position && position.queryHash !== queryHash) throw new Error("Changed filter"); } catch { throw new z.ZodError([ { code: "custom", path: ["cursor"], message: "Review groups changed. Refresh to continue." }, ]); } // The newest pending change first. const rows = ( await read(db, context, { ...request, operation: "review_batches", ...(!position || position.afterOrderedAt ? { order: "updated" } : {}), ...(position ? { afterId: position.afterId, ...(position.afterOrderedAt ? { afterOrderedAt: position.afterOrderedAt } : {}), } : {}), }) ).map(splitOrderedRow); const page = rows.slice(0, request.limit); const batches = page.map(({ row }) => KnowledgeReviewBatch.parse(row)); const last = page.at(-1); return { batches, nextCursor: rows.length > request.limit && batches.length && last ? encodeCursor({ v: 3, afterId: batches.at(-1)!.id, afterScore: 0, ...(last.orderedAt ? { afterOrderedAt: last.orderedAt } : {}), queryHash, }) : null, }; } export async function listKnowledgeEntryHistory( db: Database, context: KnowledgeContext, entryId: string, beforeRevision?: number, ) { const request = z .object({ entryId: z.uuid(), beforeRevision: z.number().int().positive().optional() }) .parse({ entryId, beforeRevision }); const rows = await read(db, context, { ...request, operation: "history", limit: 20 }); const entries = rows.slice(0, 20).map((row) => decodeProjection(row, false)); return { entries, beforeRevision: rows.length > 20 ? entries.at(-1)!.revision.number : null, savedByYou: await historySavedBy( db, context, request.entryId, entries.map((entry) => entry.revision.id), ), }; } /** * Of these versions, the ones the person asking saved (migration 1498), so * the history can say "You". Empty for agents and services, and before that * migration. */ async function historySavedBy( db: Database, context: KnowledgeContext, entryId: string, revisionIds: string[], ): Promise { if (context.actor.kind !== "human" || revisionIds.length === 0) return []; const result = await inKnowledgeContext(db, context, (tx) => skipUnavailable(tx, async (savepoint) => { const [row] = await rawRows<{ result: unknown }>( savepoint, sql`SELECT knowledge_entry_read(${context.accountId}::uuid,${context.workspaceId}::uuid, ${JSON.stringify(context.actor)}::jsonb, ${JSON.stringify({ operation: "history_authors", entryId, revisionIds })}::jsonb) AS result`, ); return row?.result ?? null; }), ); return z .array(z.uuid()) .catch([]) .parse(result ?? []); } const SettingsRecord = z.object({ ownerKey: z.string(), contextKey: z.string(), version: z.number().int().nonnegative(), settings: AgentLearningOverridePatch, }); function contextKey(context?: AgentLearningContext) { return context ? `${context.kind}:${context.id}` : "defaults"; } async function manageLearning( db: Database, context: KnowledgeContext, request: Record, ) { return inKnowledgeContext(db, context, async (tx) => { const [row] = await rawRows<{ result: unknown }>( tx, sql` SELECT agent_learning_manage(${context.accountId}::uuid,${context.workspaceId}::uuid, ${JSON.stringify(context.actor)}::jsonb,${JSON.stringify(request)}::jsonb) AS result`, ); return row?.result; }); } export async function getAgentLearningSettings( db: Database, context: KnowledgeContext, scope: "workspace" | "personal" | "context", source?: AgentLearningContext, ) { return SettingsRecord.parse( await manageLearning(db, context, { operation: "read", scope, contextKey: contextKey(source) }), ); } export async function saveAgentLearningSettings( db: Database, context: KnowledgeContext, input: { scope: "workspace" | "personal"; source?: AgentLearningContext | undefined; operationId: string; expectedVersion: number; settings: AgentLearningOverridePatch; }, ) { const request = z .object({ scope: z.enum(["workspace", "personal"]), operationId: z.uuid(), expectedVersion: z.number().int().nonnegative(), }) .parse(input); const settings = input.source ? AgentLearningOverridePatch.parse(input.settings) : AgentLearningDefaults.parse(input.settings); return SettingsRecord.parse( await manageLearning(db, context, { ...request, operation: "save", contextKey: contextKey(input.source), settings, }), ); } export async function listAgentLearningOverrides( db: Database, context: KnowledgeContext, scope: "workspace" | "personal", ) { return z .array( z.object({ contextKey: z.string(), version: z.number().int().positive(), settings: AgentLearningOverridePatch, updatedAt: z.string(), label: z.string(), }), ) .parse(await manageLearning(db, context, { operation: "list", scope })); } async function instructionOperation( db: Database, context: KnowledgeContext, request: Record, ) { return inKnowledgeContext(db, context, async (tx) => { const [row] = await rawRows<{ result: unknown }>( tx, sql`SELECT agent_instruction_apply(${context.accountId}::uuid, ${context.workspaceId}::uuid,${JSON.stringify(context.actor)}::jsonb,${JSON.stringify(request)}::jsonb) AS result`, ); return row?.result; }); } export async function saveAgentInstruction( db: Database, context: KnowledgeContext, input: AgentInstructionSaveRequest, ) { return AgentInstructionReceipt.parse( await instructionOperation(db, context, { ...AgentInstructionSaveRequest.parse(input), operation: "save", }), ); } export async function getAgentInstruction( db: Database, context: KnowledgeContext, target: WorkspaceInstructionPolicyTarget, ) { return z .object({ target: WorkspaceInstructionPolicyTarget, expectedCurrentRevisionId: z.uuid().nullable(), expectedActivationVersion: z.number().int().nonnegative(), content: z.string().nullable(), }) .parse( await instructionOperation(db, context, { operation: "get", target: WorkspaceInstructionPolicyTarget.parse(target), }), ); } export async function reviewAgentInstruction( db: Database, context: KnowledgeContext, input: AgentInstructionReviewRequest, ) { const { decision, ...request } = AgentInstructionReviewRequest.parse(input); return AgentInstructionReceipt.parse( await instructionOperation(db, context, { ...request, operation: decision }), ); } export async function listAgentInstructionReviews( db: Database, context: KnowledgeContext, cursor?: string, ) { const request = z.object({ cursor: z.uuid().optional() }).parse({ cursor }); const rows = z .array(AgentInstructionReviewItem) .parse(await instructionOperation(db, context, { ...request, operation: "list" })); return { entries: rows.slice(0, 50), nextCursor: rows.length > 50 ? rows[49]!.revisionId : null }; } /** Host-only parser boundary. The file metadata is never returned by agent tools. */ export async function inspectKnowledgeFilePreparation( db: Database, context: KnowledgeContext, fileId: string, ) { const value = await knowledgeFilePreparationOperation(db, context, { operation: "inspect", fileId: z.uuid().parse(fileId), }); if (value && typeof value === "object" && "status" in value && value.status === "prepare") { const raw = z.object({ file: z.record(z.string(), z.unknown()) }).parse(value).file; return { status: "prepare" as const, file: knowledgeOriginalFileAsset(raw), }; } return KnowledgeFilePreparationResult.parse(value); } /** Concurrent/recovered preparations converge on the first exact saved source. */ export async function completeKnowledgeFilePreparation( db: Database, context: KnowledgeContext, input: { fileId: string; title: string; content: string; sourceVersion?: string; purpose?: "evidence" | "reference"; }, ) { return KnowledgeFilePreparationResult.parse( await knowledgeFilePreparationOperation(db, context, { operation: "complete", fileId: z.uuid().parse(input.fileId), purpose: z.enum(["evidence", "reference"]).parse(input.purpose ?? "evidence"), ...(input.sourceVersion ? { sourceVersion: z .string() .regex(/^[a-f0-9]{64}$/) .parse(input.sourceVersion), } : {}), title: toPostgresLosslessJson(input.title), content: toPostgresLosslessJson(input.content), preview: toPostgresLosslessText(input.content.slice(0, 512)), searchText: toPostgresLosslessText(`${input.title}\n${input.content}`), codecVersion: LOSSLESS_CONTENT_CODEC_VERSION, }), ); } async function knowledgeFilePreparationOperation( db: Database, context: KnowledgeContext, request: Record, ) { return inKnowledgeContext(db, context, async (tx) => { const [row] = await rawRows<{ result: unknown }>( tx, sql`SELECT knowledge_entry_prepare_file( ${context.accountId}::uuid,${context.workspaceId}::uuid,${JSON.stringify(context.actor)}::jsonb, ${JSON.stringify(request)}::jsonb) AS result`, ); return row?.result; }); } export function knowledgeOriginalFileAsset(raw: Record): FileAsset { return FileAsset.parse({ id: raw.id, workspaceId: raw.workspace_id, status: raw.status, filename: raw.filename, safeFilename: raw.safe_filename, contentType: raw.content_type, sizeBytes: Number(raw.size_bytes), sha256: raw.sha256, bucket: raw.bucket, objectKey: raw.object_key, scope: raw.private_owner_subject_id ? "personal" : "workspace", createdAt: new Date(String(raw.created_at)).toISOString(), updatedAt: new Date(String(raw.updated_at)).toISOString(), }); } /** Exact entry visibility first; origin workspace metadata is not an access grant. */ export async function getKnowledgeOriginalFile( db: Database, context: KnowledgeContext, entryId: string, revisionId?: string, ) { return inKnowledgeContext(db, context, async (tx) => { const request = { operation: "file", entryId: z.uuid().parse(entryId), ...(revisionId ? { revisionId: z.uuid().parse(revisionId) } : {}), }; const [row] = await rawRows<{ result: unknown }>( tx, sql`SELECT knowledge_entry_read(${context.accountId}::uuid, ${context.workspaceId}::uuid,${JSON.stringify(context.actor)}::jsonb,${JSON.stringify(request)}::jsonb) AS result`, ); return row?.result ? knowledgeOriginalFileAsset(z.record(z.string(), z.unknown()).parse(row.result)) : null; }); } /** Finish only a pre-cutover, human-answered remember confirmation. */ export async function confirmLegacyKnowledge( db: Database, context: KnowledgeContext, request: { operationId: string; claimId: string; humanInputRequestId: string; }, ) { const input = z .object({ operationId: z.uuid(), claimId: z.uuid(), humanInputRequestId: z.uuid() }) .strict() .parse(request); if (context.actor.kind !== "agent") throw new Error("Legacy confirmation requires an exact agent attempt"); return inKnowledgeContext(db, context, async (tx) => { const [row] = await rawRows<{ receipt: unknown }>( tx, sql`SELECT knowledge_entry_confirm_legacy( ${context.accountId}::uuid,${context.workspaceId}::uuid,${JSON.stringify(context.actor)}::jsonb, ${JSON.stringify(input)}::jsonb) AS receipt`, ); return KnowledgeEntryWriteReceipt.parse(row?.receipt); }); } /** Compatibility only: finish an imported native instruction without rebaselining. */ export async function confirmLegacyInstruction( db: Database, context: KnowledgeContext, request: { operationId: string; proposalId: string; decisionReceiptId: string; humanInputRequestId: string; }, ) { const input = z .object({ operationId: z.uuid(), proposalId: z.uuid(), decisionReceiptId: z.uuid(), humanInputRequestId: z.uuid(), }) .strict() .parse(request); if (context.actor.kind !== "agent") throw new Error("Legacy confirmation requires an exact agent attempt"); return inKnowledgeContext(db, context, async (tx) => { const [row] = await rawRows<{ receipt: unknown }>( tx, sql`SELECT knowledge_entry_confirm_legacy( ${context.accountId}::uuid,${context.workspaceId}::uuid,${JSON.stringify(context.actor)}::jsonb, ${JSON.stringify(input)}::jsonb) AS receipt`, ); return AgentInstructionReceipt.parse(row?.receipt); }); } /** Protocol recovery runs before the model, including when the retired tool is no longer selected. */ export async function recoverLegacyKnowledgeConfirmations(db: Database, context: KnowledgeContext) { if (context.actor.kind !== "agent") throw new Error("Confirmation recovery requires an exact attempt"); return inKnowledgeContext(db, context, async (tx) => { const [row] = await rawRows<{ result: unknown }>( tx, sql`SELECT knowledge_entry_confirm_legacy( ${context.accountId}::uuid,${context.workspaceId}::uuid,${JSON.stringify(context.actor)}::jsonb, '{"operation":"recover"}'::jsonb) AS result`, ); return z .object({ receipts: z.array(KnowledgeEntryWriteReceipt), instructionReceipts: z.array(AgentInstructionReceipt), unavailable: z.number().int().nonnegative(), }) .parse(row?.result); }); }