@rizom/brain 0.2.0-alpha.715 → 0.2.0-alpha.716

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.
Files changed (29) hide show
  1. package/dist/brain.js +5 -5
  2. package/dist/chunks/app-58b8mqen.js +5 -0
  3. package/dist/chunks/{index-c5w93td1.js → index-0b1c5rz3.js} +3 -3
  4. package/dist/chunks/{index-c5w93td1.js.map → index-0b1c5rz3.js.map} +3 -3
  5. package/dist/chunks/{index-52fjmdw8.js → index-6622vvam.js} +2 -2
  6. package/dist/chunks/{index-29fkwc9t.js → index-6ac9tzsk.js} +2 -2
  7. package/dist/chunks/{index-qtm2xp4r.js → index-99xqzez4.js} +2 -2
  8. package/dist/chunks/{index-4tb8gbez.js → index-adp6qrz3.js} +2 -2
  9. package/dist/chunks/{index-v72db6rj.js → index-hmp7x320.js} +3 -3
  10. package/dist/chunks/{index-v72db6rj.js.map → index-hmp7x320.js.map} +1 -1
  11. package/dist/chunks/{linkedin-template-zrfdrkk7.js → linkedin-template-pwtp7jb6.js} +2 -2
  12. package/dist/chunks/{package-kqs68p94.js → package-6h3sy600.js} +3 -3
  13. package/dist/chunks/{package-kqs68p94.js.map → package-6h3sy600.js.map} +1 -1
  14. package/dist/entities.js +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/interfaces.js +1 -1
  17. package/dist/model.js +4 -4
  18. package/dist/model.js.map +1 -1
  19. package/dist/services.js +1 -1
  20. package/dist/testing.js +1 -1
  21. package/dist/ui/studio-chunks/main-99f3187d.js.map +1 -1
  22. package/package.json +1 -1
  23. package/dist/chunks/app-p39chj3k.js +0 -5
  24. /package/dist/chunks/{app-p39chj3k.js.map → app-58b8mqen.js.map} +0 -0
  25. /package/dist/chunks/{index-52fjmdw8.js.map → index-6622vvam.js.map} +0 -0
  26. /package/dist/chunks/{index-29fkwc9t.js.map → index-6ac9tzsk.js.map} +0 -0
  27. /package/dist/chunks/{index-qtm2xp4r.js.map → index-99xqzez4.js.map} +0 -0
  28. /package/dist/chunks/{index-4tb8gbez.js.map → index-adp6qrz3.js.map} +0 -0
  29. /package/dist/chunks/{linkedin-template-zrfdrkk7.js.map → linkedin-template-pwtp7jb6.js.map} +0 -0
package/dist/services.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./chunks/index-z0k97qgd.js";import{Ai as n,Bi as q,De as a,Fh as l,eh as b,fh as c,gh as d,qh as g,sh as h,th as i,uh as j,vh as k}from"./chunks/index-c5w93td1.js";import{Wl as f,Yl as m,Zl as p,lm as t,um as x}from"./chunks/index-zvy8405y.js";import"./chunks/index-h25wmabx.js";import"./chunks/index-z6mmae7e.js";import{xx as e}from"./chunks/index-kj0ya1j8.js";import"./chunks/index-krrz54wf.js";import"./chunks/index-2b5c2zq2.js";export{p as SdkError,a as contentGenerationResultSchema,g as defineAccountSettings,i as defineBusContract,t as defineChannel,b as defineDashboardWidget,d as defineEntityCatalog,j as defineJob,q as defineRoute,l as defineServicePlugin,x as defineSharedState,c as defineStudioWorkspace,k as defineTool,h as defineWorkspaceAction,n as protocol,f as sdkErrorCodeSchema,m as sdkErrorSchema,e as z};
2
+ import"./chunks/index-z0k97qgd.js";import{Ai as n,Bi as q,De as a,Fh as l,eh as b,fh as c,gh as d,qh as g,sh as h,th as i,uh as j,vh as k}from"./chunks/index-0b1c5rz3.js";import{Wl as f,Yl as m,Zl as p,lm as t,um as x}from"./chunks/index-zvy8405y.js";import"./chunks/index-h25wmabx.js";import"./chunks/index-z6mmae7e.js";import{xx as e}from"./chunks/index-kj0ya1j8.js";import"./chunks/index-krrz54wf.js";import"./chunks/index-2b5c2zq2.js";export{p as SdkError,a as contentGenerationResultSchema,g as defineAccountSettings,i as defineBusContract,t as defineChannel,b as defineDashboardWidget,d as defineEntityCatalog,j as defineJob,q as defineRoute,l as defineServicePlugin,x as defineSharedState,c as defineStudioWorkspace,k as defineTool,h as defineWorkspaceAction,n as protocol,f as sdkErrorCodeSchema,m as sdkErrorSchema,e as z};
3
3
 
4
4
  //# debugId=57D38A2DFCF7128F64756E2164756E21
5
5
  //# sourceMappingURL=services.js.map
package/dist/testing.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{O as k,P as V,Q as U}from"./chunks/index-v72db6rj.js";import{Ea as N,Fa as O,Ga as z,Ha as M,Ia as q,Ja as J,Ka as L,Ma as _,Na as j,R as E,U as I,ga as A,ha as x}from"./chunks/index-29fkwc9t.js";import"./chunks/index-k5zys460.js";import{Ra as D}from"./chunks/index-4tb8gbez.js";import{Ge as C,Ng as P,Og as w,Ub as h,Uj as B}from"./chunks/index-c5w93td1.js";import{$k as p}from"./chunks/index-zvy8405y.js";import{co as S,eo as v}from"./chunks/index-h25wmabx.js";import"./chunks/index-z6mmae7e.js";import"./chunks/index-kj0ya1j8.js";import"./chunks/index-krrz54wf.js";import"./chunks/index-2b5c2zq2.js";import{mkdtemp as K,rm as b}from"fs/promises";import{tmpdir as X}from"os";import{join as m}from"path";var y="none";function s(){return Promise.reject(Error("A test brain has no AI provider"))}function W(e){return{specificationVersion:"v3",provider:"test-brain",modelId:e,supportedUrls:{},doGenerate:s,doStream:s}}function T(e){let r={...e};return{generateText:s,generateObject:s,judge:s,generateImage:s,getModel:()=>W(r.model??"none"),canGenerateImages:()=>!1,getConfig:()=>({...r}),updateConfig:(o)=>{r={...r,...o}}}}function R(){return{identity:{model:"test:none",dimensions:1536,promptRevision:0},embedQuery:s,embedDocuments:s}}var Y="shell",ee=20;function te(e){if("needsConfirmation"in e)return{needsConfirmation:!0,summary:e.summary};if(!e.success)return{success:!1,error:e.error,...p({code:e.code})};return{success:!0,...p({data:e.data,message:e.message})}}function re(e,r){if(e.status==="completed"||e.status==="failed")return!0;return e.status==="pending"&&e.lastError!==null&&e.scheduledFor>r}function ne(e,r){return e.flatMap((o)=>{if(!D(o))throw Error("A test brain runs packages configured with use(), as defineBrain does");return P(o.definition,o.config,r)})}async function F(e,r){let o=k(r.directory);V(o,r.brainVersion);let f=ne(e.plugins,{name:o.name,version:o.version}),a=await K(m(r.temporaryRoot??X(),"rizom-test-brain-")),g={...E({dataDir:a,cacheDir:m(a,"cache"),distDir:m(a,"dist")}),embedding:{enabled:!1}},i;try{await new J(v.createFresh({level:S.WARN,context:"test-brain"}),{getStandardConfigWithDirectories:async()=>g,migrateEntities:O,migrateJobQueue:z,migrateConversations:M,migrateRuntimeState:q}).runAllMigrations();let t=_({name:o.name,version:o.version,logLevel:"warn",plugins:f,shellConfig:{...g,dataDir:m(a,"brain-data"),ai:{model:y}}}),n=I(j(t));i=N.createFresh(n,{aiService:T(A(n)),embeddingService:R()}),await i.initialize()}catch(t){throw await b(a,{recursive:!0,force:!0}),t}let Z=f.map((t)=>t.id),H,Q=async()=>{try{await i.shutdown()}finally{await b(a,{recursive:!0,force:!0})}};return Object.freeze({async tool(t,n){let l=i.getMCPService().listTools(),d=l.find(({tool:u})=>u.name===t);if(!d)throw Error(`No tool "${t}"; this brain has ${l.map(({tool:u})=>u.name).join(", ")}`);return te(await d.tool.handler(n,L()))},request:(t,n)=>h(i.getMessageBus(),t,n,Y),async fetch(t){let n=x(B(i),t.method.toUpperCase(),new URL(t.url).pathname);if(!n)return new Response("Not Found",{status:404});if(n.sharedHostAdmission==="deny")return new Response("Unauthorized",{status:401});return n.handler(t)},entities:C(i.getEntityService(),"restricted"),jobs:Object.freeze({async wait(t,n){let l=i.getJobQueueService(),d=async()=>{let c=await l.getStatus(n);if(!c||!Z.some((G)=>c.type===`${G}:${t.name}`))return null;if(re(c,Date.now()))return c;return await Bun.sleep(ee),d()},u=await d();return u?w(t,u):null}}),stop:()=>H??=Q()})}function Ee(e){return F(e,{brainVersion:U.version,directory:process.cwd()})}export{Ee as startTestBrain};
2
+ import{O as k,P as V,Q as U}from"./chunks/index-hmp7x320.js";import{Ea as N,Fa as O,Ga as z,Ha as M,Ia as q,Ja as J,Ka as L,Ma as _,Na as j,R as E,U as I,ga as A,ha as x}from"./chunks/index-6ac9tzsk.js";import"./chunks/index-k5zys460.js";import{Ra as D}from"./chunks/index-adp6qrz3.js";import{Ge as C,Ng as P,Og as w,Ub as h,Uj as B}from"./chunks/index-0b1c5rz3.js";import{$k as p}from"./chunks/index-zvy8405y.js";import{co as S,eo as v}from"./chunks/index-h25wmabx.js";import"./chunks/index-z6mmae7e.js";import"./chunks/index-kj0ya1j8.js";import"./chunks/index-krrz54wf.js";import"./chunks/index-2b5c2zq2.js";import{mkdtemp as K,rm as b}from"fs/promises";import{tmpdir as X}from"os";import{join as m}from"path";var y="none";function s(){return Promise.reject(Error("A test brain has no AI provider"))}function W(e){return{specificationVersion:"v3",provider:"test-brain",modelId:e,supportedUrls:{},doGenerate:s,doStream:s}}function T(e){let r={...e};return{generateText:s,generateObject:s,judge:s,generateImage:s,getModel:()=>W(r.model??"none"),canGenerateImages:()=>!1,getConfig:()=>({...r}),updateConfig:(o)=>{r={...r,...o}}}}function R(){return{identity:{model:"test:none",dimensions:1536,promptRevision:0},embedQuery:s,embedDocuments:s}}var Y="shell",ee=20;function te(e){if("needsConfirmation"in e)return{needsConfirmation:!0,summary:e.summary};if(!e.success)return{success:!1,error:e.error,...p({code:e.code})};return{success:!0,...p({data:e.data,message:e.message})}}function re(e,r){if(e.status==="completed"||e.status==="failed")return!0;return e.status==="pending"&&e.lastError!==null&&e.scheduledFor>r}function ne(e,r){return e.flatMap((o)=>{if(!D(o))throw Error("A test brain runs packages configured with use(), as defineBrain does");return P(o.definition,o.config,r)})}async function F(e,r){let o=k(r.directory);V(o,r.brainVersion);let f=ne(e.plugins,{name:o.name,version:o.version}),a=await K(m(r.temporaryRoot??X(),"rizom-test-brain-")),g={...E({dataDir:a,cacheDir:m(a,"cache"),distDir:m(a,"dist")}),embedding:{enabled:!1}},i;try{await new J(v.createFresh({level:S.WARN,context:"test-brain"}),{getStandardConfigWithDirectories:async()=>g,migrateEntities:O,migrateJobQueue:z,migrateConversations:M,migrateRuntimeState:q}).runAllMigrations();let t=_({name:o.name,version:o.version,logLevel:"warn",plugins:f,shellConfig:{...g,dataDir:m(a,"brain-data"),ai:{model:y}}}),n=I(j(t));i=N.createFresh(n,{aiService:T(A(n)),embeddingService:R()}),await i.initialize()}catch(t){throw await b(a,{recursive:!0,force:!0}),t}let Z=f.map((t)=>t.id),H,Q=async()=>{try{await i.shutdown()}finally{await b(a,{recursive:!0,force:!0})}};return Object.freeze({async tool(t,n){let l=i.getMCPService().listTools(),d=l.find(({tool:u})=>u.name===t);if(!d)throw Error(`No tool "${t}"; this brain has ${l.map(({tool:u})=>u.name).join(", ")}`);return te(await d.tool.handler(n,L()))},request:(t,n)=>h(i.getMessageBus(),t,n,Y),async fetch(t){let n=x(B(i),t.method.toUpperCase(),new URL(t.url).pathname);if(!n)return new Response("Not Found",{status:404});if(n.sharedHostAdmission==="deny")return new Response("Unauthorized",{status:401});return n.handler(t)},entities:C(i.getEntityService(),"restricted"),jobs:Object.freeze({async wait(t,n){let l=i.getJobQueueService(),d=async()=>{let c=await l.getStatus(n);if(!c||!Z.some((G)=>c.type===`${G}:${t.name}`))return null;if(re(c,Date.now()))return c;return await Bun.sleep(ee),d()},u=await d();return u?w(t,u):null}}),stop:()=>H??=Q()})}function Ee(e){return F(e,{brainVersion:U.version,directory:process.cwd()})}export{Ee as startTestBrain};
3
3
 
4
4
  //# debugId=F6E49A68A7E6134564756E2164756E21
5
5
  //# sourceMappingURL=testing.js.map
@@ -277,7 +277,7 @@
277
277
  "import { customAlphabet, nanoid } from \"nanoid\";\n\n/**\n * Create a unique ID for general use\n * Uses nanoid with configurable size (default 12 characters)\n * Default size gives ~17 years to have 1% collision probability at 1K IDs/hour\n * This wrapper allows for easy mocking in tests\n */\nexport function createId(size = 12): string {\n return nanoid(size);\n}\n\nconst LOWERCASE_ALPHANUMERIC = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\n/** A short id of lowercase letters and digits, for readable file names. */\nexport function createShortId(size = 6): string {\n return customAlphabet(LOWERCASE_ALPHANUMERIC, size)();\n}\n\n/**\n * Create a prefixed unique ID\n * Useful for identifying different types of entities\n */\nexport function createPrefixedId(prefix: string): string {\n return `${prefix}_${nanoid(12)}`;\n}\n\n/**\n * Create a batch ID with timestamp for easier debugging and sorting\n */\nexport function createBatchId(): string {\n return `batch_${Date.now()}_${nanoid(8)}`;\n}\n",
278
278
  "import { SHELL_CHANNELS } from \"@brains/contracts\";\nimport type { IJobQueueService, JobInfo } from \"@brains/job-queue\";\nimport type { Logger } from \"@brains/utils/logger\";\nimport type { RetryScope } from \"@brains/utils/retry-backoff\";\nimport { z } from \"@brains/utils/zod\";\nimport { and, eq, sql } from \"drizzle-orm\";\nimport type { EntityDB } from \"./db\";\nimport type { EmbeddingDB } from \"./db/embedding-db\";\nimport { embeddings } from \"./schema/embeddings\";\nimport { entities } from \"./schema/entities\";\nimport type {\n EmbeddingBackfillResult,\n EmbeddingFailureReference,\n EmbeddingIndexStats,\n EmbeddingJobData,\n EntityJobOptions,\n EntityMutationResult,\n EntityRegistry,\n StoreEmbeddingData,\n} from \"./types\";\n\nconst failedEmbeddingJobDataSchema = z.object({\n id: z.string().min(1),\n entityType: z.string().min(1),\n contentHash: z.string().min(1),\n});\n\nfunction parseEmbeddingFailureReference(\n job: JobInfo,\n): EmbeddingFailureReference | null {\n try {\n const data = failedEmbeddingJobDataSchema.parse(JSON.parse(job.data));\n return {\n entityId: data.id,\n entityType: data.entityType,\n contentHash: data.contentHash,\n };\n } catch {\n // Unreadable job data yields no reference and cannot suppress a retry.\n return null;\n }\n}\n\nfunction embeddingRetryKey(entityType: string, entityId: string): string {\n return `${entityType}:${entityId}`;\n}\n\nfunction embeddingReferenceKey(reference: EmbeddingFailureReference): string {\n return `${reference.entityType}:${reference.entityId}:${reference.contentHash}`;\n}\n\ninterface EmbeddingBackfillCandidate {\n id: string;\n entityType: string;\n contentHash: string;\n}\n\ninterface EmbeddingBackfillCandidates extends EmbeddingIndexStats {\n tableMissing: boolean;\n skipped: number;\n rowsToBackfill: EmbeddingBackfillCandidate[];\n /** Entities whose embedding failed for good at their current content. */\n failedRows: EmbeddingBackfillCandidate[];\n}\n\n/**\n * Embedding jobs run ahead of default-priority work (0): the readiness gate\n * holds chat until the index is built, and derivations such as FAQ or topic\n * passes can take minutes each on a local model.\n */\nconst EMBEDDING_JOB_PRIORITY = -10;\n\nexport interface EnqueueEmbeddingInput\n extends Omit<EmbeddingJobData, \"id\">, EntityJobOptions {\n entityId: string;\n}\n\nexport interface EmbeddingIndexCoordinatorOptions {\n entityDb: EntityDB;\n embeddingDb: EmbeddingDB;\n entityRegistry: EntityRegistry;\n jobQueueService: IJobQueueService;\n logger: Logger;\n embeddingsEnabled: boolean;\n /**\n * Retries embedding enqueues the job queue refuses. Without it a refusal\n * is thrown to the mutation's caller, after the entity is committed.\n */\n retries?: RetryScope | undefined;\n}\n\n/** Owns recoverable embedding persistence, queueing, and readiness statistics. */\nexport class EmbeddingIndexCoordinator {\n private readonly entityDb: EntityDB;\n private readonly embeddingDb: EmbeddingDB;\n private readonly entityRegistry: EntityRegistry;\n private readonly jobQueueService: IJobQueueService;\n private readonly logger: Logger;\n private readonly embeddingsEnabled: boolean;\n private readonly retries: RetryScope | undefined;\n\n public constructor(options: EmbeddingIndexCoordinatorOptions) {\n this.entityDb = options.entityDb;\n this.embeddingDb = options.embeddingDb;\n this.entityRegistry = options.entityRegistry;\n this.jobQueueService = options.jobQueueService;\n this.logger = options.logger;\n this.embeddingsEnabled = options.embeddingsEnabled;\n this.retries = options.retries;\n }\n\n public async deleteEmbedding(\n entityType: string,\n entityId: string,\n ): Promise<void> {\n this.retries?.cancel(embeddingRetryKey(entityType, entityId));\n await this.embeddingDb\n .delete(embeddings)\n .where(\n and(\n eq(embeddings.entityType, entityType),\n eq(embeddings.entityId, entityId),\n ),\n );\n }\n\n public async store(data: StoreEmbeddingData): Promise<void> {\n await this.embeddingDb\n .insert(embeddings)\n .values({\n entityId: data.entityId,\n entityType: data.entityType,\n embedding: data.embedding,\n contentHash: data.contentHash,\n })\n .onConflictDoUpdate({\n target: [embeddings.entityId, embeddings.entityType],\n set: {\n embedding: data.embedding,\n contentHash: data.contentHash,\n },\n });\n }\n\n public async backfillMissing(): Promise<EmbeddingBackfillResult> {\n if (!this.embeddingsEnabled) {\n this.logger.debug(\n \"Skipping embedding backfill; semantic indexing is disabled\",\n );\n return { queued: 0, skipped: 0 };\n }\n\n const candidates = await this.getBackfillCandidates();\n if (candidates.tableMissing) {\n this.logger.debug(\"Skipping embedding backfill; entities table missing\");\n return { queued: 0, skipped: 0 };\n }\n\n // The backfill runs at start: an embedding that failed for good, as in a\n // provider outage, is retried once per start.\n let queued = 0;\n let skipped = candidates.skipped - candidates.failedRows.length;\n for (const row of [\n ...candidates.rowsToBackfill,\n ...candidates.failedRows,\n ]) {\n const result = await this.enqueue({\n entityId: row.id,\n entityType: row.entityType,\n contentHash: row.contentHash,\n operation: \"update\",\n });\n if (result.jobId) queued++;\n else skipped++;\n }\n\n return { queued, skipped };\n }\n\n public async getIndexStats(): Promise<EmbeddingIndexStats> {\n const candidates = await this.getBackfillCandidates();\n return {\n missingEmbeddings: candidates.missingEmbeddings,\n staleEmbeddings: candidates.staleEmbeddings,\n failedEmbeddings: candidates.failedEmbeddings,\n embeddableEntities: candidates.embeddableEntities,\n embeddedEntities: candidates.embeddedEntities,\n };\n }\n\n public async enqueue(\n input: EnqueueEmbeddingInput,\n ): Promise<EntityMutationResult> {\n const {\n entityId,\n entityType,\n contentHash,\n operation,\n priority,\n maxRetries,\n eventContext,\n } = input;\n\n const entityConfig = this.entityRegistry.getEntityTypeConfig(entityType);\n if (!this.embeddingsEnabled || entityConfig.embeddable === false) {\n this.logger.debug(\n `Skipping embedding for ${\n this.embeddingsEnabled\n ? \"non-embeddable entity type\"\n : \"disabled indexing\"\n }: ${entityType}:${entityId}`,\n );\n return { entityId, jobId: \"\", skipped: false };\n }\n\n const jobData: EmbeddingJobData = {\n id: entityId,\n entityType,\n contentHash,\n operation,\n };\n const enqueueJob = (): Promise<string> =>\n this.jobQueueService.enqueue({\n type: SHELL_CHANNELS.embedding,\n data: jobData,\n options: {\n priority: priority ?? EMBEDDING_JOB_PRIORITY,\n ...(maxRetries !== undefined && { maxRetries }),\n source: \"entity-service\",\n deduplication: \"coalesce\",\n deduplicationKey: `embedding:${entityType}:${entityId}:${contentHash}`,\n metadata: {\n operationType: \"data_processing\",\n operationTarget: entityId,\n ...(eventContext?.interfaceType\n ? {\n interfaceType: eventContext.interfaceType,\n requestedByInterface: eventContext.interfaceType,\n }\n : {}),\n ...(eventContext?.actor\n ? {\n requestedByActor: eventContext.actor,\n ...(eventContext.actor.kind === \"user\"\n ? { requestedByUserId: eventContext.actor.userId }\n : {}),\n }\n : {}),\n silent: true,\n },\n },\n });\n\n // The job queue refuses an enqueue while another process holds its write\n // lock past the enqueue budget. The entity is committed by now, so the\n // mutation resolves with no job id and the embedding is enqueued again in\n // the background: one retry per entity, the latest content winning. A\n // retry still pending when the process exits is lost; the startup\n // backfill (backfillMissing) then finds that entity's embedding missing or\n // stale and enqueues it, so it stays the crash-safety net. An outbox would\n // replace both, but the job queue lives in a separate database by design.\n const key = embeddingRetryKey(entityType, entityId);\n let jobId: string;\n try {\n jobId = await enqueueJob();\n } catch (error) {\n if (!this.retries) throw error;\n void this.retries.retry(\n enqueueJob,\n error,\n `queue the embedding for ${key}`,\n key,\n );\n return { entityId, jobId: \"\", skipped: false };\n }\n // A queued embedding of newer content replaces an older pending retry.\n this.retries?.cancel(key);\n this.logger.debug(\n `Queued embedding job for ${entityType}:${entityId} (job: ${jobId})`,\n );\n return { entityId, jobId, skipped: false };\n }\n\n private async getBackfillCandidates(): Promise<EmbeddingBackfillCandidates> {\n if (!(await this.hasEntityTable())) {\n return {\n tableMissing: true,\n skipped: 0,\n rowsToBackfill: [],\n failedRows: [],\n missingEmbeddings: 0,\n staleEmbeddings: 0,\n failedEmbeddings: 0,\n embeddableEntities: 0,\n embeddedEntities: 0,\n };\n }\n\n const failedEmbeddingKeys = await this.getFailedEmbeddingKeys();\n const entityRows = await this.entityDb\n .select({\n id: entities.id,\n entityType: entities.entityType,\n contentHash: entities.contentHash,\n })\n .from(entities);\n const embeddingRows = await this.embeddingDb\n .select({\n entityId: embeddings.entityId,\n entityType: embeddings.entityType,\n contentHash: embeddings.contentHash,\n })\n .from(embeddings);\n\n const embeddingHashes = new Map<string, string>();\n for (const row of embeddingRows) {\n embeddingHashes.set(`${row.entityType}:${row.entityId}`, row.contentHash);\n }\n\n const rowsToBackfill: EmbeddingBackfillCandidate[] = [];\n const failedRows: EmbeddingBackfillCandidate[] = [];\n let skipped = 0;\n let missingEmbeddings = 0;\n let staleEmbeddings = 0;\n let failedEmbeddings = 0;\n let embeddableEntities = 0;\n let embeddedEntities = 0;\n\n for (const row of entityRows) {\n const entityConfig = this.entityRegistry.getEntityTypeConfig(\n row.entityType,\n );\n if (entityConfig.embeddable === false) {\n skipped++;\n continue;\n }\n embeddableEntities++;\n\n const failureKey = embeddingReferenceKey({\n entityId: row.id,\n entityType: row.entityType,\n contentHash: row.contentHash,\n });\n const hasTerminalFailure = failedEmbeddingKeys.has(failureKey);\n const embeddingHash = embeddingHashes.get(`${row.entityType}:${row.id}`);\n if (embeddingHash === undefined) {\n if (hasTerminalFailure) {\n failedEmbeddings++;\n skipped++;\n failedRows.push(row);\n } else {\n missingEmbeddings++;\n rowsToBackfill.push(row);\n }\n continue;\n }\n\n if (embeddingHash !== row.contentHash) {\n if (hasTerminalFailure) {\n failedEmbeddings++;\n skipped++;\n failedRows.push(row);\n } else {\n staleEmbeddings++;\n rowsToBackfill.push(row);\n }\n continue;\n }\n\n embeddedEntities++;\n skipped++;\n }\n\n return {\n tableMissing: false,\n skipped,\n rowsToBackfill,\n failedRows,\n missingEmbeddings,\n staleEmbeddings,\n failedEmbeddings,\n embeddableEntities,\n embeddedEntities,\n };\n }\n\n private async getFailedEmbeddingKeys(): Promise<Set<string>> {\n const failedJobs = await this.jobQueueService.getFailedJobs([\n SHELL_CHANNELS.embedding,\n ]);\n const failedEmbeddingKeys = new Set<string>();\n for (const job of failedJobs) {\n const reference = parseEmbeddingFailureReference(job);\n if (reference) {\n failedEmbeddingKeys.add(embeddingReferenceKey(reference));\n }\n }\n return failedEmbeddingKeys;\n }\n\n private async hasEntityTable(): Promise<boolean> {\n const rows = await this.entityDb.all<{ name: string }>(\n sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'entities'`,\n );\n return rows.length > 0;\n }\n}\n",
279
279
  "import { z } from \"@brains/utils/zod\";\n\n/** null means create only if absent; a token means replace that incarnation. */\nexport const entityWriteConditionSchema: z.ZodObject<{\n expectedRevision: z.ZodNullable<z.ZodString>;\n}> = z.object({\n expectedRevision: z.string().min(1).nullable(),\n});\n\nexport type EntityWriteCondition = z.output<typeof entityWriteConditionSchema>;\n\nexport class EntityWriteConflictError extends Error {\n constructor(entityType: string, entityId: string) {\n super(`Entity write conflict: ${entityType}/${entityId}`);\n this.name = \"EntityWriteConflictError\";\n }\n}\n",
280
- "import { internalFullScope } from \"./internal-scope\";\nimport { deleteEntityFts, insertEntityFts } from \"./entity-fts\";\nimport type { Channel } from \"@brains/contracts\";\nimport { broadcastChannel } from \"@brains/messaging-service\";\nimport {\n entityCreatedChannel,\n entityDeletedChannel,\n entityUpdatedChannel,\n type EntityChangePayload,\n} from \"./entity-event-channels\";\nimport type { EntityDB } from \"./db\";\nimport { EntityMutationReceiptStore } from \"./entity-mutation-receipt-store\";\nimport {\n EntityMutationAlreadyAppliedError,\n type EntityMutationReceipt,\n type EntityMutationReceiptKey,\n} from \"./entity-mutation-receipt\";\nimport { snapshotEntityMutation } from \"./entity-mutation-request\";\nimport type { EmbeddingDB } from \"./db/embedding-db\";\nimport type {\n AssetTransaction,\n SqliteAssetRepository,\n StagedUpload,\n} from \"./sqlite-asset-repository\";\nimport type {\n BaseEntity,\n EntityJobOptions,\n EntityMutationEventContext,\n EntityMutationResult,\n EmbeddingBackfillResult,\n EmbeddingIndexStats,\n StoreEmbeddingData,\n EntityEventBus,\n DeleteEntityRequest,\n CreateEntityRequest,\n UpdateEntityRequest,\n UpdateEntityOptions,\n FoldEntityRequest,\n ApplyEntityMutationOnceRequest,\n UpsertEntityRequest,\n EntityRegistry,\n EntityMutationAdmission,\n} from \"./types\";\nimport type { EntitySerializer } from \"./entity-serializer\";\nimport type { EntityQueries } from \"./entity-queries\";\nimport type { ProjectionStore } from \"./projection-store\";\nimport type {\n EntityExportStore,\n EntityExportTransaction,\n} from \"./entity-export-store\";\nimport type { IJobQueueService } from \"@brains/job-queue\";\nimport { createId } from \"@brains/utils/id\";\nimport { z } from \"@brains/utils/zod\";\nimport type { Logger } from \"@brains/utils/logger\";\nimport { computeContentHash } from \"@brains/utils/hash\";\nimport { entities } from \"./schema/entities\";\nimport type { ProjectionChangedTarget } from \"./schema/projection-state\";\nimport {\n EmbeddingIndexCoordinator,\n type EnqueueEmbeddingInput,\n} from \"./embedding-index-coordinator\";\nimport type { EntityTransaction } from \"./projection-transaction-runner\";\nimport { and, eq, sql } from \"drizzle-orm\";\nimport {\n entityWriteConditionSchema,\n EntityWriteConflictError,\n} from \"./entity-write-contracts\";\nimport {\n assertEntityWriteCondition,\n type EntityWritePrecondition,\n} from \"./entity-write-state\";\nimport { entityRevision, stableJson } from \"./entity-revision\";\nimport {\n isSchemaPhaseValidationError,\n toEntityValidationError,\n} from \"./errors\";\n\n/** Shared by ordinary mutations and atomic projection upserts. */\nexport async function validatePersist(\n registry: EntityRegistry,\n entity: BaseEntity,\n operation: \"create\" | \"update\",\n): Promise<void> {\n try {\n await registry.getPersistValidator(entity.entityType)?.(entity, {\n operation,\n });\n } catch (error) {\n // A validator that finds the content itself invalid says so with a\n // schema-phase error, which sync quarantines; any other refusal is a live\n // policy, which sync retries.\n if (isSchemaPhaseValidationError(error)) throw error;\n throw toEntityValidationError(entity.entityType, error, \"persist\") ?? error;\n }\n}\n\nfunction isUniqueConstraintError(error: unknown): boolean {\n // Drizzle wraps the LibsqlError, so walk the cause chain\n for (let current = error; current instanceof Error; current = current.cause) {\n if (\n current.message.includes(\"UNIQUE constraint failed\") ||\n current.message.includes(\"SQLITE_CONSTRAINT\")\n ) {\n return true;\n }\n }\n return false;\n}\n\nclass StaleEntityUpdateError extends Error {}\n\nconst foldSourceSchema = z.strictObject({\n entityType: z.string().min(1),\n id: z.string().min(1),\n expectedRevision: z.string().min(1),\n});\ninterface FoldRemoval {\n condition: EntityWritePrecondition;\n prior: BaseEntity;\n}\n\n/** What the final in-transaction checks see of an entity about to be written. */\ninterface EntityWriteGuard {\n /** Carries the final ID. */\n entity: BaseEntity;\n markdown: string;\n metadata: Record<string, unknown>;\n contentHash: string;\n stagedUpload: StagedUpload | undefined;\n options: Pick<UpdateEntityOptions, \"signal\" | \"beforeWrite\"> | undefined;\n assertGroupingsCurrent: () => Promise<void>;\n}\n\n/** A validated, serialized update and the stored row it replaces. */\ninterface EntityUpdatePlan extends EntityWriteGuard {\n options: UpdateEntityOptions | undefined;\n precondition: EntityWritePrecondition | undefined;\n fold: FoldRemoval | undefined;\n receipt: EntityMutationReceiptKey | undefined;\n previousMetadata: BaseEntity[\"metadata\"];\n /** Every persisted field already matches the stored row. */\n unchanged: boolean;\n}\n\ntype PreparedEntityUpdate =\n { stale: true; entityId: string } | { stale: false; plan: EntityUpdatePlan };\n\n/** The stored content hash no longer matches the caller's expectation. */\nfunction contentConflict(entityId: string): EntityMutationResult {\n return { entityId, jobId: \"\", skipped: true, skipReason: \"content-conflict\" };\n}\n\nexport interface EntityMutationDeps {\n db: EntityDB;\n entityRegistry: EntityRegistry;\n entitySerializer: EntitySerializer;\n entityQueries: EntityQueries;\n jobQueueService: IJobQueueService;\n logger: Logger;\n messageBus?: EntityEventBus;\n mutationAdmission?: EntityMutationAdmission;\n projectionStore: ProjectionStore;\n assetRepository: SqliteAssetRepository;\n entityExportStore: EntityExportStore;\n projectionNow: () => number;\n /** Embedding DB for writes (separate from entity DB). */\n embeddingDb: EmbeddingDB;\n embeddingsEnabled: boolean;\n /** Retries refused embedding enqueues; see EmbeddingIndexCoordinator. */\n embeddingRetries?: ConstructorParameters<\n typeof EmbeddingIndexCoordinator\n >[0][\"retries\"];\n}\n\n/**\n * EntityMutations handles all write operations for entities\n * Extracted from EntityService for single responsibility\n */\nexport class EntityMutations {\n private db: EntityDB;\n private readonly mutationReceipts: EntityMutationReceiptStore;\n private entityRegistry: EntityRegistry;\n private entitySerializer: EntitySerializer;\n private entityQueries: EntityQueries;\n private messageBus?: EntityEventBus;\n private mutationAdmission?: EntityMutationAdmission;\n private readonly projectionStore: ProjectionStore;\n private readonly assetRepository: SqliteAssetRepository;\n private readonly entityExportStore: EntityExportStore;\n private readonly projectionNow: () => number;\n private readonly embeddingIndex: EmbeddingIndexCoordinator;\n private projectionWakeup: (() => Promise<void>) | undefined;\n private logger: Logger;\n\n constructor(deps: EntityMutationDeps) {\n this.db = deps.db;\n this.mutationReceipts = new EntityMutationReceiptStore(deps.db);\n this.entityRegistry = deps.entityRegistry;\n this.entitySerializer = deps.entitySerializer;\n this.entityQueries = deps.entityQueries;\n this.projectionStore = deps.projectionStore;\n this.assetRepository = deps.assetRepository;\n this.entityExportStore = deps.entityExportStore;\n this.projectionNow = deps.projectionNow;\n this.logger = deps.logger.child(\"EntityMutations\");\n this.embeddingIndex = new EmbeddingIndexCoordinator({\n entityDb: deps.db,\n embeddingDb: deps.embeddingDb,\n entityRegistry: deps.entityRegistry,\n jobQueueService: deps.jobQueueService,\n logger: this.logger,\n embeddingsEnabled: deps.embeddingsEnabled,\n retries: deps.embeddingRetries,\n });\n if (deps.messageBus) {\n this.messageBus = deps.messageBus;\n }\n if (deps.mutationAdmission) {\n this.mutationAdmission = deps.mutationAdmission;\n }\n }\n\n public setProjectionWakeup(wakeup: () => Promise<void>): () => void {\n this.projectionWakeup = wakeup;\n let active = true;\n return (): void => {\n if (!active) return;\n active = false;\n if (this.projectionWakeup === wakeup) this.projectionWakeup = undefined;\n };\n }\n\n /**\n * Create a new entity (returns immediately, embedding generated in background)\n */\n public getEntityMutationReceipt(\n key: EntityMutationReceiptKey,\n ): Promise<EntityMutationReceipt | null> {\n return this.mutationReceipts.get(key);\n }\n\n public async applyEntityMutationOnce(\n input: ApplyEntityMutationOnceRequest,\n ): Promise<{ receipt: EntityMutationReceipt; applied: boolean }> {\n const mutation = snapshotEntityMutation(input);\n const key = mutation.receipt;\n const prior = await this.mutationReceipts.get(key);\n if (prior) return { receipt: prior, applied: false };\n if (mutation.operation === \"none\")\n return {\n receipt: await this.mutationReceipts.completeWithoutWrite(key),\n applied: false,\n };\n try {\n const result =\n mutation.operation === \"create\"\n ? await this.writeCreatedEntity(mutation.request, key)\n : await this.writeUpdatedEntity(mutation.request, undefined, key);\n if (result.skipReason === \"content-conflict\") {\n throw new EntityWriteConflictError(\n mutation.request.entity.entityType,\n result.entityId,\n );\n }\n const receipt = await this.mutationReceipts.get(key);\n if (!receipt)\n throw new Error(\"Missing committed entity mutation receipt\");\n return { receipt, applied: true };\n } catch (error) {\n if (error instanceof EntityMutationAlreadyAppliedError)\n return { receipt: error.receipt, applied: false };\n throw error;\n }\n }\n\n public createEntity<T extends BaseEntity>(\n request: CreateEntityRequest<T>,\n ): Promise<EntityMutationResult> {\n return this.writeCreatedEntity(request);\n }\n\n private async writeCreatedEntity<T extends BaseEntity>(\n request: CreateEntityRequest<T>,\n receipt?: EntityMutationReceiptKey,\n ): Promise<EntityMutationResult> {\n const { entity, options, stagedAsset } = request;\n options?.signal?.throwIfAborted();\n const condition =\n options?.conditionalWrite &&\n entityWriteConditionSchema.parse(options.conditionalWrite);\n if (\n condition &&\n (condition.expectedRevision !== null ||\n options.deduplicateId ||\n !entity.id)\n ) {\n throw new Error(\n \"Conditional creation requires an explicit ID, an absent precondition, and no deduplication\",\n );\n }\n const precondition: EntityWritePrecondition | undefined = condition\n ? {\n ...condition,\n entityType: entity.entityType,\n entityId: entity.id ?? \"\",\n }\n : undefined;\n this.logger.debug(\n `Creating entity asynchronously of type: ${entity[\"entityType\"]}`,\n );\n\n const assertGroupingsCurrent =\n this.entityRegistry.captureGroupingWriteGuard(entity.entityType);\n // Generate ID, timestamps, and contentHash if not provided\n const now = new Date().toISOString();\n const current = this.entitySerializer.withoutRetiredFields(entity);\n const entityWithDefaults = {\n ...current,\n id: entity.id ?? createId(),\n created: entity.created ?? now,\n updated: entity.updated ?? now,\n contentHash: computeContentHash(current.content),\n };\n\n // Validate entity against its schema\n const validatedEntity = this.entityRegistry.validateEntity(\n entity[\"entityType\"],\n entityWithDefaults,\n );\n\n await validatePersist(this.entityRegistry, validatedEntity, \"create\");\n options?.signal?.throwIfAborted();\n\n // Prepare entity for storage\n const { markdown, metadata } =\n this.entitySerializer.prepareEntityForStorage(\n validatedEntity,\n validatedEntity.entityType,\n );\n\n // Compute contentHash from the serialized markdown\n const contentHash = computeContentHash(markdown);\n const stagedUpload = this.resolveStagedUpload(\n validatedEntity.entityType,\n validatedEntity.content,\n markdown,\n stagedAsset,\n );\n\n // Resolve final ID (may deduplicate on collision)\n let finalId = validatedEntity.id;\n if (options?.deduplicateId) {\n finalId = await this.resolveUniqueId(\n validatedEntity.id,\n validatedEntity.entityType,\n );\n }\n\n await this.mutationAdmission?.assertMutationAdmission({\n operation: \"create\",\n entityType: validatedEntity.entityType,\n entityId: finalId,\n });\n\n // Persist the entity, search row, and scheduler journal atomically.\n await this.projectionStore.withDirtyInput(\n {\n sourceType: validatedEntity.entityType,\n sourceId: finalId,\n revision: entityRevision({\n contentHash,\n metadata,\n visibility: validatedEntity.visibility,\n }),\n operation: \"upsert\",\n markedAt: this.projectionNow(),\n },\n async (transaction) => {\n if (receipt)\n await this.mutationReceipts.assertVacant(transaction, receipt);\n if (precondition)\n await assertEntityWriteCondition(\n transaction,\n precondition,\n validatedEntity,\n );\n await this.guardEntityWrite(transaction, {\n entity: { ...validatedEntity, id: finalId },\n markdown,\n metadata,\n contentHash,\n stagedUpload,\n options,\n assertGroupingsCurrent,\n });\n // Once the entity write starts, settle the complete atomic mutation.\n await transaction.insert(entities).values({\n id: finalId,\n entityType: validatedEntity.entityType,\n content: markdown,\n contentHash,\n visibility: validatedEntity.visibility,\n metadata,\n created: new Date(validatedEntity.created).getTime(),\n updated: new Date(validatedEntity.updated).getTime(),\n });\n await this.recordEntityUpsert(\n transaction,\n {\n operation: \"create\",\n entityType: validatedEntity.entityType,\n entityId: finalId,\n markdown,\n },\n receipt,\n options?.persistenceOrigin,\n );\n },\n );\n await this.notifyProjectionScheduler();\n\n this.logger.debug(\n `Persisted entity ${validatedEntity.entityType}:${finalId} immediately`,\n );\n\n await this.emitEntityEvent(\n entityCreatedChannel,\n validatedEntity.entityType,\n finalId,\n {\n ...validatedEntity,\n id: finalId,\n },\n undefined,\n options?.eventContext,\n );\n\n return this.enqueueEmbedding(\n {\n entityId: finalId,\n entityType: validatedEntity.entityType,\n contentHash,\n operation: \"create\",\n },\n options,\n );\n }\n\n /**\n * Update an existing entity (returns immediately, embedding generated in background)\n */\n public updateEntity<T extends BaseEntity>(\n request: UpdateEntityRequest<T>,\n ): Promise<EntityMutationResult> {\n return this.writeUpdatedEntity(request);\n }\n\n public async foldEntity(\n request: FoldEntityRequest,\n ): Promise<EntityMutationResult> {\n // Capture the admitted pair before any asynchronous policy/serialization work.\n const source = foldSourceSchema.parse(request.source);\n const targetRevision = z.string().min(1).parse(request.targetRevision);\n const entity = structuredClone(request.entity);\n const options = { ...request.options };\n if (source.entityType !== entity.entityType || source.id === entity.id) {\n throw new Error(\"A fold requires two distinct entities of the same type\");\n }\n options.signal?.throwIfAborted();\n const priorData = await this.entityQueries.getEntityData(\n source.entityType,\n source.id,\n internalFullScope(\"fold revision check, internal mutation\"),\n );\n if (!priorData || entityRevision(priorData) !== source.expectedRevision) {\n throw new EntityWriteConflictError(source.entityType, source.id);\n }\n const prior = await this.entitySerializer.convertToEntity(priorData);\n if (prior?.visibility !== entity.visibility) {\n throw new Error(\"A fold cannot cross visibility scopes\");\n }\n await this.mutationAdmission?.assertMutationAdmission({\n operation: \"delete\",\n entityType: source.entityType,\n entityId: source.id,\n });\n return this.writeUpdatedEntity(\n {\n entity,\n options: {\n ...options,\n conditionalWrite: { expectedRevision: targetRevision },\n },\n },\n {\n condition: {\n entityType: source.entityType,\n entityId: source.id,\n expectedRevision: source.expectedRevision,\n },\n prior,\n },\n );\n }\n\n private async writeUpdatedEntity<T extends BaseEntity>(\n request: UpdateEntityRequest<T>,\n fold?: FoldRemoval,\n receipt?: EntityMutationReceiptKey,\n ): Promise<EntityMutationResult> {\n const prepared = await this.prepareUpdate(request, fold, receipt);\n if (prepared.stale) return contentConflict(prepared.entityId);\n const { plan } = prepared;\n if (plan.unchanged) return this.refreshUnchangedEntity(plan);\n\n await this.mutationAdmission?.assertMutationAdmission({\n operation: \"update\",\n entityType: plan.entity.entityType,\n entityId: plan.entity.id,\n });\n\n if ((await this.commitUpdate(plan)) === \"stale\")\n return contentConflict(plan.entity.id);\n return this.afterUpdateCommit(plan);\n }\n\n /** The markdown an update replaces, when it is stored. */\n private async storedContent(entity: BaseEntity): Promise<string | undefined> {\n const rows = await this.db\n .select({ content: entities.content })\n .from(entities)\n .where(\n and(\n eq(entities.id, entity.id),\n eq(entities.entityType, entity.entityType),\n ),\n )\n .limit(1);\n return rows.at(0)?.content;\n }\n\n /**\n * Validate and serialize an update, read the row it replaces, and settle\n * every check that can refuse or skip it before a transaction opens.\n */\n private async prepareUpdate<T extends BaseEntity>(\n request: UpdateEntityRequest<T>,\n fold: FoldRemoval | undefined,\n receipt: EntityMutationReceiptKey | undefined,\n ): Promise<PreparedEntityUpdate> {\n const { entity, options, stagedAsset } = request;\n options?.signal?.throwIfAborted();\n const condition =\n options?.conditionalWrite &&\n entityWriteConditionSchema.parse(options.conditionalWrite);\n if (\n condition &&\n (condition.expectedRevision === null ||\n options.expectedContentHash !== undefined)\n ) {\n throw new Error(\n \"Conditional replacement requires a revision and cannot combine preconditions\",\n );\n }\n const precondition: EntityWritePrecondition | undefined = condition\n ? { ...condition, entityType: entity.entityType, entityId: entity.id }\n : undefined;\n this.logger.debug(\n `Updating entity asynchronously: ${entity.entityType} with ID ${entity.id}`,\n );\n\n const assertGroupingsCurrent =\n this.entityRegistry.captureGroupingWriteGuard(entity.entityType);\n // Validate and serialize first to compute the new content hash\n const current = this.entitySerializer.withFrontmatterWrites(\n this.entitySerializer.withoutRetiredFields(entity),\n );\n const updatedEntity = {\n ...current,\n updated: new Date().toISOString(),\n contentHash: computeContentHash(current.content),\n };\n\n const validatedEntity = this.entityRegistry.validateEntity(\n entity.entityType,\n updatedEntity,\n );\n\n await validatePersist(this.entityRegistry, validatedEntity, \"update\");\n options?.signal?.throwIfAborted();\n\n const stored = this.entitySerializer.keepsStoredFrontmatter(validatedEntity)\n ? await this.storedContent(validatedEntity)\n : undefined;\n const { markdown, metadata } =\n this.entitySerializer.prepareEntityForStorage(\n validatedEntity,\n validatedEntity.entityType,\n stored,\n );\n\n const contentHash = computeContentHash(markdown);\n\n // Skip update only when all persisted fields are unchanged. Metadata-only\n // updates can leave serialized markdown/contentHash unchanged for adapters\n // that preserve frontmatter from content, but those DB metadata changes must\n // still persist for filtering/projections.\n const existing = await this.db\n .select({\n contentHash: entities.contentHash,\n visibility: entities.visibility,\n metadata: entities.metadata,\n })\n .from(entities)\n .where(\n and(\n eq(entities.id, validatedEntity.id),\n eq(entities.entityType, validatedEntity.entityType),\n ),\n )\n .limit(1);\n\n const existingEntity = existing.at(0);\n\n if (!existingEntity) {\n if (precondition)\n throw new EntityWriteConflictError(\n precondition.entityType,\n precondition.entityId,\n );\n throw new Error(\n `Entity not found: ${validatedEntity.entityType}:${validatedEntity.id}`,\n );\n }\n\n if (\n options?.expectedContentHash !== undefined &&\n existingEntity.contentHash !== options.expectedContentHash\n ) {\n this.logger.debug(\n `Skipping stale update for ${validatedEntity.entityType}:${validatedEntity.id}`,\n );\n return { stale: true, entityId: validatedEntity.id };\n }\n\n if (\n fold &&\n (validatedEntity.visibility !== fold.prior.visibility ||\n existingEntity.visibility !== fold.prior.visibility)\n ) {\n throw new EntityWriteConflictError(\n validatedEntity.entityType,\n validatedEntity.id,\n );\n }\n const stagedUpload = this.resolveStagedUpload(\n validatedEntity.entityType,\n validatedEntity.content,\n markdown,\n stagedAsset,\n );\n\n return {\n stale: false,\n plan: {\n entity: validatedEntity,\n options,\n precondition,\n fold,\n receipt,\n assertGroupingsCurrent,\n markdown,\n metadata,\n contentHash,\n stagedUpload,\n previousMetadata: existingEntity.metadata,\n unchanged:\n !precondition &&\n !receipt &&\n existingEntity.contentHash === contentHash &&\n existingEntity.visibility === validatedEntity.visibility &&\n stableJson(existingEntity.metadata) === stableJson(metadata),\n },\n };\n }\n\n /**\n * Every persisted field already matches the stored row: write nothing, but\n * take authority back from a projection, bind the asset, prune an excluded\n * FTS row, and journal the export.\n */\n private async refreshUnchangedEntity(\n plan: EntityUpdatePlan,\n ): Promise<EntityMutationResult> {\n const { entity, options } = plan;\n await this.projectionStore.transferEntityAuthority(\n {\n entityType: entity.entityType,\n id: entity.id,\n },\n async (transaction) => {\n options?.signal?.throwIfAborted();\n await plan.assertGroupingsCurrent();\n await this.bindAssetContent(\n transaction,\n entity.entityType,\n plan.markdown,\n plan.stagedUpload,\n );\n options?.signal?.throwIfAborted();\n await this.pruneFtsIndexIfExcluded(\n transaction,\n entity.id,\n entity.entityType,\n );\n return this.persistEntityExport(\n transaction,\n {\n entityType: entity.entityType,\n entityId: entity.id,\n operation: \"upsert\",\n },\n options?.persistenceOrigin,\n );\n },\n );\n this.logger.debug(\n `Skipping no-op update for ${entity.entityType}:${entity.id}`,\n );\n if (options?.eventContext) {\n await this.emitEntityEvent(\n entityUpdatedChannel,\n entity.entityType,\n entity.id,\n entity,\n plan.previousMetadata,\n options.eventContext,\n );\n }\n return { entityId: entity.id, jobId: \"\", skipped: true };\n }\n\n /**\n * Commit the update with its fold removal, FTS, both durable journals and\n * its receipt in one transaction. A row whose expected content hash changed\n * after preparation commits nothing and reports \"stale\".\n */\n private async commitUpdate(\n plan: EntityUpdatePlan,\n ): Promise<\"committed\" | \"stale\"> {\n const {\n entity,\n options,\n precondition,\n fold,\n receipt,\n markdown,\n metadata,\n contentHash,\n } = plan;\n try {\n await this.projectionStore.withDirtyInputs(\n [\n {\n sourceType: entity.entityType,\n sourceId: entity.id,\n revision: entityRevision({\n contentHash,\n metadata,\n visibility: entity.visibility,\n }),\n operation: \"upsert\",\n markedAt: this.projectionNow(),\n },\n ...(fold\n ? [\n {\n sourceType: fold.condition.entityType,\n sourceId: fold.condition.entityId,\n revision: `deleted:${fold.condition.expectedRevision}`,\n operation: \"delete\" as const,\n markedAt: this.projectionNow(),\n },\n ]\n : []),\n ],\n async (transaction) => {\n if (receipt)\n await this.mutationReceipts.assertVacant(transaction, receipt);\n if (fold)\n await assertEntityWriteCondition(\n transaction,\n fold.condition,\n fold.prior,\n );\n if (precondition)\n await assertEntityWriteCondition(transaction, precondition, entity);\n await this.guardEntityWrite(transaction, plan);\n // Cancellation after this boundary must not split the entity from its journals.\n const updateResult = await transaction\n .update(entities)\n .set({\n content: markdown,\n contentHash,\n visibility: entity.visibility,\n metadata,\n updated: new Date(entity.updated).getTime(),\n })\n .where(\n and(\n eq(entities.id, entity.id),\n eq(entities.entityType, entity.entityType),\n options?.expectedContentHash !== undefined\n ? eq(entities.contentHash, options.expectedContentHash)\n : undefined,\n ),\n );\n if (\n (precondition || options?.expectedContentHash !== undefined) &&\n Number(updateResult.rowsAffected) === 0\n ) {\n if (precondition)\n throw new EntityWriteConflictError(\n precondition.entityType,\n precondition.entityId,\n );\n throw new StaleEntityUpdateError();\n }\n if (fold) {\n await transaction\n .delete(entities)\n .where(\n and(\n eq(entities.entityType, fold.prior.entityType),\n eq(entities.id, fold.prior.id),\n ),\n );\n await this.recordEntityRemoval(\n transaction,\n { entityType: fold.prior.entityType, entityId: fold.prior.id },\n options?.persistenceOrigin,\n );\n }\n await this.recordEntityUpsert(\n transaction,\n {\n operation: \"update\",\n entityType: entity.entityType,\n entityId: entity.id,\n markdown,\n },\n receipt,\n options?.persistenceOrigin,\n );\n },\n );\n } catch (error) {\n if (!(error instanceof StaleEntityUpdateError)) throw error;\n this.logger.debug(\n `Skipping concurrently stale update for ${entity.entityType}:${entity.id}`,\n );\n return \"stale\";\n }\n return \"committed\";\n }\n\n private async afterUpdateCommit(\n plan: EntityUpdatePlan,\n ): Promise<EntityMutationResult> {\n const { entity, options, fold } = plan;\n // Recoverable cross-database/index and notification work starts only after\n // the entity pair, FTS and both durable journals have committed.\n if (fold)\n await this.embeddingIndex.deleteEmbedding(\n fold.prior.entityType,\n fold.prior.id,\n );\n await this.notifyProjectionScheduler();\n\n if (fold)\n await this.emitEntityEvent(\n entityDeletedChannel,\n fold.prior.entityType,\n fold.prior.id,\n fold.prior,\n undefined,\n options?.eventContext,\n );\n this.logger.debug(\n `Updated entity ${entity.entityType}:${entity.id} immediately`,\n );\n\n await this.emitEntityEvent(\n entityUpdatedChannel,\n entity.entityType,\n entity.id,\n entity,\n // Prior metadata lets projections (e.g. series) reconcile a moved value\n // such as a changed `seriesName` without a full resync. Already loaded\n // by prepareUpdate for the no-op check, so this adds no extra read.\n plan.previousMetadata,\n options?.eventContext,\n );\n\n return this.enqueueEmbedding(\n {\n entityId: entity.id,\n entityType: entity.entityType,\n contentHash: plan.contentHash,\n operation: \"update\",\n },\n options,\n );\n }\n\n /** Delete the entities contained in a container, one by one. */\n private async deleteContents(\n containerType: string,\n containerId: string,\n persistenceOrigin: EntityJobOptions[\"persistenceOrigin\"],\n ): Promise<void> {\n const prefix = `${containerId}:`;\n const containedTypes = [...this.entityRegistry.getContainment()]\n .filter(([, container]) => container === containerType)\n .map(([type]) => type);\n const contents = await Promise.all(\n containedTypes.map(async (type) =>\n (\n await this.db\n .select({ id: entities.id })\n .from(entities)\n .where(\n and(\n eq(entities.entityType, type),\n sql`substr(${entities.id}, 1, ${prefix.length}) = ${prefix}`,\n ),\n )\n ).map(({ id }) => ({ entityType: type, id })),\n ),\n );\n await contents.flat().reduce<Promise<void>>(async (previous, content) => {\n await previous;\n await this.deleteEntity({\n ...content,\n ...(persistenceOrigin !== undefined && {\n options: { persistenceOrigin },\n }),\n });\n }, Promise.resolve());\n }\n\n /**\n * Delete an entity by type and ID\n */\n public async deleteEntity(request: DeleteEntityRequest): Promise<boolean> {\n const { entityType, id, options } = request;\n\n // Fetch prior entity so subscribers can gate on its metadata (e.g. the\n // `seriesName` field that drives the series projection). Without this,\n // every delete forces subscribers into a full resync because they can't\n // tell whether the deleted entity was relevant to them.\n // Authorization belongs to the calling capability. This internal mutation\n // must find the admitted row at every visibility tier, not silently turn a\n // shared/restricted deletion into a public-scoped lookup miss.\n const priorData = await this.entityQueries.getEntityData(\n entityType,\n id,\n internalFullScope(\"delete prior-state lookup, internal mutation\"),\n );\n // A purged type is no longer registered: its rows have no adapter to parse.\n const prior =\n priorData && this.entityRegistry.hasEntityType(entityType)\n ? ((await this.entitySerializer.convertToEntity(priorData)) ??\n undefined)\n : undefined;\n\n if (priorData) {\n await this.mutationAdmission?.assertMutationAdmission({\n operation: \"delete\",\n entityType,\n entityId: id,\n });\n }\n\n if (!priorData) return false;\n const expectedContentHash = options?.expectedContentHash;\n // A container goes with its contents, which go first: a failure part way\n // leaves the container, never contents without one.\n await this.deleteContents(entityType, id, options?.persistenceOrigin);\n if (\n expectedContentHash !== undefined &&\n priorData.contentHash !== expectedContentHash\n ) {\n return false;\n }\n\n // Embeddings live in another database and are recoverable by backfill; the\n // entity row, FTS row, and scheduler journal share one atomic transaction.\n await this.embeddingIndex.deleteEmbedding(entityType, id);\n try {\n await this.projectionStore.withDirtyInput(\n {\n sourceType: entityType,\n sourceId: id,\n revision: `deleted:${entityRevision({\n contentHash: priorData.contentHash,\n metadata: priorData.metadata,\n visibility: priorData.visibility,\n })}`,\n operation: \"delete\",\n markedAt: this.projectionNow(),\n },\n async (transaction) => {\n const deleteResult = await transaction\n .delete(entities)\n .where(\n and(\n eq(entities.entityType, entityType),\n eq(entities.id, id),\n expectedContentHash !== undefined\n ? eq(entities.contentHash, expectedContentHash)\n : undefined,\n ),\n );\n if (\n expectedContentHash !== undefined &&\n Number(deleteResult.rowsAffected) === 0\n ) {\n throw new StaleEntityUpdateError();\n }\n await this.recordEntityRemoval(\n transaction,\n { entityType, entityId: id },\n options?.persistenceOrigin,\n );\n },\n );\n } catch (error) {\n if (!(error instanceof StaleEntityUpdateError)) throw error;\n // Changed between the check and the write: nothing was deleted. Its\n // embedding comes back through backfill.\n this.logger.debug(\n `Skipping concurrently stale delete for ${entityType}:${id}`,\n );\n return false;\n }\n await this.notifyProjectionScheduler();\n\n await this.emitEntityEvent(\n entityDeletedChannel,\n entityType,\n id,\n prior,\n undefined,\n options?.eventContext,\n );\n\n return true;\n }\n\n /**\n * Create or update an entity based on existence\n */\n public async upsertEntity<T extends BaseEntity>(\n request: UpsertEntityRequest<T>,\n ): Promise<EntityMutationResult & { created: boolean }> {\n const { entity, options, stagedAsset } = request;\n this.logger.debug(\n `Upserting entity of type ${entity.entityType} with ID ${entity.id}`,\n );\n\n if (options?.conditionalWrite) {\n const created = options.conditionalWrite.expectedRevision === null;\n const result = created\n ? await this.createEntity({ entity, options, stagedAsset })\n : await this.updateEntity({ entity, options, stagedAsset });\n return { ...result, created };\n }\n\n const exists = await this.entityQueries.entityExists(\n entity.entityType,\n entity.id,\n );\n\n if (exists) {\n const result = await this.updateEntity({\n entity,\n ...(stagedAsset !== undefined && { stagedAsset }),\n ...(options !== undefined && { options }),\n });\n return { ...result, created: false };\n }\n\n try {\n const result = await this.createEntity({\n entity,\n ...(stagedAsset !== undefined && { stagedAsset }),\n ...(options !== undefined && { options }),\n });\n return { ...result, created: true };\n } catch (error) {\n // A concurrent create can win between the existence check and the\n // insert — fall through to the update path instead of surfacing the\n // raw unique-constraint violation.\n if (!isUniqueConstraintError(error)) {\n throw error;\n }\n this.logger.debug(\n `Entity ${entity.entityType}:${entity.id} was created concurrently, updating instead`,\n );\n const result = await this.updateEntity({\n entity,\n ...(stagedAsset !== undefined && { stagedAsset }),\n ...(options !== undefined && { options }),\n });\n return { ...result, created: false };\n }\n }\n\n /** Reconcile indexes and lifecycle subscribers after atomic projection writes. */\n public async reconcileProjectionTargets(\n targets: readonly ProjectionChangedTarget[],\n ): Promise<void> {\n await Promise.all(\n targets.map(async (target) => {\n if (target.operation === \"delete\") {\n await this.emitEntityEvent(\n entityDeletedChannel,\n target.entityType,\n target.entityId,\n );\n await this.embeddingIndex.deleteEmbedding(\n target.entityType,\n target.entityId,\n );\n return;\n }\n if (!target.contentHash) {\n throw new Error(\n `Projection target ${target.entityType}:${target.entityId} has no content hash`,\n );\n }\n await this.emitEntityEvent(\n entityUpdatedChannel,\n target.entityType,\n target.entityId,\n );\n await this.embeddingIndex.enqueue({\n entityId: target.entityId,\n entityType: target.entityType,\n contentHash: target.contentHash,\n operation: \"update\",\n });\n }),\n );\n }\n\n /**\n * Store embedding for an entity\n * Used by embedding job handler to store embedding in the embeddings table\n * Entity must already exist in entities table\n */\n public async storeEmbedding(data: StoreEmbeddingData): Promise<void> {\n await this.embeddingIndex.store(data);\n }\n\n public async backfillMissingEmbeddings(): Promise<EmbeddingBackfillResult> {\n return this.embeddingIndex.backfillMissing();\n }\n\n public async getEmbeddingIndexStats(): Promise<EmbeddingIndexStats> {\n return this.embeddingIndex.getIndexStats();\n }\n\n private resolveStagedUpload(\n entityType: string,\n entityContent: string,\n storedContent: string,\n stagedAsset: CreateEntityRequest<BaseEntity>[\"stagedAsset\"],\n ): StagedUpload | undefined {\n const assetBacked =\n this.entityRegistry.getEntityTypeConfig(entityType).binaryStorage ===\n \"asset\";\n if (!stagedAsset) return undefined;\n if (!assetBacked) {\n throw new Error(\n `Entity type ${entityType} is not registered for asset-backed storage`,\n );\n }\n if (\n entityContent !== stagedAsset.ref ||\n storedContent !== stagedAsset.ref\n ) {\n throw new Error(\n `Staged asset ${stagedAsset.ref} does not match canonical ${entityType} content`,\n );\n }\n return this.assetRepository.claimedUpload(stagedAsset);\n }\n\n private async bindAssetContent(\n transaction: AssetTransaction,\n entityType: string,\n storedContent: string,\n stagedUpload?: StagedUpload,\n ): Promise<void> {\n if (\n this.entityRegistry.getEntityTypeConfig(entityType).binaryStorage !==\n \"asset\"\n ) {\n return;\n }\n await this.assetRepository.bindEntityContent(\n transaction,\n storedContent,\n stagedUpload,\n );\n }\n\n /**\n * The last refusals before an entity row is written, inside its transaction:\n * asset binding, the caller's guard over the final persisted fields,\n * cancellation, and grouping currency.\n */\n private async guardEntityWrite(\n transaction: EntityTransaction,\n write: EntityWriteGuard,\n ): Promise<void> {\n const { entity, markdown, contentHash, metadata, options } = write;\n await this.bindAssetContent(\n transaction,\n entity.entityType,\n markdown,\n write.stagedUpload,\n );\n await options?.beforeWrite?.({\n ...entity,\n content: markdown,\n contentHash,\n metadata,\n });\n options?.signal?.throwIfAborted();\n await write.assertGroupingsCurrent();\n options?.signal?.throwIfAborted();\n }\n\n /** Index, journal and receipt an entity row written in this transaction. */\n private async recordEntityUpsert(\n transaction: EntityTransaction,\n write: {\n operation: \"create\" | \"update\";\n entityType: string;\n entityId: string;\n markdown: string;\n },\n receipt: EntityMutationReceiptKey | undefined,\n origin: EntityJobOptions[\"persistenceOrigin\"],\n ): Promise<void> {\n const { operation, entityType, entityId } = write;\n await this.syncFtsIndex(transaction, entityId, entityType, write.markdown);\n await this.persistEntityExport(\n transaction,\n { entityType, entityId, operation: \"upsert\" },\n origin,\n );\n if (receipt)\n await this.mutationReceipts.record(transaction, receipt, {\n operation,\n entityType,\n entityId,\n });\n }\n\n /** Unindex and journal an entity row deleted in this transaction. */\n private async recordEntityRemoval(\n transaction: EntityTransaction,\n target: { entityType: string; entityId: string },\n origin: EntityJobOptions[\"persistenceOrigin\"],\n ): Promise<void> {\n await this.deleteFtsIndex(transaction, target.entityId, target.entityType);\n await this.persistEntityExport(\n transaction,\n { ...target, operation: \"delete\" },\n origin,\n );\n }\n\n private enqueueEmbedding(\n target: Pick<\n EnqueueEmbeddingInput,\n \"entityId\" | \"entityType\" | \"contentHash\" | \"operation\"\n >,\n options: EntityJobOptions | undefined,\n ): Promise<EntityMutationResult> {\n return this.embeddingIndex.enqueue({\n ...target,\n ...(options?.priority !== undefined && { priority: options.priority }),\n ...(options?.maxRetries !== undefined && {\n maxRetries: options.maxRetries,\n }),\n ...(options?.eventContext && { eventContext: options.eventContext }),\n });\n }\n\n /** Synchronize FTS independently from vector embedding policy. */\n private async syncFtsIndex(\n database: Pick<EntityDB, \"run\">,\n entityId: string,\n entityType: string,\n content: string,\n ): Promise<void> {\n await this.deleteFtsIndex(database, entityId, entityType);\n if (!this.isFullTextSearchable(entityType)) return;\n await insertEntityFts(database, entityType, entityId, content);\n }\n\n private async pruneFtsIndexIfExcluded(\n database: Pick<EntityDB, \"run\">,\n entityId: string,\n entityType: string,\n ): Promise<void> {\n if (this.isFullTextSearchable(entityType)) return;\n await this.deleteFtsIndex(database, entityId, entityType);\n }\n\n private async deleteFtsIndex(\n database: Pick<EntityDB, \"run\">,\n entityId: string,\n entityType: string,\n ): Promise<void> {\n await deleteEntityFts(database, entityType, entityId);\n }\n\n private isFullTextSearchable(entityType: string): boolean {\n return (\n this.entityRegistry.getEntityTypeConfig(entityType).fullTextSearchable !==\n false\n );\n }\n\n /**\n * Find a unique ID by appending -2, -3, etc. if the base ID already exists.\n */\n private async resolveUniqueId(\n baseId: string,\n entityType: string,\n ): Promise<string> {\n const exists = await this.entityQueries.entityExists(entityType, baseId);\n\n if (!exists) {\n return baseId;\n }\n\n // Try suffixes -2, -3, ... up to a reasonable limit\n for (let suffix = 2; suffix <= 100; suffix++) {\n const candidateId = `${baseId}-${suffix}`;\n const taken = await this.entityQueries.entityExists(\n entityType,\n candidateId,\n );\n\n if (!taken) {\n this.logger.debug(`Deduplicated entity ID: ${baseId} → ${candidateId}`);\n return candidateId;\n }\n }\n\n // Extremely unlikely fallback: append random suffix\n const fallbackId = `${baseId}-${createId().slice(0, 8)}`;\n this.logger.warn(\n `Could not deduplicate entity ID after 100 attempts, using random suffix: ${fallbackId}`,\n );\n return fallbackId;\n }\n\n public async wakeProjectionScheduler(): Promise<void> {\n await this.notifyProjectionScheduler();\n }\n\n private async notifyProjectionScheduler(): Promise<void> {\n try {\n await this.projectionWakeup?.();\n } catch (error) {\n // The durable journal remains pending for the next wakeup or restart.\n this.logger.error(\"Failed to wake projection scheduler\", error);\n }\n }\n\n /**\n * Broadcast an entity lifecycle event via the message bus\n */\n private async emitEntityEvent(\n channel: Channel<EntityChangePayload>,\n entityType: string,\n entityId: string,\n entity?: BaseEntity,\n previousMetadata?: BaseEntity[\"metadata\"],\n eventContext?: EntityMutationEventContext,\n ): Promise<void> {\n if (!this.messageBus) {\n return;\n }\n\n this.logger.debug(`Emitting ${channel.name} for ${entityType}:${entityId}`);\n\n const payload: EntityChangePayload = {\n entityType,\n entityId,\n ...(eventContext?.conversationId\n ? { conversationId: eventContext.conversationId }\n : {}),\n ...(eventContext?.channelId ? { channelId: eventContext.channelId } : {}),\n ...(eventContext?.runId ? { runId: eventContext.runId } : {}),\n ...(eventContext?.toolCallId\n ? { toolCallId: eventContext.toolCallId }\n : {}),\n ...(eventContext?.actor ? { actor: eventContext.actor } : {}),\n ...(eventContext?.interfaceType\n ? { interfaceType: eventContext.interfaceType }\n : {}),\n ...(entity ? { entity: { ...entity } } : {}),\n ...(previousMetadata ? { previousMetadata } : {}),\n };\n\n try {\n await broadcastChannel(\n this.messageBus,\n channel,\n payload,\n \"entity-service\",\n );\n } catch (error) {\n // Lifecycle delivery is a wake-up optimization. The durable export and\n // projection journals remain available for startup/periodic recovery.\n this.logger.error(\n `Failed to publish ${channel.name} for ${entityType}:${entityId}`,\n error,\n );\n }\n }\n\n private async persistEntityExport(\n transaction: EntityExportTransaction,\n target: {\n entityType: string;\n entityId: string;\n operation: \"upsert\" | \"delete\";\n },\n origin: EntityJobOptions[\"persistenceOrigin\"],\n ): Promise<void> {\n if (origin === \"directory-sync\") {\n await this.entityExportStore.clear(transaction, target);\n return;\n }\n await this.entityExportStore.record(transaction, {\n ...target,\n markedAt: this.projectionNow(),\n });\n }\n}\n",
280
+ "import { internalFullScope } from \"./internal-scope\";\nimport { deleteEntityFts, insertEntityFts } from \"./entity-fts\";\nimport type { Channel } from \"@brains/contracts\";\nimport { broadcastChannel } from \"@brains/messaging-service\";\nimport {\n entityCreatedChannel,\n entityDeletedChannel,\n entityUpdatedChannel,\n type EntityChangePayload,\n} from \"./entity-event-channels\";\nimport type { EntityDB } from \"./db\";\nimport { EntityMutationReceiptStore } from \"./entity-mutation-receipt-store\";\nimport {\n EntityMutationAlreadyAppliedError,\n type EntityMutationReceipt,\n type EntityMutationReceiptKey,\n} from \"./entity-mutation-receipt\";\nimport { snapshotEntityMutation } from \"./entity-mutation-request\";\nimport type { EmbeddingDB } from \"./db/embedding-db\";\nimport type {\n AssetTransaction,\n SqliteAssetRepository,\n StagedUpload,\n} from \"./sqlite-asset-repository\";\nimport type {\n BaseEntity,\n EntityJobOptions,\n EntityMutationEventContext,\n EntityMutationResult,\n EmbeddingBackfillResult,\n EmbeddingIndexStats,\n StoreEmbeddingData,\n EntityEventBus,\n DeleteEntityRequest,\n CreateEntityRequest,\n UpdateEntityRequest,\n UpdateEntityOptions,\n FoldEntityRequest,\n ApplyEntityMutationOnceRequest,\n UpsertEntityRequest,\n EntityRegistry,\n EntityMutationAdmission,\n} from \"./types\";\nimport type { EntitySerializer } from \"./entity-serializer\";\nimport type { EntityQueries } from \"./entity-queries\";\nimport type { ProjectionStore } from \"./projection-store\";\nimport type {\n EntityExportStore,\n EntityExportTransaction,\n} from \"./entity-export-store\";\nimport type { IJobQueueService } from \"@brains/job-queue\";\nimport { createId } from \"@brains/utils/id\";\nimport { z } from \"@brains/utils/zod\";\nimport type { Logger } from \"@brains/utils/logger\";\nimport { computeContentHash } from \"@brains/utils/hash\";\nimport { entities } from \"./schema/entities\";\nimport type { ProjectionChangedTarget } from \"./schema/projection-state\";\nimport {\n EmbeddingIndexCoordinator,\n type EnqueueEmbeddingInput,\n} from \"./embedding-index-coordinator\";\nimport type { EntityTransaction } from \"./projection-transaction-runner\";\nimport { and, eq, sql } from \"drizzle-orm\";\nimport {\n entityWriteConditionSchema,\n EntityWriteConflictError,\n} from \"./entity-write-contracts\";\nimport {\n assertEntityWriteCondition,\n type EntityWritePrecondition,\n} from \"./entity-write-state\";\nimport { entityRevision, stableJson } from \"./entity-revision\";\nimport {\n isSchemaPhaseValidationError,\n toEntityValidationError,\n} from \"./errors\";\n\n/** Shared by ordinary mutations and atomic projection upserts. */\nexport async function validatePersist(\n registry: EntityRegistry,\n entity: BaseEntity,\n operation: \"create\" | \"update\",\n): Promise<void> {\n try {\n await registry.getPersistValidator(entity.entityType)?.(entity, {\n operation,\n });\n } catch (error) {\n // A validator that finds the content itself invalid says so with a\n // schema-phase error, which sync quarantines; any other refusal is a live\n // policy, which sync retries.\n if (isSchemaPhaseValidationError(error)) throw error;\n throw toEntityValidationError(entity.entityType, error, \"persist\") ?? error;\n }\n}\n\nfunction isUniqueConstraintError(error: unknown): boolean {\n // Drizzle wraps the LibsqlError, so walk the cause chain\n for (let current = error; current instanceof Error; current = current.cause) {\n if (\n current.message.includes(\"UNIQUE constraint failed\") ||\n current.message.includes(\"SQLITE_CONSTRAINT\")\n ) {\n return true;\n }\n }\n return false;\n}\n\nclass StaleEntityUpdateError extends Error {}\n\nconst foldSourceSchema = z.strictObject({\n entityType: z.string().min(1),\n id: z.string().min(1),\n expectedRevision: z.string().min(1),\n});\ninterface FoldRemoval {\n condition: EntityWritePrecondition;\n prior: BaseEntity;\n}\n\n/** What the final in-transaction checks see of an entity about to be written. */\ninterface EntityWriteGuard {\n /** Carries the final ID. */\n entity: BaseEntity;\n markdown: string;\n metadata: Record<string, unknown>;\n contentHash: string;\n stagedUpload: StagedUpload | undefined;\n options: Pick<UpdateEntityOptions, \"signal\" | \"beforeWrite\"> | undefined;\n assertGroupingsCurrent: () => Promise<void>;\n}\n\n/** A validated, serialized update and the stored row it replaces. */\ninterface EntityUpdatePlan extends EntityWriteGuard {\n options: UpdateEntityOptions | undefined;\n precondition: EntityWritePrecondition | undefined;\n fold: FoldRemoval | undefined;\n receipt: EntityMutationReceiptKey | undefined;\n previousMetadata: BaseEntity[\"metadata\"];\n /** Every persisted field already matches the stored row. */\n unchanged: boolean;\n}\n\ntype PreparedEntityUpdate =\n { stale: true; entityId: string } | { stale: false; plan: EntityUpdatePlan };\n\n/** The stored content hash no longer matches the caller's expectation. */\nfunction contentConflict(entityId: string): EntityMutationResult {\n return { entityId, jobId: \"\", skipped: true, skipReason: \"content-conflict\" };\n}\n\nexport interface EntityMutationDeps {\n db: EntityDB;\n entityRegistry: EntityRegistry;\n entitySerializer: EntitySerializer;\n entityQueries: EntityQueries;\n jobQueueService: IJobQueueService;\n logger: Logger;\n messageBus?: EntityEventBus;\n mutationAdmission?: EntityMutationAdmission;\n projectionStore: ProjectionStore;\n assetRepository: SqliteAssetRepository;\n entityExportStore: EntityExportStore;\n projectionNow: () => number;\n /** Embedding DB for writes (separate from entity DB). */\n embeddingDb: EmbeddingDB;\n embeddingsEnabled: boolean;\n /** Retries refused embedding enqueues; see EmbeddingIndexCoordinator. */\n embeddingRetries?: ConstructorParameters<\n typeof EmbeddingIndexCoordinator\n >[0][\"retries\"];\n}\n\n/**\n * EntityMutations handles all write operations for entities\n * Extracted from EntityService for single responsibility\n */\nexport class EntityMutations {\n private db: EntityDB;\n private readonly mutationReceipts: EntityMutationReceiptStore;\n private entityRegistry: EntityRegistry;\n private entitySerializer: EntitySerializer;\n private entityQueries: EntityQueries;\n private messageBus?: EntityEventBus;\n private mutationAdmission?: EntityMutationAdmission;\n private readonly projectionStore: ProjectionStore;\n private readonly assetRepository: SqliteAssetRepository;\n private readonly entityExportStore: EntityExportStore;\n private readonly projectionNow: () => number;\n private readonly embeddingIndex: EmbeddingIndexCoordinator;\n private projectionWakeup: (() => Promise<void>) | undefined;\n private logger: Logger;\n\n constructor(deps: EntityMutationDeps) {\n this.db = deps.db;\n this.mutationReceipts = new EntityMutationReceiptStore(deps.db);\n this.entityRegistry = deps.entityRegistry;\n this.entitySerializer = deps.entitySerializer;\n this.entityQueries = deps.entityQueries;\n this.projectionStore = deps.projectionStore;\n this.assetRepository = deps.assetRepository;\n this.entityExportStore = deps.entityExportStore;\n this.projectionNow = deps.projectionNow;\n this.logger = deps.logger.child(\"EntityMutations\");\n this.embeddingIndex = new EmbeddingIndexCoordinator({\n entityDb: deps.db,\n embeddingDb: deps.embeddingDb,\n entityRegistry: deps.entityRegistry,\n jobQueueService: deps.jobQueueService,\n logger: this.logger,\n embeddingsEnabled: deps.embeddingsEnabled,\n retries: deps.embeddingRetries,\n });\n if (deps.messageBus) {\n this.messageBus = deps.messageBus;\n }\n if (deps.mutationAdmission) {\n this.mutationAdmission = deps.mutationAdmission;\n }\n }\n\n public setProjectionWakeup(wakeup: () => Promise<void>): () => void {\n this.projectionWakeup = wakeup;\n let active = true;\n return (): void => {\n if (!active) return;\n active = false;\n if (this.projectionWakeup === wakeup) this.projectionWakeup = undefined;\n };\n }\n\n /**\n * Create a new entity (returns immediately, embedding generated in background)\n */\n public getEntityMutationReceipt(\n key: EntityMutationReceiptKey,\n ): Promise<EntityMutationReceipt | null> {\n return this.mutationReceipts.get(key);\n }\n\n public async applyEntityMutationOnce(\n input: ApplyEntityMutationOnceRequest,\n ): Promise<{ receipt: EntityMutationReceipt; applied: boolean }> {\n const mutation = snapshotEntityMutation(input);\n const key = mutation.receipt;\n const prior = await this.mutationReceipts.get(key);\n if (prior) return { receipt: prior, applied: false };\n if (mutation.operation === \"none\")\n return {\n receipt: await this.mutationReceipts.completeWithoutWrite(key),\n applied: false,\n };\n try {\n const result =\n mutation.operation === \"create\"\n ? await this.writeCreatedEntity(mutation.request, key)\n : await this.writeUpdatedEntity(mutation.request, undefined, key);\n if (result.skipReason === \"content-conflict\") {\n throw new EntityWriteConflictError(\n mutation.request.entity.entityType,\n result.entityId,\n );\n }\n const receipt = await this.mutationReceipts.get(key);\n if (!receipt)\n throw new Error(\"Missing committed entity mutation receipt\");\n return { receipt, applied: true };\n } catch (error) {\n if (error instanceof EntityMutationAlreadyAppliedError)\n return { receipt: error.receipt, applied: false };\n throw error;\n }\n }\n\n public createEntity<T extends BaseEntity>(\n request: CreateEntityRequest<T>,\n ): Promise<EntityMutationResult> {\n return this.writeCreatedEntity(request);\n }\n\n private async writeCreatedEntity<T extends BaseEntity>(\n request: CreateEntityRequest<T>,\n receipt?: EntityMutationReceiptKey,\n ): Promise<EntityMutationResult> {\n const { entity, options, stagedAsset } = request;\n options?.signal?.throwIfAborted();\n const condition =\n options?.conditionalWrite &&\n entityWriteConditionSchema.parse(options.conditionalWrite);\n if (\n condition &&\n (condition.expectedRevision !== null ||\n options.deduplicateId ||\n !entity.id)\n ) {\n throw new Error(\n \"Conditional creation requires an explicit ID, an absent precondition, and no deduplication\",\n );\n }\n const precondition: EntityWritePrecondition | undefined = condition\n ? {\n ...condition,\n entityType: entity.entityType,\n entityId: entity.id ?? \"\",\n }\n : undefined;\n this.logger.debug(\n `Creating entity asynchronously of type: ${entity[\"entityType\"]}`,\n );\n\n const assertGroupingsCurrent =\n this.entityRegistry.captureGroupingWriteGuard(entity.entityType);\n // Generate ID, timestamps, and contentHash if not provided\n const now = new Date().toISOString();\n const current = this.entitySerializer.withoutRetiredFields(entity);\n const entityWithDefaults = {\n ...current,\n id: entity.id ?? createId(),\n created: entity.created ?? now,\n updated: entity.updated ?? now,\n contentHash: computeContentHash(current.content),\n };\n\n // Validate entity against its schema\n const validatedEntity = this.entityRegistry.validateEntity(\n entity[\"entityType\"],\n entityWithDefaults,\n );\n\n await validatePersist(this.entityRegistry, validatedEntity, \"create\");\n options?.signal?.throwIfAborted();\n\n // Prepare entity for storage\n const { markdown, metadata } =\n this.entitySerializer.prepareEntityForStorage(\n validatedEntity,\n validatedEntity.entityType,\n );\n\n // Compute contentHash from the serialized markdown\n const contentHash = computeContentHash(markdown);\n const stagedUpload = this.resolveStagedUpload(\n validatedEntity.entityType,\n validatedEntity.content,\n markdown,\n stagedAsset,\n );\n\n // Resolve final ID (may deduplicate on collision)\n let finalId = validatedEntity.id;\n if (options?.deduplicateId) {\n finalId = await this.resolveUniqueId(\n validatedEntity.id,\n validatedEntity.entityType,\n );\n }\n\n await this.mutationAdmission?.assertMutationAdmission({\n operation: \"create\",\n entityType: validatedEntity.entityType,\n entityId: finalId,\n });\n\n // Persist the entity, search row, and scheduler journal atomically.\n await this.projectionStore.withDirtyInput(\n {\n sourceType: validatedEntity.entityType,\n sourceId: finalId,\n revision: entityRevision({\n contentHash,\n metadata,\n visibility: validatedEntity.visibility,\n }),\n operation: \"upsert\",\n markedAt: this.projectionNow(),\n },\n async (transaction) => {\n if (receipt)\n await this.mutationReceipts.assertVacant(transaction, receipt);\n if (precondition)\n await assertEntityWriteCondition(\n transaction,\n precondition,\n validatedEntity,\n );\n await this.guardEntityWrite(transaction, {\n entity: { ...validatedEntity, id: finalId },\n markdown,\n metadata,\n contentHash,\n stagedUpload,\n options,\n assertGroupingsCurrent,\n });\n // Once the entity write starts, settle the complete atomic mutation.\n await transaction.insert(entities).values({\n id: finalId,\n entityType: validatedEntity.entityType,\n content: markdown,\n contentHash,\n visibility: validatedEntity.visibility,\n metadata,\n created: new Date(validatedEntity.created).getTime(),\n updated: new Date(validatedEntity.updated).getTime(),\n });\n await this.recordEntityUpsert(\n transaction,\n {\n operation: \"create\",\n entityType: validatedEntity.entityType,\n entityId: finalId,\n markdown,\n },\n receipt,\n options?.persistenceOrigin,\n );\n },\n );\n await this.notifyProjectionScheduler();\n\n this.logger.debug(\n `Persisted entity ${validatedEntity.entityType}:${finalId} immediately`,\n );\n\n await this.emitEntityEvent(\n entityCreatedChannel,\n validatedEntity.entityType,\n finalId,\n {\n ...validatedEntity,\n id: finalId,\n },\n undefined,\n options?.eventContext,\n );\n\n return this.enqueueEmbedding(\n {\n entityId: finalId,\n entityType: validatedEntity.entityType,\n contentHash,\n operation: \"create\",\n },\n options,\n );\n }\n\n /**\n * Update an existing entity (returns immediately, embedding generated in background)\n */\n public updateEntity<T extends BaseEntity>(\n request: UpdateEntityRequest<T>,\n ): Promise<EntityMutationResult> {\n return this.writeUpdatedEntity(request);\n }\n\n public async foldEntity(\n request: FoldEntityRequest,\n ): Promise<EntityMutationResult> {\n // Capture the admitted pair before any asynchronous policy/serialization work.\n const source = foldSourceSchema.parse(request.source);\n const targetRevision = z.string().min(1).parse(request.targetRevision);\n const entity = structuredClone(request.entity);\n const options = { ...request.options };\n if (source.entityType !== entity.entityType || source.id === entity.id) {\n throw new Error(\"A fold requires two distinct entities of the same type\");\n }\n options.signal?.throwIfAborted();\n const priorData = await this.entityQueries.getEntityData(\n source.entityType,\n source.id,\n internalFullScope(\"fold revision check, internal mutation\"),\n );\n if (!priorData || entityRevision(priorData) !== source.expectedRevision) {\n throw new EntityWriteConflictError(source.entityType, source.id);\n }\n const prior = await this.entitySerializer.convertToEntity(priorData);\n if (prior?.visibility !== entity.visibility) {\n throw new Error(\"A fold cannot cross visibility scopes\");\n }\n await this.mutationAdmission?.assertMutationAdmission({\n operation: \"delete\",\n entityType: source.entityType,\n entityId: source.id,\n });\n return this.writeUpdatedEntity(\n {\n entity,\n options: {\n ...options,\n conditionalWrite: { expectedRevision: targetRevision },\n },\n },\n {\n condition: {\n entityType: source.entityType,\n entityId: source.id,\n expectedRevision: source.expectedRevision,\n },\n prior,\n },\n );\n }\n\n private async writeUpdatedEntity<T extends BaseEntity>(\n request: UpdateEntityRequest<T>,\n fold?: FoldRemoval,\n receipt?: EntityMutationReceiptKey,\n ): Promise<EntityMutationResult> {\n const prepared = await this.prepareUpdate(request, fold, receipt);\n if (prepared.stale) return contentConflict(prepared.entityId);\n const { plan } = prepared;\n if (plan.unchanged) return this.refreshUnchangedEntity(plan);\n\n await this.mutationAdmission?.assertMutationAdmission({\n operation: \"update\",\n entityType: plan.entity.entityType,\n entityId: plan.entity.id,\n });\n\n if ((await this.commitUpdate(plan)) === \"stale\")\n return contentConflict(plan.entity.id);\n return this.afterUpdateCommit(plan);\n }\n\n /** The markdown an update replaces, when it is stored. */\n private async storedContent(entity: BaseEntity): Promise<string | undefined> {\n const rows = await this.db\n .select({ content: entities.content })\n .from(entities)\n .where(\n and(\n eq(entities.id, entity.id),\n eq(entities.entityType, entity.entityType),\n ),\n )\n .limit(1);\n return rows.at(0)?.content;\n }\n\n /**\n * Validate and serialize an update, read the row it replaces, and settle\n * every check that can refuse or skip it before a transaction opens.\n */\n private async prepareUpdate<T extends BaseEntity>(\n request: UpdateEntityRequest<T>,\n fold: FoldRemoval | undefined,\n receipt: EntityMutationReceiptKey | undefined,\n ): Promise<PreparedEntityUpdate> {\n const { entity, options, stagedAsset } = request;\n options?.signal?.throwIfAborted();\n const condition =\n options?.conditionalWrite &&\n entityWriteConditionSchema.parse(options.conditionalWrite);\n if (\n condition &&\n (condition.expectedRevision === null ||\n options.expectedContentHash !== undefined)\n ) {\n throw new Error(\n \"Conditional replacement requires a revision and cannot combine preconditions\",\n );\n }\n const precondition: EntityWritePrecondition | undefined = condition\n ? { ...condition, entityType: entity.entityType, entityId: entity.id }\n : undefined;\n this.logger.debug(\n `Updating entity asynchronously: ${entity.entityType} with ID ${entity.id}`,\n );\n\n const assertGroupingsCurrent =\n this.entityRegistry.captureGroupingWriteGuard(entity.entityType);\n // Validate and serialize first to compute the new content hash\n const current = this.entitySerializer.withFrontmatterWrites(\n this.entitySerializer.withoutRetiredFields(entity),\n );\n const updatedEntity = {\n ...current,\n updated: new Date().toISOString(),\n contentHash: computeContentHash(current.content),\n };\n\n const validatedEntity = this.entityRegistry.validateEntity(\n entity.entityType,\n updatedEntity,\n );\n\n await validatePersist(this.entityRegistry, validatedEntity, \"update\");\n options?.signal?.throwIfAborted();\n\n const stored = this.entitySerializer.keepsStoredFrontmatter(validatedEntity)\n ? await this.storedContent(validatedEntity)\n : undefined;\n const { markdown, metadata } =\n this.entitySerializer.prepareEntityForStorage(\n validatedEntity,\n validatedEntity.entityType,\n stored,\n );\n\n const contentHash = computeContentHash(markdown);\n\n // Skip update only when all persisted fields are unchanged. Metadata-only\n // updates can leave serialized markdown/contentHash unchanged for adapters\n // that preserve frontmatter from content, but those DB metadata changes must\n // still persist for filtering/projections.\n const existing = await this.db\n .select({\n contentHash: entities.contentHash,\n visibility: entities.visibility,\n metadata: entities.metadata,\n })\n .from(entities)\n .where(\n and(\n eq(entities.id, validatedEntity.id),\n eq(entities.entityType, validatedEntity.entityType),\n ),\n )\n .limit(1);\n\n const existingEntity = existing.at(0);\n\n if (!existingEntity) {\n if (precondition)\n throw new EntityWriteConflictError(\n precondition.entityType,\n precondition.entityId,\n );\n throw new Error(\n `Entity not found: ${validatedEntity.entityType}:${validatedEntity.id}`,\n );\n }\n\n if (\n options?.expectedContentHash !== undefined &&\n existingEntity.contentHash !== options.expectedContentHash\n ) {\n this.logger.debug(\n `Skipping stale update for ${validatedEntity.entityType}:${validatedEntity.id}`,\n );\n return { stale: true, entityId: validatedEntity.id };\n }\n\n if (\n fold &&\n (validatedEntity.visibility !== fold.prior.visibility ||\n existingEntity.visibility !== fold.prior.visibility)\n ) {\n throw new EntityWriteConflictError(\n validatedEntity.entityType,\n validatedEntity.id,\n );\n }\n const stagedUpload = this.resolveStagedUpload(\n validatedEntity.entityType,\n validatedEntity.content,\n markdown,\n stagedAsset,\n );\n\n return {\n stale: false,\n plan: {\n entity: validatedEntity,\n options,\n precondition,\n fold,\n receipt,\n assertGroupingsCurrent,\n markdown,\n metadata,\n contentHash,\n stagedUpload,\n previousMetadata: existingEntity.metadata,\n unchanged:\n !precondition &&\n !receipt &&\n existingEntity.contentHash === contentHash &&\n existingEntity.visibility === validatedEntity.visibility &&\n stableJson(existingEntity.metadata) === stableJson(metadata),\n },\n };\n }\n\n /**\n * Every persisted field already matches the stored row: write nothing, but\n * take authority back from a projection, bind the asset, prune an excluded\n * FTS row, and journal the export.\n */\n private async refreshUnchangedEntity(\n plan: EntityUpdatePlan,\n ): Promise<EntityMutationResult> {\n const { entity, options } = plan;\n await this.projectionStore.transferEntityAuthority(\n {\n entityType: entity.entityType,\n id: entity.id,\n },\n async (transaction) => {\n options?.signal?.throwIfAborted();\n await plan.assertGroupingsCurrent();\n await this.bindAssetContent(\n transaction,\n entity.entityType,\n plan.markdown,\n plan.stagedUpload,\n );\n options?.signal?.throwIfAborted();\n await this.pruneFtsIndexIfExcluded(\n transaction,\n entity.id,\n entity.entityType,\n );\n return this.persistEntityExport(\n transaction,\n {\n entityType: entity.entityType,\n entityId: entity.id,\n operation: \"upsert\",\n },\n options?.persistenceOrigin,\n );\n },\n );\n this.logger.debug(\n `Skipping no-op update for ${entity.entityType}:${entity.id}`,\n );\n if (options?.eventContext) {\n await this.emitEntityEvent(\n entityUpdatedChannel,\n entity.entityType,\n entity.id,\n entity,\n plan.previousMetadata,\n options.eventContext,\n );\n }\n return { entityId: entity.id, jobId: \"\", skipped: true };\n }\n\n /**\n * Commit the update with its fold removal, FTS, both durable journals and\n * its receipt in one transaction. A row whose expected content hash changed\n * after preparation commits nothing and reports \"stale\".\n */\n private async commitUpdate(\n plan: EntityUpdatePlan,\n ): Promise<\"committed\" | \"stale\"> {\n const {\n entity,\n options,\n precondition,\n fold,\n receipt,\n markdown,\n metadata,\n contentHash,\n } = plan;\n try {\n await this.projectionStore.withDirtyInputs(\n [\n {\n sourceType: entity.entityType,\n sourceId: entity.id,\n revision: entityRevision({\n contentHash,\n metadata,\n visibility: entity.visibility,\n }),\n operation: \"upsert\",\n markedAt: this.projectionNow(),\n },\n ...(fold\n ? [\n {\n sourceType: fold.condition.entityType,\n sourceId: fold.condition.entityId,\n revision: `deleted:${fold.condition.expectedRevision}`,\n operation: \"delete\" as const,\n markedAt: this.projectionNow(),\n },\n ]\n : []),\n ],\n async (transaction) => {\n if (receipt)\n await this.mutationReceipts.assertVacant(transaction, receipt);\n if (fold)\n await assertEntityWriteCondition(\n transaction,\n fold.condition,\n fold.prior,\n );\n if (precondition)\n await assertEntityWriteCondition(transaction, precondition, entity);\n await this.guardEntityWrite(transaction, plan);\n // Cancellation after this boundary must not split the entity from its journals.\n const updateResult = await transaction\n .update(entities)\n .set({\n content: markdown,\n contentHash,\n visibility: entity.visibility,\n metadata,\n updated: new Date(entity.updated).getTime(),\n })\n .where(\n and(\n eq(entities.id, entity.id),\n eq(entities.entityType, entity.entityType),\n options?.expectedContentHash !== undefined\n ? eq(entities.contentHash, options.expectedContentHash)\n : undefined,\n ),\n );\n if (\n (precondition || options?.expectedContentHash !== undefined) &&\n Number(updateResult.rowsAffected) === 0\n ) {\n if (precondition)\n throw new EntityWriteConflictError(\n precondition.entityType,\n precondition.entityId,\n );\n throw new StaleEntityUpdateError();\n }\n if (fold) {\n await transaction\n .delete(entities)\n .where(\n and(\n eq(entities.entityType, fold.prior.entityType),\n eq(entities.id, fold.prior.id),\n ),\n );\n await this.recordEntityRemoval(\n transaction,\n { entityType: fold.prior.entityType, entityId: fold.prior.id },\n options?.persistenceOrigin,\n );\n }\n await this.recordEntityUpsert(\n transaction,\n {\n operation: \"update\",\n entityType: entity.entityType,\n entityId: entity.id,\n markdown,\n },\n receipt,\n options?.persistenceOrigin,\n );\n },\n );\n } catch (error) {\n if (!(error instanceof StaleEntityUpdateError)) throw error;\n this.logger.debug(\n `Skipping concurrently stale update for ${entity.entityType}:${entity.id}`,\n );\n return \"stale\";\n }\n return \"committed\";\n }\n\n private async afterUpdateCommit(\n plan: EntityUpdatePlan,\n ): Promise<EntityMutationResult> {\n const { entity, options, fold } = plan;\n // Recoverable cross-database/index and notification work starts only after\n // the entity pair, FTS and both durable journals have committed.\n if (fold)\n await this.embeddingIndex.deleteEmbedding(\n fold.prior.entityType,\n fold.prior.id,\n );\n await this.notifyProjectionScheduler();\n\n if (fold)\n await this.emitEntityEvent(\n entityDeletedChannel,\n fold.prior.entityType,\n fold.prior.id,\n fold.prior,\n undefined,\n options?.eventContext,\n );\n this.logger.debug(\n `Updated entity ${entity.entityType}:${entity.id} immediately`,\n );\n\n await this.emitEntityEvent(\n entityUpdatedChannel,\n entity.entityType,\n entity.id,\n entity,\n // Prior metadata lets projections (e.g. series) reconcile a moved value\n // such as a changed `seriesName` without a full resync. Already loaded\n // by prepareUpdate for the no-op check, so this adds no extra read.\n plan.previousMetadata,\n options?.eventContext,\n );\n\n return this.enqueueEmbedding(\n {\n entityId: entity.id,\n entityType: entity.entityType,\n contentHash: plan.contentHash,\n operation: \"update\",\n },\n options,\n );\n }\n\n /** Delete the entities contained in a container, one by one. */\n private async deleteContents(\n containerType: string,\n containerId: string,\n persistenceOrigin: EntityJobOptions[\"persistenceOrigin\"],\n ): Promise<void> {\n const prefix = `${containerId}:`;\n const containedTypes = [...this.entityRegistry.getContainment()]\n .filter(([, container]) => container === containerType)\n .map(([type]) => type);\n const contents = await Promise.all(\n containedTypes.map(async (type) =>\n (\n await this.db\n .select({ id: entities.id })\n .from(entities)\n .where(\n and(\n eq(entities.entityType, type),\n sql`substr(${entities.id}, 1, ${prefix.length}) = ${prefix}`,\n ),\n )\n ).map(({ id }) => ({ entityType: type, id })),\n ),\n );\n await contents.flat().reduce<Promise<void>>(async (previous, content) => {\n await previous;\n await this.deleteEntity({\n ...content,\n ...(persistenceOrigin !== undefined && {\n options: { persistenceOrigin },\n }),\n });\n }, Promise.resolve());\n }\n\n /**\n * Delete an entity by type and ID\n */\n public async deleteEntity(request: DeleteEntityRequest): Promise<boolean> {\n const { entityType, id, options } = request;\n\n // Fetch prior entity so subscribers can gate on its metadata (e.g. the\n // `seriesName` field that drives the series projection). Without this,\n // every delete forces subscribers into a full resync because they can't\n // tell whether the deleted entity was relevant to them.\n // Authorization belongs to the calling capability. This internal mutation\n // must find the admitted row at every visibility tier, not silently turn a\n // shared/restricted deletion into a public-scoped lookup miss.\n const priorData = await this.entityQueries.getEntityData(\n entityType,\n id,\n internalFullScope(\"delete prior-state lookup, internal mutation\"),\n );\n // A purged type is no longer registered: its rows have no adapter to parse.\n const prior =\n priorData && this.entityRegistry.hasEntityType(entityType)\n ? ((await this.entitySerializer.convertToEntity(priorData)) ??\n undefined)\n : undefined;\n\n if (priorData) {\n await this.mutationAdmission?.assertMutationAdmission({\n operation: \"delete\",\n entityType,\n entityId: id,\n });\n }\n\n if (!priorData) return false;\n // A conditional delete of a version that is no longer stored deletes\n // nothing, its contents included.\n const expectedContentHash = options?.expectedContentHash;\n if (\n expectedContentHash !== undefined &&\n priorData.contentHash !== expectedContentHash\n ) {\n return false;\n }\n // A container goes with its contents, which go first: a failure part way\n // leaves the container, never contents without one.\n await this.deleteContents(entityType, id, options?.persistenceOrigin);\n\n // Embeddings live in another database and are recoverable by backfill; the\n // entity row, FTS row, and scheduler journal share one atomic transaction.\n await this.embeddingIndex.deleteEmbedding(entityType, id);\n try {\n await this.projectionStore.withDirtyInput(\n {\n sourceType: entityType,\n sourceId: id,\n revision: `deleted:${entityRevision({\n contentHash: priorData.contentHash,\n metadata: priorData.metadata,\n visibility: priorData.visibility,\n })}`,\n operation: \"delete\",\n markedAt: this.projectionNow(),\n },\n async (transaction) => {\n const deleteResult = await transaction\n .delete(entities)\n .where(\n and(\n eq(entities.entityType, entityType),\n eq(entities.id, id),\n expectedContentHash !== undefined\n ? eq(entities.contentHash, expectedContentHash)\n : undefined,\n ),\n );\n if (\n expectedContentHash !== undefined &&\n Number(deleteResult.rowsAffected) === 0\n ) {\n throw new StaleEntityUpdateError();\n }\n await this.recordEntityRemoval(\n transaction,\n { entityType, entityId: id },\n options?.persistenceOrigin,\n );\n },\n );\n } catch (error) {\n if (!(error instanceof StaleEntityUpdateError)) throw error;\n // Changed between the check and the write: nothing was deleted. Its\n // embedding comes back through backfill.\n this.logger.debug(\n `Skipping concurrently stale delete for ${entityType}:${id}`,\n );\n return false;\n }\n await this.notifyProjectionScheduler();\n\n await this.emitEntityEvent(\n entityDeletedChannel,\n entityType,\n id,\n prior,\n undefined,\n options?.eventContext,\n );\n\n return true;\n }\n\n /**\n * Create or update an entity based on existence\n */\n public async upsertEntity<T extends BaseEntity>(\n request: UpsertEntityRequest<T>,\n ): Promise<EntityMutationResult & { created: boolean }> {\n const { entity, options, stagedAsset } = request;\n this.logger.debug(\n `Upserting entity of type ${entity.entityType} with ID ${entity.id}`,\n );\n\n if (options?.conditionalWrite) {\n const created = options.conditionalWrite.expectedRevision === null;\n const result = created\n ? await this.createEntity({ entity, options, stagedAsset })\n : await this.updateEntity({ entity, options, stagedAsset });\n return { ...result, created };\n }\n\n const exists = await this.entityQueries.entityExists(\n entity.entityType,\n entity.id,\n );\n\n if (exists) {\n const result = await this.updateEntity({\n entity,\n ...(stagedAsset !== undefined && { stagedAsset }),\n ...(options !== undefined && { options }),\n });\n return { ...result, created: false };\n }\n\n try {\n const result = await this.createEntity({\n entity,\n ...(stagedAsset !== undefined && { stagedAsset }),\n ...(options !== undefined && { options }),\n });\n return { ...result, created: true };\n } catch (error) {\n // A concurrent create can win between the existence check and the\n // insert — fall through to the update path instead of surfacing the\n // raw unique-constraint violation.\n if (!isUniqueConstraintError(error)) {\n throw error;\n }\n this.logger.debug(\n `Entity ${entity.entityType}:${entity.id} was created concurrently, updating instead`,\n );\n const result = await this.updateEntity({\n entity,\n ...(stagedAsset !== undefined && { stagedAsset }),\n ...(options !== undefined && { options }),\n });\n return { ...result, created: false };\n }\n }\n\n /** Reconcile indexes and lifecycle subscribers after atomic projection writes. */\n public async reconcileProjectionTargets(\n targets: readonly ProjectionChangedTarget[],\n ): Promise<void> {\n await Promise.all(\n targets.map(async (target) => {\n if (target.operation === \"delete\") {\n await this.emitEntityEvent(\n entityDeletedChannel,\n target.entityType,\n target.entityId,\n );\n await this.embeddingIndex.deleteEmbedding(\n target.entityType,\n target.entityId,\n );\n return;\n }\n if (!target.contentHash) {\n throw new Error(\n `Projection target ${target.entityType}:${target.entityId} has no content hash`,\n );\n }\n await this.emitEntityEvent(\n entityUpdatedChannel,\n target.entityType,\n target.entityId,\n );\n await this.embeddingIndex.enqueue({\n entityId: target.entityId,\n entityType: target.entityType,\n contentHash: target.contentHash,\n operation: \"update\",\n });\n }),\n );\n }\n\n /**\n * Store embedding for an entity\n * Used by embedding job handler to store embedding in the embeddings table\n * Entity must already exist in entities table\n */\n public async storeEmbedding(data: StoreEmbeddingData): Promise<void> {\n await this.embeddingIndex.store(data);\n }\n\n public async backfillMissingEmbeddings(): Promise<EmbeddingBackfillResult> {\n return this.embeddingIndex.backfillMissing();\n }\n\n public async getEmbeddingIndexStats(): Promise<EmbeddingIndexStats> {\n return this.embeddingIndex.getIndexStats();\n }\n\n private resolveStagedUpload(\n entityType: string,\n entityContent: string,\n storedContent: string,\n stagedAsset: CreateEntityRequest<BaseEntity>[\"stagedAsset\"],\n ): StagedUpload | undefined {\n const assetBacked =\n this.entityRegistry.getEntityTypeConfig(entityType).binaryStorage ===\n \"asset\";\n if (!stagedAsset) return undefined;\n if (!assetBacked) {\n throw new Error(\n `Entity type ${entityType} is not registered for asset-backed storage`,\n );\n }\n if (\n entityContent !== stagedAsset.ref ||\n storedContent !== stagedAsset.ref\n ) {\n throw new Error(\n `Staged asset ${stagedAsset.ref} does not match canonical ${entityType} content`,\n );\n }\n return this.assetRepository.claimedUpload(stagedAsset);\n }\n\n private async bindAssetContent(\n transaction: AssetTransaction,\n entityType: string,\n storedContent: string,\n stagedUpload?: StagedUpload,\n ): Promise<void> {\n if (\n this.entityRegistry.getEntityTypeConfig(entityType).binaryStorage !==\n \"asset\"\n ) {\n return;\n }\n await this.assetRepository.bindEntityContent(\n transaction,\n storedContent,\n stagedUpload,\n );\n }\n\n /**\n * The last refusals before an entity row is written, inside its transaction:\n * asset binding, the caller's guard over the final persisted fields,\n * cancellation, and grouping currency.\n */\n private async guardEntityWrite(\n transaction: EntityTransaction,\n write: EntityWriteGuard,\n ): Promise<void> {\n const { entity, markdown, contentHash, metadata, options } = write;\n await this.bindAssetContent(\n transaction,\n entity.entityType,\n markdown,\n write.stagedUpload,\n );\n await options?.beforeWrite?.({\n ...entity,\n content: markdown,\n contentHash,\n metadata,\n });\n options?.signal?.throwIfAborted();\n await write.assertGroupingsCurrent();\n options?.signal?.throwIfAborted();\n }\n\n /** Index, journal and receipt an entity row written in this transaction. */\n private async recordEntityUpsert(\n transaction: EntityTransaction,\n write: {\n operation: \"create\" | \"update\";\n entityType: string;\n entityId: string;\n markdown: string;\n },\n receipt: EntityMutationReceiptKey | undefined,\n origin: EntityJobOptions[\"persistenceOrigin\"],\n ): Promise<void> {\n const { operation, entityType, entityId } = write;\n await this.syncFtsIndex(transaction, entityId, entityType, write.markdown);\n await this.persistEntityExport(\n transaction,\n { entityType, entityId, operation: \"upsert\" },\n origin,\n );\n if (receipt)\n await this.mutationReceipts.record(transaction, receipt, {\n operation,\n entityType,\n entityId,\n });\n }\n\n /** Unindex and journal an entity row deleted in this transaction. */\n private async recordEntityRemoval(\n transaction: EntityTransaction,\n target: { entityType: string; entityId: string },\n origin: EntityJobOptions[\"persistenceOrigin\"],\n ): Promise<void> {\n await this.deleteFtsIndex(transaction, target.entityId, target.entityType);\n await this.persistEntityExport(\n transaction,\n { ...target, operation: \"delete\" },\n origin,\n );\n }\n\n private enqueueEmbedding(\n target: Pick<\n EnqueueEmbeddingInput,\n \"entityId\" | \"entityType\" | \"contentHash\" | \"operation\"\n >,\n options: EntityJobOptions | undefined,\n ): Promise<EntityMutationResult> {\n return this.embeddingIndex.enqueue({\n ...target,\n ...(options?.priority !== undefined && { priority: options.priority }),\n ...(options?.maxRetries !== undefined && {\n maxRetries: options.maxRetries,\n }),\n ...(options?.eventContext && { eventContext: options.eventContext }),\n });\n }\n\n /** Synchronize FTS independently from vector embedding policy. */\n private async syncFtsIndex(\n database: Pick<EntityDB, \"run\">,\n entityId: string,\n entityType: string,\n content: string,\n ): Promise<void> {\n await this.deleteFtsIndex(database, entityId, entityType);\n if (!this.isFullTextSearchable(entityType)) return;\n await insertEntityFts(database, entityType, entityId, content);\n }\n\n private async pruneFtsIndexIfExcluded(\n database: Pick<EntityDB, \"run\">,\n entityId: string,\n entityType: string,\n ): Promise<void> {\n if (this.isFullTextSearchable(entityType)) return;\n await this.deleteFtsIndex(database, entityId, entityType);\n }\n\n private async deleteFtsIndex(\n database: Pick<EntityDB, \"run\">,\n entityId: string,\n entityType: string,\n ): Promise<void> {\n await deleteEntityFts(database, entityType, entityId);\n }\n\n private isFullTextSearchable(entityType: string): boolean {\n return (\n this.entityRegistry.getEntityTypeConfig(entityType).fullTextSearchable !==\n false\n );\n }\n\n /**\n * Find a unique ID by appending -2, -3, etc. if the base ID already exists.\n */\n private async resolveUniqueId(\n baseId: string,\n entityType: string,\n ): Promise<string> {\n const exists = await this.entityQueries.entityExists(entityType, baseId);\n\n if (!exists) {\n return baseId;\n }\n\n // Try suffixes -2, -3, ... up to a reasonable limit\n for (let suffix = 2; suffix <= 100; suffix++) {\n const candidateId = `${baseId}-${suffix}`;\n const taken = await this.entityQueries.entityExists(\n entityType,\n candidateId,\n );\n\n if (!taken) {\n this.logger.debug(`Deduplicated entity ID: ${baseId} → ${candidateId}`);\n return candidateId;\n }\n }\n\n // Extremely unlikely fallback: append random suffix\n const fallbackId = `${baseId}-${createId().slice(0, 8)}`;\n this.logger.warn(\n `Could not deduplicate entity ID after 100 attempts, using random suffix: ${fallbackId}`,\n );\n return fallbackId;\n }\n\n public async wakeProjectionScheduler(): Promise<void> {\n await this.notifyProjectionScheduler();\n }\n\n private async notifyProjectionScheduler(): Promise<void> {\n try {\n await this.projectionWakeup?.();\n } catch (error) {\n // The durable journal remains pending for the next wakeup or restart.\n this.logger.error(\"Failed to wake projection scheduler\", error);\n }\n }\n\n /**\n * Broadcast an entity lifecycle event via the message bus\n */\n private async emitEntityEvent(\n channel: Channel<EntityChangePayload>,\n entityType: string,\n entityId: string,\n entity?: BaseEntity,\n previousMetadata?: BaseEntity[\"metadata\"],\n eventContext?: EntityMutationEventContext,\n ): Promise<void> {\n if (!this.messageBus) {\n return;\n }\n\n this.logger.debug(`Emitting ${channel.name} for ${entityType}:${entityId}`);\n\n const payload: EntityChangePayload = {\n entityType,\n entityId,\n ...(eventContext?.conversationId\n ? { conversationId: eventContext.conversationId }\n : {}),\n ...(eventContext?.channelId ? { channelId: eventContext.channelId } : {}),\n ...(eventContext?.runId ? { runId: eventContext.runId } : {}),\n ...(eventContext?.toolCallId\n ? { toolCallId: eventContext.toolCallId }\n : {}),\n ...(eventContext?.actor ? { actor: eventContext.actor } : {}),\n ...(eventContext?.interfaceType\n ? { interfaceType: eventContext.interfaceType }\n : {}),\n ...(entity ? { entity: { ...entity } } : {}),\n ...(previousMetadata ? { previousMetadata } : {}),\n };\n\n try {\n await broadcastChannel(\n this.messageBus,\n channel,\n payload,\n \"entity-service\",\n );\n } catch (error) {\n // Lifecycle delivery is a wake-up optimization. The durable export and\n // projection journals remain available for startup/periodic recovery.\n this.logger.error(\n `Failed to publish ${channel.name} for ${entityType}:${entityId}`,\n error,\n );\n }\n }\n\n private async persistEntityExport(\n transaction: EntityExportTransaction,\n target: {\n entityType: string;\n entityId: string;\n operation: \"upsert\" | \"delete\";\n },\n origin: EntityJobOptions[\"persistenceOrigin\"],\n ): Promise<void> {\n if (origin === \"directory-sync\") {\n await this.entityExportStore.clear(transaction, target);\n return;\n }\n await this.entityExportStore.record(transaction, {\n ...target,\n markedAt: this.projectionNow(),\n });\n }\n}\n",
281
281
  "import {\n and,\n desc,\n eq,\n inArray,\n isNotNull,\n isNull,\n lte,\n or,\n sql,\n} from \"drizzle-orm\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { createId } from \"@brains/utils/id\";\nimport { z } from \"@brains/utils/zod\";\nimport type { EntityDB } from \"./db\";\nimport {\n parseBulkMutationInput,\n parseDurableBulkMutationChildInput,\n parseDurableBulkMutationRootInput,\n parseSettleDurableBulkMutationChildInput,\n type BulkMutationInput,\n type DurableBulkMutationChildInput,\n type DurableBulkMutationRootInput,\n type ProjectionBatchOwnedJob,\n type ProjectionBatchRecoveryResult,\n type ProjectionBatchRootReader,\n type SettleDurableBulkMutationChildInput,\n} from \"./projection-batch-contracts\";\nimport {\n projectionAdmissionState,\n projectionBatchChildren,\n projectionBatches,\n type ProjectionBatch,\n} from \"./schema/projection-batches\";\nimport type {\n EntityTransaction,\n ProjectionTransactionRunner,\n} from \"./projection-transaction-runner\";\n\nconst DURABLE_ROOT_RECOVERY_GRACE_MS = 5_000;\nconst DURABLE_ROOT_PARTIAL_TIMEOUT_MS = 30_000;\nconst PROJECTION_BATCH_LEASE_MS = 30_000;\nconst CALLBACK_BATCH_HEARTBEAT_MS = 10_000;\n\nexport class ProjectionBatchFencedError extends Error {}\n\ninterface ProjectionBatchScope {\n batchId: string;\n source: string;\n operationId: string;\n ownerToken: string;\n}\n\ninterface TerminalProjectionBatchTransition {\n abandoned: boolean;\n terminalAt: number;\n fenceOwner: boolean;\n clearLease: boolean;\n}\n\nexport interface ProjectionBatchDiagnostics {\n preparing: number;\n open: number;\n abandoned: number;\n expiredCallbackLeases: number;\n oldestActiveAgeMs: number | null;\n oldestProgressAgeMs: number | null;\n}\n\ninterface ProjectionBatchCoordinatorOptions {\n db: EntityDB;\n transactions: ProjectionTransactionRunner;\n now: () => number;\n getRecoveryGeneration: (\n transaction: EntityTransaction,\n fallback: number,\n ) => Promise<number>;\n}\n\n/** Owns durable and callback projection-batch admission and recovery. */\nexport class ProjectionBatchCoordinator {\n private readonly db: EntityDB;\n private readonly transactions: ProjectionTransactionRunner;\n private readonly now: () => number;\n private readonly readRecoveryGeneration: ProjectionBatchCoordinatorOptions[\"getRecoveryGeneration\"];\n private readonly batchScope = new AsyncLocalStorage<\n ProjectionBatchScope | undefined\n >();\n\n public constructor(options: ProjectionBatchCoordinatorOptions) {\n this.db = options.db;\n this.transactions = options.transactions;\n this.now = options.now;\n this.readRecoveryGeneration = options.getRecoveryGeneration;\n }\n\n /**\n * Force this coordinator's ambient batch scope to empty for the duration\n * of `fn`, regardless of what the calling continuation inherited.\n *\n * `runBulkMutation`/`runDurableBulkMutationChild` trust\n * `AsyncLocalStorage.getStore()` as a fast path to detect genuine nesting\n * within one caller's own call stack. That trust breaks across a job\n * scheduler that multiplexes independent units of work onto shared native\n * continuations (this app's job queue dispatches jobs as Effect fibers,\n * which have no relationship to Node's AsyncLocalStorage tracking): an\n * unrelated job's leftover scope can appear ambient to a new one and trip\n * the identity fence on jobs that were never actually nested. Callers that\n * define a fresh unit of work (the job queue, once per job) must call this\n * before running it, so a job never inherits another job's batch scope.\n */\n public runFreshBatchScope<T>(fn: () => T): T {\n return this.batchScope.run(undefined, fn);\n }\n\n private assertBatchIdentity(\n scope: ProjectionBatchScope,\n input: BulkMutationInput,\n ): void {\n if (\n scope.source !== input.source ||\n scope.operationId !== input.operationId\n ) {\n throw new ProjectionBatchFencedError(\n `Projection batch \"${input.operationId}\" cannot join active batch \"${scope.operationId}\"`,\n );\n }\n }\n\n public async runBulkMutation<TResult>(\n input: BulkMutationInput,\n mutation: () => Promise<TResult>,\n ): Promise<TResult> {\n const parsed = parseBulkMutationInput(input);\n const existingScope = this.batchScope.getStore();\n if (existingScope) {\n this.assertBatchIdentity(existingScope, parsed);\n return mutation();\n }\n\n const scope = await this.openCallbackBatch(parsed);\n const heartbeat = setInterval(() => {\n void this.renewCallbackBatch(scope).catch(() => {\n // Mutation transactions enforce the fence if renewal loses ownership.\n });\n }, CALLBACK_BATCH_HEARTBEAT_MS);\n heartbeat.unref();\n try {\n return await this.batchScope.run(scope, mutation);\n } finally {\n clearInterval(heartbeat);\n await this.closeCallbackBatch(scope);\n }\n }\n\n public async prepareDurableBulkMutation(\n input: DurableBulkMutationRootInput,\n ): Promise<void> {\n const parsed = parseDurableBulkMutationRootInput(input);\n const now = this.now();\n await this.runTransaction(async (transaction) => {\n const existing = await transaction\n .select()\n .from(projectionBatches)\n .where(\n and(\n eq(projectionBatches.source, parsed.source),\n eq(projectionBatches.operationId, parsed.operationId),\n ),\n )\n .limit(1);\n const batch = existing[0];\n if (batch) {\n if (\n (batch.status === \"preparing\" || batch.status === \"open\") &&\n batch.rootJobId === parsed.rootJobId &&\n batch.expectedChildren === parsed.expectedChildren\n ) {\n return;\n }\n throw new ProjectionBatchFencedError(\n `Durable projection batch \"${parsed.operationId}\" cannot be prepared`,\n );\n }\n await transaction\n .insert(projectionAdmissionState)\n .values({ id: 1, epoch: 0 })\n .onConflictDoNothing({ target: projectionAdmissionState.id });\n await transaction\n .update(projectionAdmissionState)\n .set({ epoch: sql`${projectionAdmissionState.epoch} + 1` })\n .where(eq(projectionAdmissionState.id, 1));\n await transaction.insert(projectionBatches).values({\n id: createId(),\n source: parsed.source,\n operationId: parsed.operationId,\n status: \"preparing\",\n ownerKind: \"job-root\",\n ownerToken: createId(),\n rootJobId: parsed.rootJobId,\n expectedChildren: parsed.expectedChildren,\n enqueueComplete: 0,\n enqueueFailed: 0,\n openedAt: now,\n lastProgressAt: now,\n leaseExpiresAt: now + PROJECTION_BATCH_LEASE_MS,\n });\n });\n }\n\n public async finalizeDurableBulkMutationEnqueue(\n operationId: string,\n ): Promise<void> {\n const parsedOperationId = z\n .string()\n .trim()\n .min(1)\n .max(200)\n .parse(operationId);\n const now = this.now();\n await this.runBatchStateWrite(() =>\n this.db\n .update(projectionBatches)\n .set({\n status: \"open\",\n enqueueComplete: 1,\n lastProgressAt: now,\n leaseExpiresAt: null,\n })\n .where(\n and(\n eq(projectionBatches.operationId, parsedOperationId),\n inArray(projectionBatches.status, [\"preparing\", \"open\"]),\n ),\n ),\n );\n }\n\n public async failDurableBulkMutationEnqueue(\n operationId: string,\n ): Promise<void> {\n const parsedOperationId = z\n .string()\n .trim()\n .min(1)\n .max(200)\n .parse(operationId);\n const now = this.now();\n await this.runBatchStateWrite(() =>\n this.db\n .update(projectionBatches)\n .set({\n enqueueComplete: 1,\n enqueueFailed: 1,\n lastProgressAt: now,\n leaseExpiresAt: null,\n })\n .where(\n and(\n eq(projectionBatches.operationId, parsedOperationId),\n inArray(projectionBatches.status, [\"preparing\", \"open\"]),\n ),\n ),\n );\n }\n\n public async runDurableBulkMutationChild<TResult>(\n input: DurableBulkMutationChildInput,\n mutation: () => Promise<TResult>,\n ): Promise<TResult> {\n const parsed = parseDurableBulkMutationChildInput(input);\n const existingScope = this.batchScope.getStore();\n if (existingScope) {\n this.assertBatchIdentity(existingScope, parsed);\n return mutation();\n }\n const scope = await this.openDurableBatchChild(parsed);\n return this.batchScope.run(scope, mutation);\n }\n\n public async settleDurableBulkMutationChild(\n input: SettleDurableBulkMutationChildInput,\n ): Promise<boolean> {\n const parsed = parseSettleDurableBulkMutationChildInput(input);\n const now = this.now();\n return this.runTransaction(async (transaction) => {\n const batches = await transaction\n .select()\n .from(projectionBatches)\n .where(\n and(\n eq(projectionBatches.operationId, parsed.operationId),\n eq(projectionBatches.ownerKind, \"job-root\"),\n ),\n )\n .limit(1);\n const batch = batches[0];\n if (!batch || batch.status === \"closed\" || batch.status === \"abandoned\") {\n return false;\n }\n const updated = await transaction\n .update(projectionBatchChildren)\n .set({ status: parsed.outcome, terminalAt: now })\n .where(\n and(\n eq(projectionBatchChildren.batchId, batch.id),\n eq(projectionBatchChildren.childKey, parsed.childKey),\n eq(projectionBatchChildren.jobId, parsed.jobId),\n ),\n )\n .returning({ childKey: projectionBatchChildren.childKey });\n if (updated.length === 0) return false;\n\n const terminalRows = await transaction\n .select({ total: sql<number>`count(*)` })\n .from(projectionBatchChildren)\n .where(\n and(\n eq(projectionBatchChildren.batchId, batch.id),\n inArray(projectionBatchChildren.status, [\"completed\", \"failed\"]),\n ),\n );\n if (Number(terminalRows[0]?.total ?? 0) < batch.expectedChildren) {\n return false;\n }\n const failedRows = await transaction\n .select({ total: sql<number>`count(*)` })\n .from(projectionBatchChildren)\n .where(\n and(\n eq(projectionBatchChildren.batchId, batch.id),\n eq(projectionBatchChildren.status, \"failed\"),\n ),\n );\n const abandoned = Number(failedRows[0]?.total ?? 0) > 0;\n await this.transitionProjectionBatchToTerminal(transaction, batch, {\n abandoned,\n terminalAt: now,\n fenceOwner: false,\n clearLease: true,\n });\n return true;\n });\n }\n\n public async recoverProjectionBatches(\n readRoot: ProjectionBatchRootReader,\n ): Promise<ProjectionBatchRecoveryResult> {\n const now = this.now();\n const expiredCallbackCandidates = await this.db\n .select({ id: projectionBatches.id })\n .from(projectionBatches)\n .where(\n and(\n eq(projectionBatches.ownerKind, \"callback\"),\n eq(projectionBatches.status, \"open\"),\n lte(projectionBatches.leaseExpiresAt, now),\n ),\n );\n const fencedCallbacks =\n expiredCallbackCandidates.length === 0\n ? 0\n : await this.runTransaction(async (transaction) => {\n const expired = await transaction\n .select()\n .from(projectionBatches)\n .where(\n and(\n eq(projectionBatches.ownerKind, \"callback\"),\n eq(projectionBatches.status, \"open\"),\n lte(projectionBatches.leaseExpiresAt, now),\n ),\n );\n for (const batch of expired) {\n const recoveryGeneration = await this.getRecoveryGeneration(\n transaction,\n batch.highestGeneration ?? 0,\n );\n await transaction\n .update(projectionBatches)\n .set({\n status: \"abandoned\",\n ownerToken: createId(),\n terminalAt: now,\n lastProgressAt: now,\n leaseExpiresAt: null,\n recoveryGeneration,\n recoveredAt: batch.highestGeneration === null ? now : null,\n })\n .where(\n and(\n eq(projectionBatches.id, batch.id),\n eq(projectionBatches.ownerToken, batch.ownerToken),\n eq(projectionBatches.status, \"open\"),\n ),\n );\n }\n return expired.length;\n });\n\n const durableBatches = await this.db\n .select()\n .from(projectionBatches)\n .where(\n and(\n eq(projectionBatches.ownerKind, \"job-root\"),\n inArray(projectionBatches.status, [\"preparing\", \"open\"]),\n ),\n );\n let releasedDurableRoots = 0;\n for (const batch of durableBatches) {\n if (!batch.rootJobId) continue;\n const jobs = await readRoot(batch.rootJobId, batch.operationId);\n const hasActiveJob = jobs.some(\n (job) => job.status === \"pending\" || job.status === \"processing\",\n );\n const terminalRecoveryReady = jobs.every(\n (job) =>\n job.terminalAt !== null &&\n job.terminalAt <= now - DURABLE_ROOT_RECOVERY_GRACE_MS,\n );\n const completeRoot = jobs.length >= batch.expectedChildren;\n const provablyPartial =\n now - batch.openedAt >= DURABLE_ROOT_PARTIAL_TIMEOUT_MS;\n if (\n hasActiveJob ||\n !terminalRecoveryReady ||\n (!completeRoot && !provablyPartial)\n ) {\n continue;\n }\n const released = await this.reconcileDurableRoot(batch.id, jobs, now);\n if (released) releasedDurableRoots++;\n }\n await this.cleanupProjectionBatches();\n return { fencedCallbacks, releasedDurableRoots };\n }\n\n public async cleanupProjectionBatches(\n retentionMs: number = 7 * 24 * 60 * 60 * 1_000,\n maximumRecords: number = 100,\n ): Promise<number> {\n const parsedRetention = z.number().int().nonnegative().parse(retentionMs);\n const parsedMaximum = z\n .number()\n .int()\n .nonnegative()\n .max(10_000)\n .parse(maximumRecords);\n const terminalPredicate = or(\n eq(projectionBatches.status, \"closed\"),\n and(\n eq(projectionBatches.status, \"abandoned\"),\n isNotNull(projectionBatches.recoveredAt),\n ),\n );\n const expired = await this.db\n .select({ id: projectionBatches.id })\n .from(projectionBatches)\n .where(\n and(\n terminalPredicate,\n lte(projectionBatches.terminalAt, this.now() - parsedRetention),\n ),\n );\n const overflow = await this.db\n .select({ id: projectionBatches.id })\n .from(projectionBatches)\n .where(terminalPredicate)\n .orderBy(desc(projectionBatches.terminalAt))\n .limit(10_000)\n .offset(parsedMaximum);\n const ids = [...new Set([...expired, ...overflow].map(({ id }) => id))];\n if (ids.length === 0) return 0;\n const deleted = await this.db\n .delete(projectionBatches)\n .where(inArray(projectionBatches.id, ids))\n .returning({ id: projectionBatches.id });\n return deleted.length;\n }\n\n private async reconcileDurableRoot(\n batchId: string,\n jobs: readonly ProjectionBatchOwnedJob[],\n now: number,\n ): Promise<boolean> {\n return this.runTransaction(async (transaction) => {\n const batches = await transaction\n .select()\n .from(projectionBatches)\n .where(eq(projectionBatches.id, batchId))\n .limit(1);\n const batch = batches[0];\n if (!batch || (batch.status !== \"open\" && batch.status !== \"preparing\")) {\n return false;\n }\n for (const job of jobs) {\n const childStatus =\n job.status === \"completed\"\n ? \"completed\"\n : job.status === \"failed\"\n ? \"failed\"\n : \"active\";\n await transaction\n .insert(projectionBatchChildren)\n .values({\n batchId,\n childKey: job.childKey,\n jobId: job.jobId,\n status: childStatus,\n ...(childStatus === \"completed\" || childStatus === \"failed\"\n ? { terminalAt: now }\n : {}),\n })\n .onConflictDoUpdate({\n target: [\n projectionBatchChildren.batchId,\n projectionBatchChildren.childKey,\n ],\n set: {\n jobId: job.jobId,\n status: childStatus,\n terminalAt:\n childStatus === \"completed\" || childStatus === \"failed\"\n ? now\n : null,\n },\n });\n }\n\n const active = jobs.some(\n (job) => job.status === \"pending\" || job.status === \"processing\",\n );\n const completeRoot = jobs.length >= batch.expectedChildren && !active;\n const provablyPartial =\n !active &&\n jobs.length < batch.expectedChildren &&\n now - batch.openedAt >= DURABLE_ROOT_PARTIAL_TIMEOUT_MS;\n if (!completeRoot && !provablyPartial) return false;\n\n const abandoned =\n provablyPartial || jobs.some((job) => job.status === \"failed\");\n await this.transitionProjectionBatchToTerminal(transaction, batch, {\n abandoned,\n terminalAt: now,\n fenceOwner: true,\n clearLease: false,\n });\n return true;\n });\n }\n\n private async transitionProjectionBatchToTerminal(\n transaction: EntityTransaction,\n batch: ProjectionBatch,\n transition: TerminalProjectionBatchTransition,\n ): Promise<void> {\n const recoveryGeneration = transition.abandoned\n ? await this.getRecoveryGeneration(\n transaction,\n batch.highestGeneration ?? 0,\n )\n : null;\n await transaction\n .update(projectionBatches)\n .set({\n status: transition.abandoned ? \"abandoned\" : \"closed\",\n ownerToken:\n transition.abandoned && transition.fenceOwner\n ? createId()\n : batch.ownerToken,\n terminalAt: transition.terminalAt,\n lastProgressAt: transition.terminalAt,\n leaseExpiresAt: transition.clearLease ? null : batch.leaseExpiresAt,\n recoveryGeneration,\n recoveredAt:\n transition.abandoned && batch.highestGeneration === null\n ? transition.terminalAt\n : null,\n })\n .where(eq(projectionBatches.id, batch.id));\n }\n\n public async getProjectionBatchDiagnostics(): Promise<ProjectionBatchDiagnostics> {\n const now = this.now();\n const rows = await this.db\n .select({\n status: projectionBatches.status,\n ownerKind: projectionBatches.ownerKind,\n openedAt: projectionBatches.openedAt,\n lastProgressAt: projectionBatches.lastProgressAt,\n leaseExpiresAt: projectionBatches.leaseExpiresAt,\n recoveredAt: projectionBatches.recoveredAt,\n })\n .from(projectionBatches)\n .where(\n inArray(projectionBatches.status, [\"preparing\", \"open\", \"abandoned\"]),\n );\n const active = rows.filter(\n (row) => row.status === \"preparing\" || row.status === \"open\",\n );\n return {\n preparing: rows.filter((row) => row.status === \"preparing\").length,\n open: rows.filter((row) => row.status === \"open\").length,\n abandoned: rows.filter(\n (row) => row.status === \"abandoned\" && row.recoveredAt === null,\n ).length,\n expiredCallbackLeases: active.filter(\n (row) =>\n row.ownerKind === \"callback\" &&\n row.leaseExpiresAt !== null &&\n row.leaseExpiresAt <= now,\n ).length,\n oldestActiveAgeMs:\n active.length === 0\n ? null\n : Math.max(0, now - Math.min(...active.map((row) => row.openedAt))),\n oldestProgressAgeMs:\n active.length === 0\n ? null\n : Math.max(\n 0,\n now - Math.min(...active.map((row) => row.lastProgressAt)),\n ),\n };\n }\n\n private async openDurableBatchChild(\n input: DurableBulkMutationChildInput,\n ): Promise<ProjectionBatchScope> {\n const now = this.now();\n return this.runTransaction(async (transaction) => {\n let batch = (\n await transaction\n .select()\n .from(projectionBatches)\n .where(\n and(\n eq(projectionBatches.source, input.source),\n eq(projectionBatches.operationId, input.operationId),\n ),\n )\n .limit(1)\n )[0];\n if (!batch) {\n await transaction\n .insert(projectionAdmissionState)\n .values({ id: 1, epoch: 0 })\n .onConflictDoNothing({ target: projectionAdmissionState.id });\n await transaction\n .update(projectionAdmissionState)\n .set({ epoch: sql`${projectionAdmissionState.epoch} + 1` })\n .where(eq(projectionAdmissionState.id, 1));\n const inserted = await transaction\n .insert(projectionBatches)\n .values({\n id: createId(),\n source: input.source,\n operationId: input.operationId,\n status: \"open\",\n ownerKind: \"job-root\",\n ownerToken: createId(),\n rootJobId: input.rootJobId,\n expectedChildren: input.expectedChildren,\n enqueueComplete: 1,\n enqueueFailed: 0,\n openedAt: now,\n lastProgressAt: now,\n })\n .returning();\n batch = inserted[0];\n }\n if (\n (batch?.status !== \"preparing\" && batch?.status !== \"open\") ||\n batch.ownerKind !== \"job-root\" ||\n batch.rootJobId !== input.rootJobId ||\n batch.expectedChildren !== input.expectedChildren\n ) {\n throw new ProjectionBatchFencedError(\n `Durable projection batch \"${input.operationId}\" is not open for this owner`,\n );\n }\n\n const existingChildren = await transaction\n .select()\n .from(projectionBatchChildren)\n .where(\n and(\n eq(projectionBatchChildren.batchId, batch.id),\n eq(projectionBatchChildren.childKey, input.childKey),\n ),\n )\n .limit(1);\n const existingChild = existingChildren[0];\n if (\n existingChild &&\n (existingChild.status === \"completed\" ||\n existingChild.status === \"failed\" ||\n existingChild.status === \"missing\")\n ) {\n throw new ProjectionBatchFencedError(\n `Durable projection batch child \"${input.childKey}\" is terminal`,\n );\n }\n await transaction\n .insert(projectionBatchChildren)\n .values({\n batchId: batch.id,\n childKey: input.childKey,\n jobId: input.jobId,\n status: \"active\",\n })\n .onConflictDoUpdate({\n target: [\n projectionBatchChildren.batchId,\n projectionBatchChildren.childKey,\n ],\n set: { jobId: input.jobId, status: \"active\", terminalAt: null },\n });\n await transaction\n .update(projectionBatches)\n .set({ status: \"open\", lastProgressAt: now, leaseExpiresAt: null })\n .where(eq(projectionBatches.id, batch.id));\n return {\n batchId: batch.id,\n source: batch.source,\n operationId: batch.operationId,\n ownerToken: batch.ownerToken,\n };\n });\n }\n\n private async openCallbackBatch(\n input: BulkMutationInput,\n ): Promise<ProjectionBatchScope> {\n const scope: ProjectionBatchScope = {\n batchId: createId(),\n source: input.source,\n operationId: input.operationId,\n ownerToken: createId(),\n };\n const now = this.now();\n await this.runTransaction(async (transaction) => {\n await transaction\n .insert(projectionAdmissionState)\n .values({ id: 1, epoch: 0 })\n .onConflictDoNothing({ target: projectionAdmissionState.id });\n await transaction\n .update(projectionAdmissionState)\n .set({ epoch: sql`${projectionAdmissionState.epoch} + 1` })\n .where(eq(projectionAdmissionState.id, 1));\n await transaction.insert(projectionBatches).values({\n id: scope.batchId,\n source: scope.source,\n operationId: scope.operationId,\n status: \"open\",\n ownerKind: \"callback\",\n ownerToken: scope.ownerToken,\n expectedChildren: 0,\n enqueueComplete: 1,\n enqueueFailed: 0,\n openedAt: now,\n lastProgressAt: now,\n leaseExpiresAt: now + PROJECTION_BATCH_LEASE_MS,\n });\n });\n return scope;\n }\n\n private async renewCallbackBatch(scope: ProjectionBatchScope): Promise<void> {\n const now = this.now();\n const rows = await this.db\n .update(projectionBatches)\n .set({\n lastProgressAt: now,\n leaseExpiresAt: now + PROJECTION_BATCH_LEASE_MS,\n })\n .where(\n and(\n eq(projectionBatches.id, scope.batchId),\n eq(projectionBatches.ownerToken, scope.ownerToken),\n eq(projectionBatches.status, \"open\"),\n ),\n )\n .returning({ id: projectionBatches.id });\n if (rows.length === 0) {\n throw new ProjectionBatchFencedError(\n `Projection batch \"${scope.batchId}\" no longer owns its fence`,\n );\n }\n }\n\n private async closeCallbackBatch(scope: ProjectionBatchScope): Promise<void> {\n const now = this.now();\n await this.db\n .update(projectionBatches)\n .set({\n status: \"closed\",\n terminalAt: now,\n lastProgressAt: now,\n leaseExpiresAt: null,\n })\n .where(\n and(\n eq(projectionBatches.id, scope.batchId),\n eq(projectionBatches.ownerToken, scope.ownerToken),\n eq(projectionBatches.status, \"open\"),\n ),\n );\n }\n\n private async assertBatchScope(\n transaction: EntityTransaction,\n scope: ProjectionBatchScope,\n ): Promise<void> {\n const rows = await transaction\n .select({ status: projectionBatches.status })\n .from(projectionBatches)\n .where(\n and(\n eq(projectionBatches.id, scope.batchId),\n eq(projectionBatches.ownerToken, scope.ownerToken),\n ),\n )\n .limit(1);\n if (rows[0]?.status !== \"open\") {\n throw new ProjectionBatchFencedError(\n `Projection batch \"${scope.batchId}\" no longer owns its fence`,\n );\n }\n }\n\n private async recordBatchGeneration(\n transaction: EntityTransaction,\n scope: ProjectionBatchScope,\n generation: number,\n ): Promise<void> {\n const now = this.now();\n // assertBatchScope already validated this owner in the same write\n // transaction, so recovery cannot fence it between validation and update.\n await transaction\n .update(projectionBatches)\n .set({\n firstGeneration: sql`coalesce(${projectionBatches.firstGeneration}, ${generation})`,\n highestGeneration: generation,\n mutationCount: sql`${projectionBatches.mutationCount} + 1`,\n lastProgressAt: now,\n leaseExpiresAt: now + PROJECTION_BATCH_LEASE_MS,\n })\n .where(\n and(\n eq(projectionBatches.id, scope.batchId),\n eq(projectionBatches.ownerToken, scope.ownerToken),\n eq(projectionBatches.status, \"open\"),\n ),\n );\n }\n\n public runMutationTransaction<TResult>(\n mutation: (\n transaction: EntityTransaction,\n recordGeneration: (generation: number) => Promise<void>,\n ) => Promise<TResult>,\n ): Promise<TResult> {\n const scope = this.batchScope.getStore();\n return this.runTransaction(async (transaction) => {\n if (scope) await this.assertBatchScope(transaction, scope);\n return mutation(transaction, async (generation) => {\n if (scope) {\n await this.recordBatchGeneration(transaction, scope, generation);\n }\n });\n });\n }\n\n public async hasActiveBatch(): Promise<boolean> {\n const active = await this.db\n .select({ id: projectionBatches.id })\n .from(projectionBatches)\n .where(inArray(projectionBatches.status, [\"preparing\", \"open\"]))\n .limit(1);\n return active.length > 0;\n }\n\n public async hasActiveBatchInTransaction(\n transaction: EntityTransaction,\n ): Promise<boolean> {\n const active = await transaction\n .select({ id: projectionBatches.id })\n .from(projectionBatches)\n .where(inArray(projectionBatches.status, [\"preparing\", \"open\"]))\n .limit(1);\n return active.length > 0;\n }\n\n public async getAdmissionEpoch(\n transaction: EntityTransaction,\n ): Promise<number> {\n await transaction\n .insert(projectionAdmissionState)\n .values({ id: 1, epoch: 0 })\n .onConflictDoNothing({ target: projectionAdmissionState.id });\n const rows = await transaction\n .select({ epoch: projectionAdmissionState.epoch })\n .from(projectionAdmissionState)\n .where(eq(projectionAdmissionState.id, 1))\n .limit(1);\n return rows[0]?.epoch ?? 0;\n }\n\n public async markRecoveredThrough(\n transaction: EntityTransaction,\n cutoffGeneration: number,\n recoveredAt: number,\n ): Promise<void> {\n await transaction\n .update(projectionBatches)\n .set({ recoveredAt })\n .where(\n and(\n eq(projectionBatches.status, \"abandoned\"),\n isNull(projectionBatches.recoveredAt),\n lte(projectionBatches.recoveryGeneration, cutoffGeneration),\n ),\n );\n }\n\n private getRecoveryGeneration(\n transaction: EntityTransaction,\n fallback: number,\n ): Promise<number> {\n return this.readRecoveryGeneration(transaction, fallback);\n }\n\n private runTransaction<TResult>(\n transaction: (database: EntityTransaction) => Promise<TResult>,\n ): Promise<TResult> {\n return this.transactions.run(transaction);\n }\n\n private runBatchStateWrite<TResult>(\n write: () => Promise<TResult>,\n ): Promise<TResult> {\n return this.transactions.runSqliteWrite(write);\n }\n}\n",
282
282
  "import { z } from \"@brains/utils/zod\";\n\ntype Strict<Shape extends z.ZodRawShape> = z.ZodObject<Shape, z.core.$strict>;\n\nconst bulkMutationInputSchema: Strict<{\n source: z.ZodString;\n operationId: z.ZodString;\n}> = z.strictObject({\n source: z.string().trim().min(1).max(100),\n operationId: z.string().trim().min(1).max(200),\n});\n\nexport type BulkMutationInput = z.output<typeof bulkMutationInputSchema>;\n\nconst durableBulkMutationRootSchema: Strict<{\n source: z.ZodString;\n operationId: z.ZodString;\n rootJobId: z.ZodString;\n expectedChildren: z.ZodNumber;\n}> = z.strictObject({\n source: z.string().trim().min(1).max(100),\n operationId: z.string().trim().min(1).max(200),\n rootJobId: z.string().trim().min(1).max(200),\n expectedChildren: z.number().int().positive().max(10_000),\n});\n\nexport type DurableBulkMutationRootInput = z.output<\n typeof durableBulkMutationRootSchema\n>;\n\nconst durableBulkMutationChildSchema: Strict<{\n source: z.ZodString;\n operationId: z.ZodString;\n rootJobId: z.ZodString;\n expectedChildren: z.ZodNumber;\n childKey: z.ZodString;\n jobId: z.ZodString;\n}> = z.strictObject({\n source: z.string().trim().min(1).max(100),\n operationId: z.string().trim().min(1).max(200),\n rootJobId: z.string().trim().min(1).max(200),\n expectedChildren: z.number().int().positive().max(10_000),\n childKey: z.string().trim().min(1).max(200),\n jobId: z.string().trim().min(1).max(200),\n});\n\nexport type DurableBulkMutationChildInput = z.output<\n typeof durableBulkMutationChildSchema\n>;\n\nconst settleDurableBulkMutationChildSchema: Strict<{\n operationId: z.ZodString;\n childKey: z.ZodString;\n jobId: z.ZodString;\n outcome: z.ZodEnum<{ completed: \"completed\"; failed: \"failed\" }>;\n}> = z.strictObject({\n operationId: z.string().trim().min(1).max(200),\n childKey: z.string().trim().min(1).max(200),\n jobId: z.string().trim().min(1).max(200),\n outcome: z.enum([\"completed\", \"failed\"]),\n});\n\nexport type SettleDurableBulkMutationChildInput = z.output<\n typeof settleDurableBulkMutationChildSchema\n>;\n\nexport function parseBulkMutationInput(input: unknown): BulkMutationInput {\n return bulkMutationInputSchema.parse(input);\n}\n\nexport function parseDurableBulkMutationRootInput(\n input: unknown,\n): DurableBulkMutationRootInput {\n return durableBulkMutationRootSchema.parse(input);\n}\n\nexport function parseDurableBulkMutationChildInput(\n input: unknown,\n): DurableBulkMutationChildInput {\n return durableBulkMutationChildSchema.parse(input);\n}\n\nexport function parseSettleDurableBulkMutationChildInput(\n input: unknown,\n): SettleDurableBulkMutationChildInput {\n return settleDurableBulkMutationChildSchema.parse(input);\n}\n\nexport interface ProjectionBatchOwnedJob {\n jobId: string;\n childKey: string;\n status: \"pending\" | \"processing\" | \"completed\" | \"failed\";\n terminalAt: number | null;\n}\n\nexport type ProjectionBatchRootReader = (\n rootJobId: string,\n operationId: string,\n) => Promise<readonly ProjectionBatchOwnedJob[]>;\n\nexport interface ProjectionBatchRecoveryResult {\n fencedCallbacks: number;\n releasedDurableRoots: number;\n}\n",
283
283
  "import {\n index,\n integer,\n primaryKey,\n sqliteTable,\n text,\n uniqueIndex,\n type SQLiteTableWithColumns,\n} from \"drizzle-orm/sqlite-core\";\nimport type {\n ProjectionIntegerColumn,\n ProjectionTextColumn,\n} from \"./projection-state\";\n\ntype ProjectionAdmissionStateTable = SQLiteTableWithColumns<{\n name: \"projection_admission_state\";\n schema: undefined;\n columns: {\n id: ProjectionIntegerColumn<\n \"projection_admission_state\",\n \"id\",\n true,\n true,\n true\n >;\n epoch: ProjectionIntegerColumn<\n \"projection_admission_state\",\n \"epoch\",\n true,\n true\n >;\n };\n dialect: \"sqlite\";\n}>;\n\ntype ProjectionBatchesTable = SQLiteTableWithColumns<{\n name: \"projection_batches\";\n schema: undefined;\n columns: {\n id: ProjectionTextColumn<\"projection_batches\", \"id\", true, false, true>;\n source: ProjectionTextColumn<\"projection_batches\", \"source\", true>;\n operationId: ProjectionTextColumn<\n \"projection_batches\",\n \"operation_id\",\n true\n >;\n status: ProjectionTextColumn<\n \"projection_batches\",\n \"status\",\n true,\n false,\n false,\n \"preparing\" | \"open\" | \"closed\" | \"abandoned\",\n [\"preparing\", \"open\", \"closed\", \"abandoned\"]\n >;\n ownerKind: ProjectionTextColumn<\n \"projection_batches\",\n \"owner_kind\",\n true,\n false,\n false,\n \"callback\" | \"job-root\",\n [\"callback\", \"job-root\"]\n >;\n ownerToken: ProjectionTextColumn<\"projection_batches\", \"owner_token\", true>;\n rootJobId: ProjectionTextColumn<\"projection_batches\", \"root_job_id\", false>;\n expectedChildren: ProjectionIntegerColumn<\n \"projection_batches\",\n \"expected_children\",\n true,\n true\n >;\n enqueueComplete: ProjectionIntegerColumn<\n \"projection_batches\",\n \"enqueue_complete\",\n true,\n true\n >;\n enqueueFailed: ProjectionIntegerColumn<\n \"projection_batches\",\n \"enqueue_failed\",\n true,\n true\n >;\n openedAt: ProjectionIntegerColumn<\"projection_batches\", \"opened_at\", true>;\n lastProgressAt: ProjectionIntegerColumn<\n \"projection_batches\",\n \"last_progress_at\",\n true\n >;\n leaseExpiresAt: ProjectionIntegerColumn<\n \"projection_batches\",\n \"lease_expires_at\",\n false\n >;\n terminalAt: ProjectionIntegerColumn<\n \"projection_batches\",\n \"terminal_at\",\n false\n >;\n recoveredAt: ProjectionIntegerColumn<\n \"projection_batches\",\n \"recovered_at\",\n false\n >;\n firstGeneration: ProjectionIntegerColumn<\n \"projection_batches\",\n \"first_generation\",\n false\n >;\n highestGeneration: ProjectionIntegerColumn<\n \"projection_batches\",\n \"highest_generation\",\n false\n >;\n mutationCount: ProjectionIntegerColumn<\n \"projection_batches\",\n \"mutation_count\",\n true,\n true\n >;\n recoveryGeneration: ProjectionIntegerColumn<\n \"projection_batches\",\n \"recovery_generation\",\n false\n >;\n };\n dialect: \"sqlite\";\n}>;\n\ntype ProjectionBatchChildrenTable = SQLiteTableWithColumns<{\n name: \"projection_batch_children\";\n schema: undefined;\n columns: {\n batchId: ProjectionTextColumn<\n \"projection_batch_children\",\n \"batch_id\",\n true\n >;\n childKey: ProjectionTextColumn<\n \"projection_batch_children\",\n \"child_key\",\n true\n >;\n jobId: ProjectionTextColumn<\"projection_batch_children\", \"job_id\", false>;\n status: ProjectionTextColumn<\n \"projection_batch_children\",\n \"status\",\n true,\n true,\n false,\n \"expected\" | \"active\" | \"completed\" | \"failed\" | \"missing\",\n [\"expected\", \"active\", \"completed\", \"failed\", \"missing\"]\n >;\n terminalAt: ProjectionIntegerColumn<\n \"projection_batch_children\",\n \"terminal_at\",\n false\n >;\n };\n dialect: \"sqlite\";\n}>;\n\n/** Singleton epoch used to fence waves that overlap a bulk mutation. */\nexport const projectionAdmissionState: ProjectionAdmissionStateTable =\n sqliteTable(\"projection_admission_state\", {\n id: integer(\"id\").primaryKey(),\n epoch: integer(\"epoch\").notNull().default(0),\n });\n\nexport const projectionBatches: ProjectionBatchesTable = sqliteTable(\n \"projection_batches\",\n {\n id: text(\"id\").primaryKey(),\n source: text(\"source\").notNull(),\n operationId: text(\"operation_id\").notNull(),\n status: text(\"status\", {\n enum: [\"preparing\", \"open\", \"closed\", \"abandoned\"],\n }).notNull(),\n ownerKind: text(\"owner_kind\", {\n enum: [\"callback\", \"job-root\"],\n }).notNull(),\n ownerToken: text(\"owner_token\").notNull(),\n rootJobId: text(\"root_job_id\"),\n expectedChildren: integer(\"expected_children\").notNull().default(0),\n enqueueComplete: integer(\"enqueue_complete\").notNull().default(0),\n enqueueFailed: integer(\"enqueue_failed\").notNull().default(0),\n openedAt: integer(\"opened_at\").notNull(),\n lastProgressAt: integer(\"last_progress_at\").notNull(),\n leaseExpiresAt: integer(\"lease_expires_at\"),\n terminalAt: integer(\"terminal_at\"),\n recoveredAt: integer(\"recovered_at\"),\n firstGeneration: integer(\"first_generation\"),\n highestGeneration: integer(\"highest_generation\"),\n mutationCount: integer(\"mutation_count\").notNull().default(0),\n recoveryGeneration: integer(\"recovery_generation\"),\n },\n (table) => ({\n operationIdx: uniqueIndex(\"projection_batches_operation_idx\").on(\n table.source,\n table.operationId,\n ),\n admissionIdx: index(\"projection_batches_admission_idx\").on(\n table.status,\n table.openedAt,\n ),\n rootJobIdx: index(\"projection_batches_root_job_idx\").on(table.rootJobId),\n recoveryIdx: index(\"projection_batches_recovery_idx\").on(\n table.recoveredAt,\n table.recoveryGeneration,\n ),\n }),\n);\n\nexport const projectionBatchChildren: ProjectionBatchChildrenTable =\n sqliteTable(\n \"projection_batch_children\",\n {\n batchId: text(\"batch_id\")\n .notNull()\n .references(() => projectionBatches.id, { onDelete: \"cascade\" }),\n childKey: text(\"child_key\").notNull(),\n jobId: text(\"job_id\"),\n status: text(\"status\", {\n enum: [\"expected\", \"active\", \"completed\", \"failed\", \"missing\"],\n })\n .notNull()\n .default(\"expected\"),\n terminalAt: integer(\"terminal_at\"),\n },\n (table) => ({\n pk: primaryKey({ columns: [table.batchId, table.childKey] }),\n jobIdx: uniqueIndex(\"projection_batch_children_job_idx\").on(table.jobId),\n statusIdx: index(\"projection_batch_children_status_idx\").on(\n table.batchId,\n table.status,\n ),\n }),\n );\n\nexport type ProjectionBatch = typeof projectionBatches.$inferSelect;\nexport type ProjectionBatchChild = typeof projectionBatchChildren.$inferSelect;\n",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rizom/brain",
3
- "version": "0.2.0-alpha.715",
3
+ "version": "0.2.0-alpha.716",
4
4
  "description": "Brain runtime + CLI — scaffold, run, and manage AI brain instances",
5
5
  "keywords": [
6
6
  "brain",
@@ -1,5 +0,0 @@
1
- // @bun
2
- import{B as a}from"./index-52fjmdw8.js";import"./index-66v76w4h.js";import"./index-29fkwc9t.js";import"./index-k5zys460.js";import"./index-c5w93td1.js";import"./index-zvy8405y.js";import"./index-h25wmabx.js";import"./index-z6mmae7e.js";import"./index-kj0ya1j8.js";import"./index-krrz54wf.js";import"./index-2b5c2zq2.js";export{a as App};
3
-
4
- //# debugId=B0224EA8233B0C3764756E2164756E21
5
- //# sourceMappingURL=app-p39chj3k.js.map