@sixb/sqlite 0.1.21 → 0.1.23

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 (100) hide show
  1. package/dist/agents/agent-storage.d.ts +8 -2
  2. package/dist/agents/agent-storage.d.ts.map +1 -1
  3. package/dist/agents/approvals.d.ts +51 -0
  4. package/dist/agents/approvals.d.ts.map +1 -0
  5. package/dist/agents/checkpoints.d.ts +1 -0
  6. package/dist/agents/checkpoints.d.ts.map +1 -1
  7. package/dist/agents/index.d.ts +1 -0
  8. package/dist/agents/index.d.ts.map +1 -1
  9. package/dist/agents/memory.d.ts +21 -0
  10. package/dist/agents/memory.d.ts.map +1 -0
  11. package/dist/agents/messages.d.ts.map +1 -1
  12. package/dist/agents/rows.d.ts +15 -1
  13. package/dist/agents/rows.d.ts.map +1 -1
  14. package/dist/agents/runs.d.ts +14 -1
  15. package/dist/agents/runs.d.ts.map +1 -1
  16. package/dist/agents/settings.d.ts +29 -0
  17. package/dist/agents/settings.d.ts.map +1 -0
  18. package/dist/agents/threads.d.ts +12 -1
  19. package/dist/agents/threads.d.ts.map +1 -1
  20. package/dist/ai-cost-groups.d.ts.map +1 -1
  21. package/dist/ai-cost-storage.d.ts.map +1 -1
  22. package/dist/ai-usage-storage.d.ts +4 -1
  23. package/dist/ai-usage-storage.d.ts.map +1 -1
  24. package/dist/artifact-storage.d.ts +10 -1
  25. package/dist/artifact-storage.d.ts.map +1 -1
  26. package/dist/auth-storage/auth-storage.d.ts +3 -2
  27. package/dist/auth-storage/auth-storage.d.ts.map +1 -1
  28. package/dist/auth-storage/users.d.ts +7 -3
  29. package/dist/auth-storage/users.d.ts.map +1 -1
  30. package/dist/execution-storage.d.ts +2 -1
  31. package/dist/execution-storage.d.ts.map +1 -1
  32. package/dist/index.js +3348 -1515
  33. package/dist/index.js.map +32 -26
  34. package/dist/migrations.d.ts +0 -1
  35. package/dist/migrations.d.ts.map +1 -1
  36. package/dist/objects/conditional-reader.d.ts +8 -0
  37. package/dist/objects/conditional-reader.d.ts.map +1 -0
  38. package/dist/objects/query-compiler.d.ts +26 -1
  39. package/dist/objects/query-compiler.d.ts.map +1 -1
  40. package/dist/objects/read-scope.d.ts +10 -1
  41. package/dist/objects/read-scope.d.ts.map +1 -1
  42. package/dist/objects/reader.d.ts +2 -0
  43. package/dist/objects/reader.d.ts.map +1 -1
  44. package/dist/objects/scoped-reader.d.ts +15 -0
  45. package/dist/objects/scoped-reader.d.ts.map +1 -0
  46. package/dist/objects/selected-reader.d.ts.map +1 -1
  47. package/dist/objects/storage.d.ts +6 -1
  48. package/dist/objects/storage.d.ts.map +1 -1
  49. package/dist/ontology-storage/index.d.ts +2 -0
  50. package/dist/ontology-storage/index.d.ts.map +1 -1
  51. package/dist/ontology-storage/materialization-writer.d.ts +2 -0
  52. package/dist/ontology-storage/materialization-writer.d.ts.map +1 -1
  53. package/dist/ontology-storage/materializations.d.ts.map +1 -1
  54. package/dist/ontology-storage/unique-values.d.ts +42 -0
  55. package/dist/ontology-storage/unique-values.d.ts.map +1 -0
  56. package/package.json +3 -3
  57. package/src/agents/agent-storage.ts +11 -2
  58. package/src/agents/approvals.ts +456 -0
  59. package/src/agents/checkpoints.ts +9 -4
  60. package/src/agents/index.ts +1 -0
  61. package/src/agents/memory.ts +195 -0
  62. package/src/agents/messages.ts +21 -18
  63. package/src/agents/rows.ts +46 -1
  64. package/src/agents/runs.ts +202 -21
  65. package/src/agents/settings.ts +112 -0
  66. package/src/agents/threads.ts +385 -1
  67. package/src/ai-cost-groups.ts +11 -1
  68. package/src/ai-cost-storage.ts +54 -12
  69. package/src/ai-usage-storage.ts +79 -2
  70. package/src/artifact-storage.ts +206 -9
  71. package/src/auth-storage/auth-storage.ts +58 -26
  72. package/src/auth-storage/users.ts +106 -60
  73. package/src/execution-storage.ts +39 -0
  74. package/src/migrations/067-artifact-kinds.sql +32 -0
  75. package/src/migrations/068-artifact-state.sql +15 -0
  76. package/src/migrations/069-agent-thread-participants.sql +16 -0
  77. package/src/migrations/070-forked-context-checkpoints.sql +45 -0
  78. package/src/migrations/071-unique-values.sql +22 -0
  79. package/src/migrations/072-generated-media-usage.sql +32 -0
  80. package/src/migrations/073-model-call-files.sql +11 -0
  81. package/src/migrations/074-agent-memory.sql +32 -0
  82. package/src/migrations/075-artifact-threads.sql +21 -0
  83. package/src/migrations/076-agent-approvals.sql +59 -0
  84. package/src/migrations/077-agent-approval-resume.sql +20 -0
  85. package/src/migrations/078-subagent-threads.sql +241 -0
  86. package/src/migrations/079-subagent-questions.sql +6 -0
  87. package/src/migrations.ts +75 -1
  88. package/src/objects/README.md +7 -0
  89. package/src/objects/conditional-reader.ts +27 -0
  90. package/src/objects/query-compiler.ts +36 -6
  91. package/src/objects/read-scope.ts +140 -23
  92. package/src/objects/reader.ts +47 -14
  93. package/src/objects/scoped-reader.ts +103 -0
  94. package/src/objects/selected-reader.ts +12 -75
  95. package/src/objects/storage.ts +16 -0
  96. package/src/ontology-storage/index.ts +3 -0
  97. package/src/ontology-storage/materialization-writer.ts +14 -0
  98. package/src/ontology-storage/materializations.ts +16 -1
  99. package/src/ontology-storage/unique-values.ts +187 -0
  100. package/src/transactions.ts +1 -1
package/dist/index.js.map CHANGED
@@ -1,26 +1,29 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/index.ts", "../src/action-run-storage.ts", "../src/transactions.ts", "../src/migrations.ts", "../src/activity-storage.ts", "../src/agents/checkpoints.ts", "../src/agents/rows.ts", "../src/agents/messages.ts", "../src/storage-errors.ts", "../src/agents/runs.ts", "../src/run-list-query.ts", "../src/agents/threads.ts", "../src/agents/agent-storage.ts", "../src/ai-cost-storage.ts", "../src/ai-cost-groups.ts", "../src/ai-usage-storage.ts", "../src/ai-limit-storage.ts", "../src/artifact-storage.ts", "../src/auth-storage/auth-storage.ts", "../src/auth-storage/access-tokens.ts", "../src/auth-storage/rows.ts", "../src/auth-storage/shared.ts", "../src/auth-storage/device-authorizations.ts", "../src/auth-storage/group-memberships.ts", "../src/auth-storage/identities.ts", "../src/auth-storage/invitations.ts", "../src/auth-storage/magic-links.ts", "../src/auth-storage/oidc-attempts.ts", "../src/auth-storage/service-account-group-memberships.ts", "../src/auth-storage/service-accounts.ts", "../src/auth-storage/sessions.ts", "../src/auth-storage/users.ts", "../src/connector-connection-storage.ts", "../src/execution-storage.ts", "../src/file-download-grant-storage.ts", "../src/file-upload-session-storage.ts", "../src/objects/storage.ts", "../src/objects/query-compiler.ts", "../src/vector-encoding.ts", "../src/objects/reader.ts", "../src/objects/rows.ts", "../src/objects/vector-extension.ts", "../src/objects/selected-reader.ts", "../src/objects/read-scope.ts", "../src/ontology-storage/shared.ts", "../src/ontology-storage/commits.ts", "../src/ontology-storage/materializations.ts", "../src/ontology-storage/materialization-session.ts", "../src/ontology-storage/materialization-state.ts", "../src/ontology-storage/source-roots.ts", "../src/ontology-storage/replacement-plans.ts", "../src/ontology-storage/materialization-writer.ts", "../src/ontology-storage/outbox.ts", "../src/ontology-storage/sources.ts", "../src/ontology-storage/source-cleanup.ts", "../src/ontology-storage/vector-indexing.ts", "../src/ontology-storage/vectors.ts", "../src/ontology-storage/index.ts", "../src/pipeline-run-storage.ts", "../src/latest-run-query.ts", "../src/projection-run-storage.ts", "../src/rules-storage.ts", "../src/share-grant-storage.ts", "../src/share-session-storage.ts", "../src/sync-run-storage.ts", "../src/testing.ts", "../src/timeseries-storage.ts", "../src/webhook-run-storage.ts", "../src/workflow-intervention-storage.ts", "../src/workflow-run-storage.ts"],
3
+ "sources": ["../src/index.ts", "../src/action-run-storage.ts", "../src/transactions.ts", "../src/migrations.ts", "../src/activity-storage.ts", "../src/agents/approvals.ts", "../src/agents/rows.ts", "../src/agents/checkpoints.ts", "../src/agents/memory.ts", "../src/agents/messages.ts", "../src/storage-errors.ts", "../src/agents/runs.ts", "../src/run-list-query.ts", "../src/agents/settings.ts", "../src/agents/threads.ts", "../src/agents/agent-storage.ts", "../src/ai-cost-storage.ts", "../src/ai-cost-groups.ts", "../src/ai-usage-storage.ts", "../src/ai-limit-storage.ts", "../src/artifact-storage.ts", "../src/auth-storage/auth-storage.ts", "../src/auth-storage/access-tokens.ts", "../src/auth-storage/rows.ts", "../src/auth-storage/shared.ts", "../src/auth-storage/device-authorizations.ts", "../src/auth-storage/group-memberships.ts", "../src/auth-storage/identities.ts", "../src/auth-storage/invitations.ts", "../src/auth-storage/magic-links.ts", "../src/auth-storage/oidc-attempts.ts", "../src/auth-storage/service-account-group-memberships.ts", "../src/auth-storage/service-accounts.ts", "../src/auth-storage/sessions.ts", "../src/auth-storage/users.ts", "../src/connector-connection-storage.ts", "../src/execution-storage.ts", "../src/file-download-grant-storage.ts", "../src/file-upload-session-storage.ts", "../src/objects/storage.ts", "../src/objects/query-compiler.ts", "../src/vector-encoding.ts", "../src/objects/read-scope.ts", "../src/objects/scoped-reader.ts", "../src/objects/reader.ts", "../src/objects/rows.ts", "../src/objects/vector-extension.ts", "../src/objects/conditional-reader.ts", "../src/objects/selected-reader.ts", "../src/ontology-storage/shared.ts", "../src/ontology-storage/commits.ts", "../src/ontology-storage/materializations.ts", "../src/ontology-storage/materialization-session.ts", "../src/ontology-storage/materialization-state.ts", "../src/ontology-storage/source-roots.ts", "../src/ontology-storage/replacement-plans.ts", "../src/ontology-storage/materialization-writer.ts", "../src/ontology-storage/unique-values.ts", "../src/ontology-storage/outbox.ts", "../src/ontology-storage/sources.ts", "../src/ontology-storage/source-cleanup.ts", "../src/ontology-storage/vector-indexing.ts", "../src/ontology-storage/vectors.ts", "../src/ontology-storage/index.ts", "../src/pipeline-run-storage.ts", "../src/latest-run-query.ts", "../src/projection-run-storage.ts", "../src/rules-storage.ts", "../src/share-grant-storage.ts", "../src/share-session-storage.ts", "../src/sync-run-storage.ts", "../src/testing.ts", "../src/timeseries-storage.ts", "../src/webhook-run-storage.ts", "../src/workflow-intervention-storage.ts", "../src/workflow-run-storage.ts"],
4
4
  "sourcesContent": [
5
5
  "// Keep SQL module declarations visible to downstream workspaces that typecheck this package from\n// source.\n/// <reference path=\"./sql.d.ts\" />\n\nimport { AsyncLocalStorage } from \"node:async_hooks\"\nimport type {\n MigrationCapableStorage,\n Storage,\n StorageMigrator,\n StorageTransactionOptions,\n} from \"@sixb/core\"\nimport { ProviderMaterializationTransactionLifecycle } from \"@sixb/core/internal/ontology-storage-provider\"\nimport {\n createTransactionStorageProxy,\n throwNestedStorageTransaction,\n} from \"@sixb/core/internal/storage\"\nimport {\n createAgentOperationScope,\n createAuthOperationScope,\n createObjectOperationScope,\n createOntologyOperationScope,\n createOperationScopedFacade,\n createStorageOperationScope,\n createWorkflowRunOperationScope,\n} from \"@sixb/core/internal/storage-operation-scope\"\nimport {\n type AiCostStorage,\n type AiLimitStorage,\n type AiUsageStorage,\n type ShareGrantStorage,\n type ShareSessionStorage,\n StorageTransactionError,\n} from \"@sixb/core/storage\"\nimport { SqliteActionRunStorage } from \"./action-run-storage\"\nimport { SqliteActivityStorage } from \"./activity-storage\"\nimport { SqliteAgentStorage } from \"./agents\"\nimport { SqliteAiCostStorage } from \"./ai-cost-storage\"\nimport { SqliteAiLimitStorage } from \"./ai-limit-storage\"\nimport { SqliteAiUsageStorage } from \"./ai-usage-storage\"\nimport { SqliteArtifactStorage } from \"./artifact-storage\"\nimport { SqliteAuthStorage } from \"./auth-storage\"\nimport { SqliteConnectorConnectionStorage } from \"./connector-connection-storage\"\nimport { SqliteExecutionStorage } from \"./execution-storage\"\nimport { SqliteFileDownloadGrantStorage } from \"./file-download-grant-storage\"\nimport { SqliteFileUploadSessionStorage } from \"./file-upload-session-storage\"\nimport { createSqliteStorageMigrators, sqliteStoragePath } from \"./migrations\"\nimport { SqliteObjectStorage } from \"./objects\"\nimport { SqliteOntologyStorage, type SqliteOntologyTransactionContext } from \"./ontology-storage\"\nimport { SqlitePipelineRunStorage } from \"./pipeline-run-storage\"\nimport { SqliteProjectionRunStorage } from \"./projection-run-storage\"\nimport { SqliteRulesStorage } from \"./rules-storage\"\nimport { SqliteShareGrantStorage } from \"./share-grant-storage\"\nimport { SqliteShareSessionStorage } from \"./share-session-storage\"\nimport { SqliteSyncRunStorage } from \"./sync-run-storage\"\nimport { registerSqliteStorageTestingAdapter } from \"./testing\"\nimport { SqliteTimeseriesStorage } from \"./timeseries-storage\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n runImmediateTransactionAsync,\n type SqliteStoreConnection,\n} from \"./transactions\"\nimport { SqliteWebhookRunStorage } from \"./webhook-run-storage\"\nimport { SqliteWorkflowInterventionStorage } from \"./workflow-intervention-storage\"\nimport { SqliteWorkflowRunStorage } from \"./workflow-run-storage\"\n\nexport interface SqliteStorageOptions {\n /** Directory path for the SQLite storage database. */\n path?: string\n}\n\n/**\n * SQLite storage provider for Sixb.\n *\n * Bundles object, timeseries, auth, execution, AI accounting, sync run, pipeline run, projection\n * run, workflow run, webhook run, and connector connection storage backed by SQLite.\n *\n * Usage:\n * ```ts\n * const storage = new SqliteStorage({ path: \".sixb\" })\n *\n * export const sixb = createSixb({\n * broker: new InMemoryBroker(),\n * storage,\n * })\n * ```\n */\nexport class SqliteStorage implements MigrationCapableStorage {\n readonly objects: Storage[\"objects\"]\n readonly ontology: SqliteOntologyStorage\n readonly auth: SqliteAuthStorage\n readonly executions: SqliteExecutionStorage\n readonly agents: SqliteAgentStorage\n readonly artifacts: SqliteArtifactStorage\n readonly aiUsage: AiUsageStorage\n readonly aiCosts: AiCostStorage\n readonly aiLimits: AiLimitStorage\n readonly actionRuns: SqliteActionRunStorage\n readonly pipelineRuns: SqlitePipelineRunStorage\n readonly syncRuns: SqliteSyncRunStorage\n readonly projectionRuns: SqliteProjectionRunStorage\n readonly workflowRuns: SqliteWorkflowRunStorage\n readonly workflowInterventions: SqliteWorkflowInterventionStorage\n readonly timeseries: Storage[\"timeseries\"]\n readonly webhookRuns: SqliteWebhookRunStorage\n readonly rules: SqliteRulesStorage\n readonly shareGrants: ShareGrantStorage\n readonly shareSessions: ShareSessionStorage\n readonly connectorConnections: SqliteConnectorConnectionStorage\n readonly fileUploadSessions: SqliteFileUploadSessionStorage\n readonly fileDownloadGrants: SqliteFileDownloadGrantStorage\n readonly activity: SqliteActivityStorage\n readonly migrators: readonly StorageMigrator[]\n\n private readonly connection: SqliteStoreConnection\n private readonly readConnection: SqliteStoreConnection\n private readonly transactionScope = new AsyncLocalStorage<{ active: boolean }>()\n private transactionTail: Promise<void> = Promise.resolve()\n\n constructor(options: SqliteStorageOptions = {}) {\n const path = options.path ? sqliteStoragePath(options.path) : undefined\n this.connection = openSqliteStoreConnection({ path })\n if (path) {\n this.connection.db.run(\"PRAGMA journal_mode = WAL\")\n this.readConnection = openSqliteStoreConnection({ path, readonly: true })\n } else {\n this.readConnection = this.connection\n }\n\n const stores = createSqliteStores(this.connection, {\n runOntologyOperation: async (run) => run(),\n transactionContext: null,\n })\n const assertRootOperationAvailable = () => this.assertRootOperationAvailable()\n const scope = createStorageOperationScope(\n (run) => this.runRootStorageOperation(run),\n assertRootOperationAvailable\n )\n const ontologyScope = createStorageOperationScope(\n (run) => this.runRootOntologyOperation(run),\n assertRootOperationAvailable\n )\n const readScope = path\n ? createStorageOperationScope(async (run) => {\n this.assertRootOperationAvailable()\n return run()\n }, assertRootOperationAvailable)\n : scope\n const readObjects = path\n ? new SqliteObjectStorage({ connection: this.readConnection })\n : stores.objects\n const readTimeseries = path\n ? new SqliteTimeseriesStorage({ connection: this.readConnection })\n : stores.timeseries\n this.objects = createObjectOperationScope(readObjects, readScope)\n this.ontology = createOntologyOperationScope(stores.ontology, ontologyScope)\n this.auth = createAuthOperationScope(stores.auth, scope)\n this.executions = createOperationScopedFacade(stores.executions, scope)\n this.agents = createAgentOperationScope(stores.agents, scope)\n this.artifacts = createOperationScopedFacade(stores.artifacts, scope)\n this.aiUsage = createOperationScopedFacade(stores.aiUsage, scope)\n this.aiCosts = createOperationScopedFacade(stores.aiCosts, scope)\n this.aiLimits = createOperationScopedFacade(stores.aiLimits, scope)\n this.actionRuns = createOperationScopedFacade(stores.actionRuns, scope)\n this.pipelineRuns = createOperationScopedFacade(stores.pipelineRuns, scope)\n this.timeseries = createOperationScopedFacade(readTimeseries, readScope)\n this.syncRuns = createOperationScopedFacade(stores.syncRuns, scope)\n this.projectionRuns = createOperationScopedFacade(stores.projectionRuns, scope)\n this.workflowRuns = createWorkflowRunOperationScope(stores.workflowRuns, scope)\n this.workflowInterventions = createOperationScopedFacade(stores.workflowInterventions, scope)\n this.webhookRuns = createOperationScopedFacade(stores.webhookRuns, scope)\n this.rules = createOperationScopedFacade(stores.rules, scope)\n this.shareGrants = createOperationScopedFacade(stores.shareGrants, scope)\n this.shareSessions = createOperationScopedFacade(stores.shareSessions, scope)\n this.connectorConnections = createOperationScopedFacade(stores.connectorConnections, scope)\n this.fileUploadSessions = createOperationScopedFacade(stores.fileUploadSessions, scope)\n this.fileDownloadGrants = createOperationScopedFacade(stores.fileDownloadGrants, scope)\n this.activity = createOperationScopedFacade(stores.activity, scope)\n this.migrators = options.path ? createSqliteStorageMigrators(options.path) : []\n registerSqliteStorageTestingAdapter(this, {\n advanceConnectorConnectionTime: (durationMs) =>\n stores.connectorConnections.advanceTimeForTesting(durationMs),\n db: this.connection.db,\n })\n }\n\n async ping(): Promise<void> {\n this.assertRootOperationAvailable()\n if (this.readConnection !== this.connection) {\n this.readConnection.db.query(\"SELECT 1\").get()\n return\n }\n await this.runRootStorageOperation(() => {\n this.connection.db.query(\"SELECT 1\").get()\n })\n }\n\n /**\n * The `isolation` option is intentionally ignored. SQLite runs every write transaction through\n * one connection serialized by {@link withTransactionLock} and a `BEGIN IMMEDIATE`, so there is no\n * concurrent writer to isolate against. File-backed object and timeseries reads use a separate WAL\n * snapshot connection; Postgres is where `isolation: \"serializable\"` maps to a real isolation level.\n */\n async transaction<T>(\n run: (tx: Storage) => Promise<T> | T,\n _options: StorageTransactionOptions = {}\n ): Promise<T> {\n if (this.transactionScope.getStore()) {\n throwNestedStorageTransaction()\n }\n\n return this.withTransactionLock(async () => {\n let active = true\n const scope = { active: true }\n const transactionContext: SqliteOntologyTransactionContext = {\n id: {},\n materializations: new ProviderMaterializationTransactionLifecycle(),\n active: true,\n }\n const txStorage = this.createTransactionStorage(transactionContext)\n const tx = createTransactionStorageProxy(txStorage, () => active)\n\n try {\n return await runImmediateTransactionAsync(this.connection.db, () =>\n this.transactionScope.run(scope, async () => {\n try {\n const result = await run(tx)\n transactionContext.materializations.assertCommittable()\n return result\n } finally {\n scope.active = false\n transactionContext.active = false\n txStorage.ontology.deactivateSessions()\n transactionContext.materializations.deactivate()\n }\n })\n )\n } finally {\n active = false\n }\n })\n }\n\n close(): void {\n if (this.readConnection !== this.connection) closeSqliteStoreConnection(this.readConnection)\n closeSqliteStoreConnection(this.connection)\n }\n\n private createTransactionStorage(\n transactionContext: SqliteOntologyTransactionContext\n ): Storage & { readonly ontology: SqliteOntologyStorage } {\n return {\n ...createSqliteStores(\n {\n db: this.connection.db,\n ownsConnection: false,\n },\n {\n runOntologyOperation: async (run) => run(),\n transactionContext,\n }\n ),\n ping: async () => {\n this.connection.db.query(\"SELECT 1\").get()\n },\n transaction: async <T>(): Promise<T> => {\n throwNestedStorageTransaction()\n },\n }\n }\n\n private runRootStorageOperation<T>(run: () => Promise<T> | T): Promise<T> {\n this.assertRootOperationAvailable()\n return this.withTransactionLock(async () => run())\n }\n\n private runRootOntologyOperation<T>(run: () => Promise<T> | T): Promise<T> {\n this.assertRootOperationAvailable()\n return this.withTransactionLock(() => runImmediateTransactionAsync(this.connection.db, run))\n }\n\n private assertRootOperationAvailable(): void {\n if (!this.transactionScope.getStore()?.active) return\n throw new StorageTransactionError(\n \"[SixbSqlite] Root storage cannot be used inside a transaction callback; use the provided tx storage.\"\n )\n }\n\n private async withTransactionLock<T>(run: () => Promise<T>): Promise<T> {\n const previous = this.transactionTail\n let release!: () => void\n this.transactionTail = new Promise<void>((resolve) => {\n release = resolve\n })\n\n await previous\n try {\n return await run()\n } finally {\n release()\n }\n }\n}\n\nfunction createSqliteStores(\n connection: SqliteStoreConnection,\n options: {\n readonly runOntologyOperation: <T>(run: () => Promise<T> | T) => Promise<T>\n readonly transactionContext: SqliteOntologyTransactionContext | null\n }\n): SqliteStoreSet {\n const auth = new SqliteAuthStorage({ connection })\n const shareGrants = new SqliteShareGrantStorage({ connection })\n const shareSessions = new SqliteShareSessionStorage({ connection })\n const executions = new SqliteExecutionStorage(connection.db, auth, shareSessions)\n return {\n objects: new SqliteObjectStorage({ connection }),\n ontology: new SqliteOntologyStorage({\n db: connection.db,\n runRootOperation: options.runOntologyOperation,\n transactionContext: options.transactionContext,\n }),\n auth,\n executions,\n agents: new SqliteAgentStorage({ connection, executions }),\n artifacts: new SqliteArtifactStorage(connection),\n aiUsage: new SqliteAiUsageStorage({ connection }),\n aiCosts: new SqliteAiCostStorage(connection),\n aiLimits: new SqliteAiLimitStorage({ connection }),\n actionRuns: new SqliteActionRunStorage({ connection, executions }),\n pipelineRuns: new SqlitePipelineRunStorage({ connection, executions }),\n timeseries: new SqliteTimeseriesStorage({ connection }),\n syncRuns: new SqliteSyncRunStorage({ connection, executions }),\n projectionRuns: new SqliteProjectionRunStorage({ connection, executions }),\n workflowRuns: new SqliteWorkflowRunStorage({ connection, executions }),\n workflowInterventions: new SqliteWorkflowInterventionStorage({ connection }),\n webhookRuns: new SqliteWebhookRunStorage({ connection, executions }),\n rules: new SqliteRulesStorage({ connection }),\n shareGrants,\n shareSessions,\n connectorConnections: new SqliteConnectorConnectionStorage(connection),\n fileUploadSessions: new SqliteFileUploadSessionStorage(connection),\n fileDownloadGrants: new SqliteFileDownloadGrantStorage(connection),\n activity: new SqliteActivityStorage(connection),\n }\n}\n\ninterface SqliteStoreSet {\n readonly objects: SqliteObjectStorage\n readonly ontology: SqliteOntologyStorage\n readonly auth: SqliteAuthStorage\n readonly executions: SqliteExecutionStorage\n readonly agents: SqliteAgentStorage\n readonly artifacts: SqliteArtifactStorage\n readonly aiUsage: SqliteAiUsageStorage\n readonly aiCosts: SqliteAiCostStorage\n readonly aiLimits: SqliteAiLimitStorage\n readonly actionRuns: SqliteActionRunStorage\n readonly pipelineRuns: SqlitePipelineRunStorage\n readonly syncRuns: SqliteSyncRunStorage\n readonly projectionRuns: SqliteProjectionRunStorage\n readonly workflowRuns: SqliteWorkflowRunStorage\n readonly workflowInterventions: SqliteWorkflowInterventionStorage\n readonly timeseries: SqliteTimeseriesStorage\n readonly webhookRuns: SqliteWebhookRunStorage\n readonly rules: SqliteRulesStorage\n readonly shareGrants: SqliteShareGrantStorage\n readonly shareSessions: SqliteShareSessionStorage\n readonly connectorConnections: SqliteConnectorConnectionStorage\n readonly fileUploadSessions: SqliteFileUploadSessionStorage\n readonly fileDownloadGrants: SqliteFileDownloadGrantStorage\n readonly activity: SqliteActivityStorage\n}\n\nexport { migrateSqliteStorage } from \"./migrations\"\n",
6
6
  "import type { Database } from \"bun:sqlite\"\nimport type { ActionSubject, JsonValue } from \"@sixb/core\"\nimport {\n parseActionRunFailure,\n serializeActionRunFailure,\n} from \"@sixb/core/internal/action-run-storage\"\nimport { assertActionRunExecution } from \"@sixb/core/internal/action-run-storage-provider\"\nimport { normalizeRecordActionRunInput, resolveActionRunEffects } from \"@sixb/core/internal/storage\"\nimport type {\n ActionRunEffectsRecord,\n ActionRunPhase,\n ActionRunRecord,\n ActionRunStatus,\n ActionRunStorage,\n ActionRunWritebackRecord,\n ExecutionStorage,\n ListActionRunsInput,\n ListActionRunsResult,\n RecordActionEffectsInput,\n RecordActionRunInput,\n} from \"@sixb/core/storage\"\nimport { ActionRunError } from \"@sixb/core/storage\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n type SqliteStoreConnection,\n} from \"./transactions\"\n\nexport interface SqliteActionRunStorageOptions {\n /** Execution lookup sharing the same provider transaction. */\n executions: ExecutionStorage\n /** Path to SQLite database file. Defaults to ':memory:' for in-memory database. */\n path?: string\n /** Internal shared connection used by bundled SqliteStorage. */\n connection?: SqliteStoreConnection\n}\n\nexport class SqliteActionRunStorage implements ActionRunStorage {\n private readonly connection: SqliteStoreConnection\n private readonly db: Database\n\n private readonly executions: ExecutionStorage\n\n constructor(options: SqliteActionRunStorageOptions) {\n this.connection = openSqliteStoreConnection(options)\n this.db = this.connection.db\n this.executions = options.executions\n }\n\n async record(input: RecordActionRunInput): Promise<ActionRunRecord> {\n const record = normalizeRecordActionRunInput(input)\n await assertActionRunExecution({\n executions: this.executions,\n projectId: record.projectId,\n executionId: record.executionId,\n runId: record.id,\n actionId: record.actionId,\n })\n\n const inserted = this.db\n .query(\n `\n INSERT INTO action_runs (\n project_id,\n id,\n execution_id,\n action_id,\n subject_kind,\n object_type_id,\n primary_id,\n status,\n phase,\n started_at,\n finished_at,\n params,\n idempotency_key,\n writeback_status,\n writeback_completed_at,\n writeback_result,\n writeback_error,\n error\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT DO NOTHING\n `\n )\n .run(\n record.projectId,\n record.id,\n record.executionId,\n record.actionId,\n record.subject.kind,\n record.subject.kind === \"object\" ? record.subject.objectTypeId : null,\n record.subject.kind === \"object\" ? record.subject.primaryId : null,\n record.status,\n record.phase,\n record.startedAt.toISOString(),\n record.finishedAt.toISOString(),\n JSON.stringify(record.params),\n record.idempotencyKey,\n record.writeback?.status ?? null,\n record.writeback?.completedAt.toISOString() ?? null,\n record.writeback?.status === \"succeeded\" ? JSON.stringify(record.writeback.result) : null,\n record.writeback?.status === \"failed\"\n ? serializeActionRunFailure(record.writeback.error, \"writeback\")\n : null,\n record.status === \"failed\" ? serializeActionRunFailure(record.error) : null\n )\n\n if (inserted.changes === 0) {\n const conflict = this.selectRow(record.projectId, record.id)\n throw new ActionRunError(\n conflict\n ? `[SixbSqlite] Action run '${record.id}' is already recorded for project '${record.projectId}'.`\n : `[SixbSqlite] Execution '${record.executionId}' already belongs to another Action run.`\n )\n }\n return rowToActionRunRecord(this.requireRow(record.projectId, record.id))\n }\n\n async recordEffects(input: RecordActionEffectsInput): Promise<ActionRunRecord> {\n return this.db.transaction(() => {\n const existing = this.selectRow(input.projectId, input.id)\n const { run, effects } = resolveActionRunEffects(\n existing ? rowToActionRunRecord(existing) : null,\n input\n )\n if (!effects) return run\n\n this.db\n .query(\n `\n UPDATE action_runs\n SET\n phase = ?,\n effects_status = ?,\n effects_completed_at = ?,\n effects_error = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n \"effects\",\n effects.status,\n effects.completedAt.toISOString(),\n effects.status === \"failed\" ? serializeActionRunFailure(effects.error, \"effects\") : null,\n input.projectId,\n input.id\n )\n return rowToActionRunRecord(this.requireRow(input.projectId, input.id))\n })()\n }\n\n async getById(params: { projectId: string; id: string }): Promise<ActionRunRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM action_runs WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as DatabaseRow | null\n\n return row ? rowToActionRunRecord(row) : null\n }\n\n async getByExecutionIds(params: {\n readonly projectId: string\n readonly executionIds: readonly string[]\n }): Promise<readonly ActionRunRecord[]> {\n const executionIds = [...new Set(params.executionIds)]\n if (executionIds.length === 0) {\n return []\n }\n\n const rows = this.db\n .query(\n `\n SELECT *\n FROM action_runs\n WHERE project_id = ?\n AND execution_id IN (SELECT value FROM json_each(?))\n `\n )\n .all(params.projectId, JSON.stringify(executionIds)) as DatabaseRow[]\n\n const byExecution = new Map(rows.map((row) => [row.execution_id, row]))\n return executionIds.flatMap((executionId) => {\n const row = byExecution.get(executionId)\n return row ? [rowToActionRunRecord(row)] : []\n })\n }\n\n async list(input: ListActionRunsInput): Promise<ListActionRunsResult> {\n if ((input.statuses && input.statuses.length === 0) || input.actionIds?.length === 0) {\n return {\n runs: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: (string | number)[] = [input.projectId]\n\n if (input.actionId) {\n whereClauses.push(\"action_id = ?\")\n args.push(input.actionId)\n }\n\n if (input.actionIds) {\n whereClauses.push(`action_id IN (${input.actionIds.map(() => \"?\").join(\", \")})`)\n args.push(...input.actionIds)\n }\n\n if (input.objectTypeIds) {\n if (input.objectTypeIds.length === 0) {\n whereClauses.push(\"subject_kind <> ?\")\n args.push(\"object\")\n } else {\n whereClauses.push(\n `(subject_kind <> ? OR object_type_id IN (${input.objectTypeIds\n .map(() => \"?\")\n .join(\", \")}))`\n )\n args.push(\"object\", ...input.objectTypeIds)\n }\n }\n\n if (input.objectTypeId) {\n whereClauses.push(\"subject_kind = ?\")\n args.push(\"object\")\n whereClauses.push(\"object_type_id = ?\")\n args.push(input.objectTypeId)\n }\n\n if (input.primaryId) {\n whereClauses.push(\"subject_kind = ?\")\n args.push(\"object\")\n whereClauses.push(\"primary_id = ?\")\n args.push(input.primaryId)\n }\n\n if (input.subject) {\n whereClauses.push(\"subject_kind = ?\")\n args.push(input.subject.kind)\n if (input.subject.kind === \"object\") {\n whereClauses.push(\"object_type_id = ?\")\n args.push(input.subject.objectTypeId)\n whereClauses.push(\"primary_id = ?\")\n args.push(input.subject.primaryId)\n }\n }\n\n if (input.statuses) {\n whereClauses.push(`status IN (${input.statuses.map(() => \"?\").join(\", \")})`)\n args.push(...input.statuses)\n }\n\n if (input.startedAfter) {\n whereClauses.push(\"started_at >= ?\")\n args.push(input.startedAfter.toISOString())\n }\n\n if (input.startedBefore) {\n whereClauses.push(\"started_at <= ?\")\n args.push(input.startedBefore.toISOString())\n }\n\n const where = `WHERE ${whereClauses.join(\" AND \")}`\n const order = input.order === \"asc\" ? \"ASC\" : \"DESC\"\n const offset = input.offset ?? 0\n const limit = input.limit\n\n const totalRow = this.db\n .query(`SELECT COUNT(*) AS count FROM action_runs ${where}`)\n .get(...args) as { count: number }\n\n let query = `\n SELECT * FROM action_runs\n ${where}\n ORDER BY started_at ${order}, id ${order}\n `\n const queryArgs = [...args]\n\n if (limit !== undefined) {\n query += \" LIMIT ? OFFSET ?\"\n queryArgs.push(limit, offset)\n } else if (offset > 0) {\n query += \" LIMIT -1 OFFSET ?\"\n queryArgs.push(offset)\n }\n\n const rows = this.db.query(query).all(...queryArgs) as DatabaseRow[]\n const runs = rows.map((row) => rowToActionRunRecord(row))\n\n return {\n runs,\n hasMore: offset + runs.length < totalRow.count,\n total: totalRow.count,\n }\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n\n private selectRow(projectId: string, id: string): DatabaseRow | null {\n return this.db\n .query(\"SELECT * FROM action_runs WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as DatabaseRow | null\n }\n\n private requireRow(projectId: string, id: string): DatabaseRow {\n const row = this.selectRow(projectId, id)\n if (!row) {\n throw new ActionRunError(\n `[SixbSqlite] Action run '${id}' disappeared from project '${projectId}' while recording it.`\n )\n }\n return row\n }\n}\n\nfunction toActionRunWritebackRecord(row: DatabaseRow): ActionRunWritebackRecord | undefined {\n if (!row.writeback_status) {\n return undefined\n }\n\n const completedAt = new Date(row.writeback_completed_at ?? row.finished_at)\n if (row.writeback_status === \"succeeded\") {\n return {\n status: \"succeeded\",\n completedAt,\n result:\n row.writeback_result === null ? null : (JSON.parse(row.writeback_result) as JsonValue),\n }\n }\n\n return {\n status: \"failed\",\n completedAt,\n error: parseActionRunFailure(row.writeback_error, \"writeback\"),\n }\n}\n\nfunction toActionRunEffectsRecord(row: DatabaseRow): ActionRunEffectsRecord | undefined {\n if (!row.effects_status) {\n return undefined\n }\n\n const completedAt = new Date(row.effects_completed_at ?? row.finished_at)\n if (row.effects_status === \"succeeded\") {\n return {\n status: \"succeeded\",\n completedAt,\n }\n }\n\n return {\n status: \"failed\",\n completedAt,\n error: parseActionRunFailure(row.effects_error, \"effects\"),\n }\n}\n\nfunction rowToActionRunRecord(row: DatabaseRow): ActionRunRecord {\n const writeback = toActionRunWritebackRecord(row)\n const effects = toActionRunEffectsRecord(row)\n const fields = {\n id: row.id,\n projectId: row.project_id,\n executionId: row.execution_id,\n actionId: row.action_id,\n subject: rowToActionSubject(row),\n phase: row.phase,\n startedAt: new Date(row.started_at),\n finishedAt: new Date(row.finished_at),\n params: JSON.parse(row.params) as ActionRunRecord[\"params\"],\n idempotencyKey: row.idempotency_key,\n ...(writeback === undefined ? {} : { writeback }),\n ...(effects === undefined ? {} : { effects }),\n }\n\n if (row.status === \"succeeded\") return { ...fields, status: \"succeeded\" }\n return { ...fields, status: \"failed\", error: parseActionRunFailure(row.error) }\n}\n\nfunction rowToActionSubject(row: DatabaseRow): ActionSubject {\n if (row.subject_kind === \"none\") {\n return { kind: \"none\" }\n }\n\n if (!row.object_type_id || !row.primary_id) {\n throw new ActionRunError(`[SixbSqlite] Action run '${row.id}' has an invalid object subject.`)\n }\n\n return {\n kind: \"object\",\n objectTypeId: row.object_type_id,\n primaryId: row.primary_id,\n }\n}\n\ninterface DatabaseRow {\n project_id: string\n id: string\n execution_id: string\n action_id: string\n subject_kind: ActionSubject[\"kind\"]\n object_type_id: string | null\n primary_id: string | null\n status: ActionRunStatus\n phase: ActionRunPhase\n started_at: string\n finished_at: string\n params: string\n idempotency_key: string\n writeback_status: ActionRunWritebackRecord[\"status\"] | null\n writeback_completed_at: string | null\n writeback_result: string | null\n writeback_error: string | null\n effects_status: ActionRunEffectsRecord[\"status\"] | null\n effects_completed_at: string | null\n effects_error: string | null\n error: string | null\n}\n",
7
- "import type { Database } from \"bun:sqlite\"\nimport { Database as SqliteDatabase } from \"bun:sqlite\"\nimport { mkdirSync } from \"node:fs\"\nimport { dirname } from \"node:path\"\nimport { freshSqliteDatabase } from \"./migrations\"\n\nexport interface SqliteStoreConnection {\n readonly db: Database\n readonly ownsConnection: boolean\n}\n\nexport interface SqliteStoreConnectionOptions {\n readonly path?: string\n readonly connection?: SqliteStoreConnection\n readonly readonly?: boolean\n}\n\nexport function openSqliteStoreConnection(\n options: SqliteStoreConnectionOptions = {}\n): SqliteStoreConnection {\n if (options.connection) {\n return {\n db: options.connection.db,\n ownsConnection: false,\n }\n }\n\n const path = options.path ?? \":memory:\"\n if (path !== \":memory:\" && !options.readonly) mkdirSync(dirname(path), { recursive: true })\n // A file is brought up to date by its migrators; a writable in-memory database starts with the\n // whole schema.\n const db =\n path === \":memory:\" && !options.readonly\n ? freshSqliteDatabase()\n : new SqliteDatabase(path, options.readonly ? { readonly: true } : undefined)\n db.run(\"PRAGMA foreign_keys = ON\")\n db.run(\"PRAGMA busy_timeout = 5000\")\n return { db, ownsConnection: true }\n}\n\nexport function closeSqliteStoreConnection(connection: SqliteStoreConnection): void {\n if (connection.ownsConnection) {\n connection.db.close()\n }\n}\n\nconst activeImmediateTransactions = new WeakSet<Database>()\nconst activeDeferredReadTransactions = new WeakSet<Database>()\n\nexport function runImmediateTransaction<T>(db: Database, run: () => T): T {\n if (activeImmediateTransactions.has(db)) {\n return run()\n }\n\n db.run(\"BEGIN IMMEDIATE\")\n activeImmediateTransactions.add(db)\n\n try {\n const result = run()\n db.run(\"COMMIT\")\n return result\n } catch (error) {\n rollbackQuietly(db)\n throw error\n } finally {\n activeImmediateTransactions.delete(db)\n }\n}\n\n/** Lets timers and request handlers run between bounded synchronous SQLite chunks. */\nexport function yieldSqliteEventLoop(): Promise<void> {\n return new Promise((resolve) => setImmediate(resolve))\n}\n\nexport async function runImmediateTransactionAsync<T>(\n db: Database,\n run: () => Promise<T> | T\n): Promise<T> {\n if (activeImmediateTransactions.has(db)) {\n return run()\n }\n\n db.run(\"BEGIN IMMEDIATE\")\n activeImmediateTransactions.add(db)\n\n try {\n const result = await run()\n db.run(\"COMMIT\")\n return result\n } catch (error) {\n rollbackQuietly(db)\n throw error\n } finally {\n activeImmediateTransactions.delete(db)\n }\n}\n\n/**\n * Run a multi-statement read against one proven SQLite snapshot.\n *\n * A provider-owned immediate transaction already has a stable snapshot and may be reused. Any\n * other pre-existing transaction is rejected because this provider cannot prove who owns it or\n * which lifecycle will close it.\n */\nexport function runDeferredReadTransaction<T>(db: Database, run: () => T): T {\n if (activeImmediateTransactions.has(db) || activeDeferredReadTransactions.has(db)) {\n return run()\n }\n if (db.inTransaction) {\n throw new Error(\n \"[SixbSqlite] Selected object reads cannot join an unverified SQLite transaction.\"\n )\n }\n\n db.run(\"BEGIN DEFERRED\")\n activeDeferredReadTransactions.add(db)\n try {\n const result = run()\n db.run(\"COMMIT\")\n return result\n } catch (error) {\n rollbackQuietly(db)\n throw error\n } finally {\n activeDeferredReadTransactions.delete(db)\n }\n}\n\nfunction rollbackQuietly(db: Database): void {\n try {\n db.run(\"ROLLBACK\")\n } catch {\n // Preserve the original SQLite storage failure.\n }\n}\n",
8
- "import { Database } from \"bun:sqlite\"\nimport { createHash } from \"node:crypto\"\nimport { existsSync, mkdirSync } from \"node:fs\"\nimport { dirname } from \"node:path\"\nimport type { StorageMigrator } from \"@sixb/core\"\nimport type {\n MigrationHistoryStore,\n MigrationRecord,\n MigrationSet,\n MigrationStep,\n MigrationStepOptions,\n} from \"@sixb/core/storage\"\nimport {\n defineMigrations,\n describeMigrationHistory,\n runMigrationSet,\n step,\n} from \"@sixb/core/storage\"\nimport initialSchemaSql from \"./migrations/001-initial-schema.sql\" with { type: \"text\" }\nimport workflowRunOutputSql from \"./migrations/002-workflow-run-output.sql\" with { type: \"text\" }\nimport mergeSyncRunsSql from \"./migrations/003-merge-sync-runs.sql\" with { type: \"text\" }\nimport executionsSql from \"./migrations/004-executions.sql\" with { type: \"text\" }\nimport workflowExecutionsSql from \"./migrations/005-workflow-executions.sql\" with { type: \"text\" }\nimport narrowOntologySourceRootIndexSql from \"./migrations/006-narrow-ontology-source-root-index.sql\" with {\n type: \"text\",\n}\nimport splitOverridesSql from \"./migrations/007-split-overrides.sql\" with { type: \"text\" }\nimport actionExecutionsSql from \"./migrations/008-action-executions.sql\" with { type: \"text\" }\nimport agentExecutionsSql from \"./migrations/009-agent-executions.sql\" with { type: \"text\" }\nimport aiUsageAccountingFoundationSql from \"./migrations/010-ai-usage-accounting-foundation.sql\" with {\n type: \"text\",\n}\nimport syncFailureRecordSql from \"./migrations/011-sync-failure-record.sql\" with { type: \"text\" }\nimport pipelineFailureRecordSql from \"./migrations/012-pipeline-failure-record.sql\" with {\n type: \"text\",\n}\nimport workflowFailureRecordSql from \"./migrations/013-workflow-failure-record.sql\" with {\n type: \"text\",\n}\nimport agentFailureRecordSql from \"./migrations/014-agent-failure-record.sql\" with { type: \"text\" }\nimport projectionFailureRecordSql from \"./migrations/015-projection-failure-record.sql\" with {\n type: \"text\",\n}\nimport webhookRunFailureRecordSql from \"./migrations/016-webhook-run-failure-record.sql\" with {\n type: \"text\",\n}\nimport actionFailureRecordSql from \"./migrations/017-action-failure-record.sql\" with {\n type: \"text\",\n}\nimport ontologyOutboxFailureRecordSql from \"./migrations/018-ontology-outbox-failure-record.sql\" with {\n type: \"text\",\n}\nimport webhookDeliveryFailureRecordSql from \"./migrations/019-webhook-delivery-failure-record.sql\" with {\n type: \"text\",\n}\nimport dropRunUsageProjectionsSql from \"./migrations/020-drop-run-usage-projections.sql\" with {\n type: \"text\",\n}\nimport syncPipelineExecutionsSql from \"./migrations/021-sync-pipeline-executions.sql\" with {\n type: \"text\",\n}\nimport projectionExecutionsSql from \"./migrations/022-projection-executions.sql\" with {\n type: \"text\",\n}\nimport webhookExecutionsSql from \"./migrations/023-webhook-executions.sql\" with { type: \"text\" }\nimport ontologyCommitExecutionsSql from \"./migrations/024-ontology-commit-executions.sql\" with {\n type: \"text\",\n}\nimport connectorConnectionsSql from \"./migrations/025-connector-connections.sql\" with {\n type: \"text\",\n}\nimport aiCostAccountingSql from \"./migrations/026-ai-cost-accounting.sql\" with { type: \"text\" }\nimport agentContextCheckpointsSql from \"./migrations/027-agent-context-checkpoints.sql\" with {\n type: \"text\",\n}\nimport objectOverrideEditTimesSql from \"./migrations/028-object-override-edit-times.sql\" with {\n type: \"text\",\n}\nimport modelAccountingSql from \"./migrations/029-model-accounting.sql\" with { type: \"text\" }\nimport aiUsageLimitsSql from \"./migrations/030-ai-usage-limits.sql\" with { type: \"text\" }\nimport subagentRunsSql from \"./migrations/031-subagent-runs.sql\" with { type: \"text\" }\nimport conversationRunSpecSql from \"./migrations/032-conversation-run-spec.sql\" with {\n type: \"text\",\n}\nimport retireAgentDefinitionsSql from \"./migrations/033-retire-agent-definitions.sql\" with {\n type: \"text\",\n}\nimport deviceAuthorizationsSql from \"./migrations/034-device-authorizations.sql\" with {\n type: \"text\",\n}\nimport shareGrantsSql from \"./migrations/035-share-grants.sql\" with { type: \"text\" }\nimport shareSessionsSql from \"./migrations/036-share-sessions.sql\" with { type: \"text\" }\nimport projectionSourceRootsSql from \"./migrations/038-projection-source-roots.sql\" with {\n type: \"text\",\n}\nimport outboxPublicationOrderSql from \"./migrations/040-outbox-publication-order.sql\" with {\n type: \"text\",\n}\nimport agentThreadWorkspacesSql from \"./migrations/041-agent-thread-workspaces.sql\" with {\n type: \"text\",\n}\nimport vectorProfilesSql from \"./migrations/042-vector-profiles.sql\" with { type: \"text\" }\nimport vectorIndexingSql from \"./migrations/043-vector-indexing.sql\" with { type: \"text\" }\nimport vectorBatchingSql from \"./migrations/044-vector-batching.sql\" with { type: \"text\" }\nimport agentThreadSandboxStateSql from \"./migrations/045-agent-thread-sandbox-state.sql\" with {\n type: \"text\",\n}\nimport workflowInterventionPrincipalsSql from \"./migrations/046-workflow-intervention-principals.sql\" with {\n type: \"text\",\n}\nimport ontologyCommitAttributionSql from \"./migrations/047-ontology-commit-attribution.sql\" with {\n type: \"text\",\n}\nimport nativeSessionsSql from \"./migrations/049-native-sessions.sql\" with { type: \"text\" }\nimport directoryGroupMembershipsSql from \"./migrations/050-directory-group-memberships.sql\" with {\n type: \"text\",\n}\nimport projectionRunSupersessionSql from \"./migrations/051-projection-run-supersession.sql\" with {\n type: \"text\",\n}\nimport compactSourceStorageSql from \"./migrations/052-compact-source-storage.sql\" with {\n type: \"text\",\n}\nimport replacementPlansSql from \"./migrations/053-replacement-plans.sql\" with { type: \"text\" }\nimport slimOntologyOutboxSql from \"./migrations/054-slim-ontology-outbox.sql\" with { type: \"text\" }\nimport commitTouchesSql from \"./migrations/055-commit-touches.sql\" with { type: \"text\" }\nimport audioTranscriptionSql from \"./migrations/056-audio-transcription.sql\" with { type: \"text\" }\nimport rerankingModelKindSql from \"./migrations/057-reranking-model-kind.sql\" with { type: \"text\" }\n\nconst MIGRATIONS_TABLE_SQL = `\n CREATE TABLE IF NOT EXISTS sixb_migrations (\n adapter_id TEXT NOT NULL,\n version INTEGER NOT NULL,\n id TEXT NOT NULL,\n checksum TEXT,\n status TEXT NOT NULL,\n started_at TEXT NOT NULL,\n finished_at TEXT,\n PRIMARY KEY (adapter_id, version)\n );\n`\n\nexport const SQLITE_STORAGE_ADAPTER_ID = \"SixbSqliteStorage\"\nexport const SQLITE_STORAGE_FILE = \"storage.sqlite\"\n\nexport const sqliteStorageMigrations = defineMigrations({\n adapterId: SQLITE_STORAGE_ADAPTER_ID,\n steps: [\n sqliteSql(\"001-initial-schema\", initialSchemaSql),\n sqliteSql(\"002-workflow-run-output\", workflowRunOutputSql),\n sqliteSql(\"003-merge-sync-runs\", mergeSyncRunsSql),\n sqliteSql(\"004-executions\", executionsSql),\n sqliteSql(\"005-workflow-executions\", workflowExecutionsSql),\n sqliteSql(\"006-narrow-ontology-source-root-index\", narrowOntologySourceRootIndexSql),\n sqliteSql(\"007-split-overrides\", splitOverridesSql),\n sqliteSql(\"008-action-executions\", actionExecutionsSql),\n sqliteSql(\"009-agent-executions\", agentExecutionsSql),\n sqliteSql(\"010-ai-usage-accounting-foundation\", aiUsageAccountingFoundationSql),\n sqliteSql(\"011-sync-failure-record\", syncFailureRecordSql),\n sqliteSql(\"012-pipeline-failure-record\", pipelineFailureRecordSql),\n sqliteSql(\"013-workflow-failure-record\", workflowFailureRecordSql),\n sqliteSql(\"014-agent-failure-record\", agentFailureRecordSql),\n sqliteSql(\"015-projection-failure-record\", projectionFailureRecordSql),\n sqliteSql(\"016-webhook-run-failure-record\", webhookRunFailureRecordSql),\n sqliteSql(\"017-action-failure-record\", actionFailureRecordSql),\n sqliteSql(\"018-ontology-outbox-failure-record\", ontologyOutboxFailureRecordSql),\n sqliteSql(\"019-webhook-delivery-failure-record\", webhookDeliveryFailureRecordSql),\n sqliteSql(\"020-drop-run-usage-projections\", dropRunUsageProjectionsSql),\n sqliteSql(\"021-sync-pipeline-executions\", syncPipelineExecutionsSql),\n sqliteStep(\n \"022-projection-executions\",\n (db) => {\n if (db.query(\"SELECT 1 FROM projection_runs LIMIT 1\").get()) {\n throw new Error(\n \"[SixbSqliteStorage] Projection execution migration cannot preserve legacy runs with unknown authority.\"\n )\n }\n db.run(projectionExecutionsSql)\n },\n { checksum: checksum(projectionExecutionsSql) }\n ),\n sqliteStep(\n \"023-webhook-executions\",\n (db) => {\n const hasRuns = db.query(\"SELECT 1 FROM webhook_runs LIMIT 1\").get()\n const hasDeliveries = db.query(\"SELECT 1 FROM webhook_deliveries LIMIT 1\").get()\n if (hasRuns || hasDeliveries) {\n throw new Error(\n \"[SixbSqliteStorage] Webhook execution migration cannot preserve legacy runs or deliveries with unknown authority.\"\n )\n }\n db.run(webhookExecutionsSql)\n },\n { checksum: checksum(webhookExecutionsSql) }\n ),\n sqliteStep(\n \"024-ontology-commit-executions\",\n (db) => {\n if (db.query(\"SELECT 1 FROM ontology_commits LIMIT 1\").get()) {\n throw new Error(\n \"[SixbSqliteStorage] Ontology commit execution migration cannot preserve commits with unknown authority.\"\n )\n }\n db.run(ontologyCommitExecutionsSql)\n },\n { checksum: checksum(ontologyCommitExecutionsSql) }\n ),\n sqliteSql(\"025-connector-connections\", connectorConnectionsSql),\n sqliteSql(\"026-ai-cost-accounting\", aiCostAccountingSql),\n sqliteSql(\"027-agent-context-checkpoints\", agentContextCheckpointsSql),\n sqliteSql(\"028-object-override-edit-times\", objectOverrideEditTimesSql),\n sqliteSql(\"029-model-accounting\", modelAccountingSql),\n sqliteSql(\"030-ai-usage-limits\", aiUsageLimitsSql),\n sqliteSql(\"031-subagent-runs\", subagentRunsSql),\n sqliteSql(\"032-conversation-run-spec\", conversationRunSpecSql),\n sqliteSql(\"033-retire-agent-definitions\", retireAgentDefinitionsSql),\n sqliteSql(\"034-device-authorizations\", deviceAuthorizationsSql),\n sqliteSql(\"035-share-grants\", shareGrantsSql),\n sqliteSql(\"036-share-sessions\", shareSessionsSql),\n sqliteSql(\"037-execution-requester-groups\", executionRequesterGroupsSql),\n sqliteSql(\"038-projection-source-roots\", projectionSourceRootsSql),\n sqliteSql(\"039-connector-optional-pkce\", connectorOptionalPkceSql),\n sqliteSql(\"040-outbox-publication-order\", outboxPublicationOrderSql),\n sqliteSql(\"041-agent-thread-workspaces\", agentThreadWorkspacesSql),\n sqliteSql(\"042-vector-profiles\", vectorProfilesSql),\n sqliteSql(\"043-vector-indexing\", vectorIndexingSql),\n sqliteSql(\"044-vector-batching\", vectorBatchingSql),\n sqliteSql(\"045-agent-thread-sandbox-state\", agentThreadSandboxStateSql),\n sqliteSql(\"046-workflow-intervention-principals\", workflowInterventionPrincipalsSql),\n sqliteSql(\"047-ontology-commit-attribution\", ontologyCommitAttributionSql),\n sqliteSql(\"048-file-upload-sessions\", fileUploadSessionsSql),\n sqliteSql(\"049-native-sessions\", nativeSessionsSql),\n sqliteSql(\"050-directory-group-memberships\", directoryGroupMembershipsSql),\n sqliteSql(\"051-projection-run-supersession\", projectionRunSupersessionSql),\n sqliteStep(\n \"052-compact-source-storage\",\n (db) => {\n // SQLite has no procedural block to check the copy in SQL: count around it instead.\n const before = sourceStorageCounts(db)\n db.run(compactSourceStorageSql)\n const after = sourceStorageCounts(db)\n if (\n after.versions !== before.versions ||\n after.roots !== before.roots ||\n after.rows !== before.rows\n ) {\n throw new Error(\n \"[SixbSqliteStorage] Source versions, roots or rows were lost while compacting source storage.\"\n )\n }\n },\n { checksum: checksum(compactSourceStorageSql) }\n ),\n sqliteSql(\"053-replacement-plans\", replacementPlansSql),\n sqliteStep(\n \"054-slim-ontology-outbox\",\n (db) => {\n // SQLite has no procedural block to refuse the conversion in SQL: check before it.\n const mismatched = unrebuildableOutboxEvents(db)\n if (mismatched > 0) {\n throw new Error(\n `[SixbSqliteStorage] ${mismatched} outbox events would not rebuild from their commit.`\n )\n }\n db.run(slimOntologyOutboxSql)\n },\n { checksum: checksum(slimOntologyOutboxSql) }\n ),\n sqliteSql(\"055-commit-touches\", commitTouchesSql),\n sqliteSql(\"056-audio-transcription\", audioTranscriptionSql),\n sqliteSql(\"057-reranking-model-kind\", rerankingModelKindSql),\n sqliteSql(\"058-file-download-grants\", fileDownloadGrantsSql),\n sqliteSql(\"059-drained-source-versions\", drainedSourceVersionsSql),\n sqliteSql(\"060-terminal-action-runs\", terminalActionRunsSql),\n sqliteSql(\"061-drop-auth-audience\", dropAuthAudienceSql),\n sqliteSql(\"062-artifacts\", artifactsSql),\n sqliteSql(\"063-drop-output-diagnostics\", dropOutputDiagnosticsSql),\n sqliteSql(\"064-activity\", activitySql),\n sqliteSql(\"065-activity-timeline\", activityTimelineSql),\n sqliteSql(\"066-activity-interactions\", activityInteractionsSql),\n ],\n})\n\nexport function sqliteStoragePath(basePath: string): string {\n return `${basePath}/${SQLITE_STORAGE_FILE}`\n}\n\nexport function sqliteSql(id: string, sqlText: string): MigrationStep<Database> {\n return sqliteStep(\n id,\n (db) => {\n db.run(sqlText)\n },\n { checksum: checksum(sqlText) }\n )\n}\n\nexport function sqliteStep(\n id: string,\n up: (db: Database) => void | Promise<void>,\n options: MigrationStepOptions = {}\n): MigrationStep<Database> {\n return step<Database>(id, up, options)\n}\n\n// Replaying every migration costs a few hundred milliseconds, and in-memory databases are made\n// often (each test's storage, for one). The schema is built once per process and each new database\n// starts as a copy of it.\nlet freshSchema: Uint8Array | undefined\n\n/** A new in-memory database holding the current schema, as replaying every migration leaves it. */\nexport function freshSqliteDatabase(): Database {\n if (!freshSchema) {\n const template = new Database(\":memory:\")\n try {\n template.run(\"PRAGMA foreign_keys = ON\")\n installFreshSqliteSchema(template)\n freshSchema = template.serialize()\n } finally {\n template.close()\n }\n }\n return Database.deserialize(freshSchema)\n}\n\nexport function installFreshSqliteSchema(db: Database): void {\n for (const migration of sqliteStorageMigrations.steps) {\n const installed = migration.up(db)\n if (installed instanceof Promise) {\n throw new Error(\n `[${sqliteStorageMigrations.adapterId}] Fresh SQLite schema installation must be synchronous`\n )\n }\n }\n}\n\nexport function createSqliteStorageMigrators(basePath: string): readonly StorageMigrator[] {\n return [\n createSqliteMigrator({\n path: sqliteStoragePath(basePath),\n migrations: sqliteStorageMigrations,\n }),\n ]\n}\n\nexport function createSqliteMigrator(params: {\n readonly path: string\n readonly migrations: MigrationSet<Database>\n}): StorageMigrator {\n return {\n adapterId: params.migrations.adapterId,\n latestVersion: params.migrations.latestVersion,\n async status() {\n return describeMigrationHistory({\n migrations: params.migrations,\n rows: await readSqliteHistory(params.path, params.migrations.adapterId),\n })\n },\n async migrate() {\n return withSqliteDatabase(params.path, (db) =>\n runMigrationSet({\n context: db,\n migrations: params.migrations,\n state: sqliteMigrationHistoryStore(db),\n })\n )\n },\n }\n}\n\nexport async function migrateSqliteStorage(basePath: string): Promise<void> {\n mkdirSync(basePath, { recursive: true })\n\n for (const migrator of createSqliteStorageMigrators(basePath)) {\n await migrator.migrate()\n }\n}\n\nfunction sqliteMigrationHistoryStore(db: Database): MigrationHistoryStore {\n return {\n ensure() {\n db.run(MIGRATIONS_TABLE_SQL)\n },\n readHistory(adapterId) {\n return db\n .query(\"SELECT * FROM sixb_migrations WHERE adapter_id = ? ORDER BY version\")\n .all(adapterId)\n .map(rowToMigrationRecord)\n },\n markStarted(adapterId, migration, at) {\n db.query(`\n INSERT INTO sixb_migrations (\n adapter_id, version, id, checksum, status, started_at, finished_at\n ) VALUES (?, ?, ?, ?, 'started', ?, NULL)\n ON CONFLICT(adapter_id, version) DO UPDATE SET\n id = excluded.id,\n checksum = excluded.checksum,\n status = excluded.status,\n started_at = excluded.started_at,\n finished_at = NULL\n `).run(adapterId, migration.version, migration.id, migration.checksum ?? null, at)\n },\n markApplied(adapterId, migration, at) {\n db.query(`\n UPDATE sixb_migrations\n SET status = 'applied', finished_at = ?\n WHERE adapter_id = ? AND version = ?\n `).run(at, adapterId, migration.version)\n },\n async transaction(run) {\n // SQLite cannot rebuild a referenced parent table while foreign-key enforcement is active,\n // even when the replacement satisfies every deferred reference. Migrations therefore run\n // with enforcement paused, validate the complete schema before commit, then restore it.\n db.run(\"PRAGMA foreign_keys = OFF\")\n db.run(\"BEGIN\")\n\n try {\n const result = await run()\n const violations = db.query(\"PRAGMA foreign_key_check\").all()\n if (violations.length > 0) {\n throw new Error(\n `[${SQLITE_STORAGE_ADAPTER_ID}] Migration produced ${violations.length} foreign-key violation(s).`\n )\n }\n db.run(\"COMMIT\")\n return result\n } catch (error) {\n rollbackQuietly(db)\n throw error\n } finally {\n db.run(\"PRAGMA foreign_keys = ON\")\n }\n },\n }\n}\n\nfunction rowToMigrationRecord(row: unknown): MigrationRecord {\n const migration = row as {\n adapter_id: string\n version: number\n id: string\n checksum: string | null\n status: \"started\" | \"applied\"\n started_at: string\n finished_at: string | null\n }\n\n return {\n adapterId: migration.adapter_id,\n version: migration.version,\n id: migration.id,\n checksum: migration.checksum ?? undefined,\n status: migration.status,\n startedAt: migration.started_at,\n finishedAt: migration.finished_at ?? undefined,\n }\n}\n\nfunction sourceStorageCounts(db: Database): {\n readonly versions: number\n readonly roots: number\n readonly rows: number\n} {\n return db\n .query(`SELECT (SELECT count(*) FROM ontology_sources) AS versions,\n (SELECT count(*) FROM ontology_source_roots) AS roots,\n (SELECT count(*) FROM ontology_source_rows) AS rows`)\n .get() as { readonly versions: number; readonly roots: number; readonly rows: number }\n}\n\n/**\n * Stored events that would not rebuild exactly from their commit and execution. Who asked and what\n * wrote are derived from the execution exactly as 047 derived the commit's copies; both sides were\n * written as canonical JSON, so equal JSON compares as equal text.\n */\nfunction unrebuildableOutboxEvents(db: Database): number {\n const row = db\n .query(\n `SELECT COUNT(*) AS mismatched\n FROM ontology_outbox AS outbox\n LEFT JOIN ontology_commits AS commits\n ON commits.project_id = outbox.project_id AND commits.id = outbox.commit_id\n LEFT JOIN executions\n ON executions.project_id = commits.project_id AND executions.id = commits.execution_id\n WHERE executions.id IS NULL\n OR outbox.envelope ->> '$.id' IS NOT outbox.id\n OR outbox.envelope ->> '$.commitOrdinal' IS NOT outbox.commit_ordinal\n OR outbox.envelope ->> '$.commitId' IS NOT commits.id\n OR outbox.envelope ->> '$.projectId' IS NOT commits.project_id\n OR outbox.envelope ->> '$.schemaVersion' IS NOT 1\n OR outbox.envelope ->> '$.occurredAt' IS NOT commits.committed_at\n OR outbox.envelope -> '$.origin' IS NOT json(commits.origin)\n OR outbox.envelope ->> '$.correlationId' IS NOT executions.correlation_id\n OR outbox.envelope -> '$.requestedBy' IS NOT CASE\n WHEN executions.requested_by_user_id IS NOT NULL\n THEN json_object('id', executions.requested_by_user_id, 'type', 'user')\n WHEN executions.requested_by_service_account_id IS NOT NULL\n THEN json_object('id', executions.requested_by_service_account_id, 'type', 'serviceAccount')\n END\n OR outbox.envelope -> '$.executor' IS NOT CASE executions.executor_kind\n WHEN 'request' THEN json_object('requestId', executions.executor_id, 'type', 'request')\n WHEN 'agent' THEN json_object('runId', executions.executor_id, 'type', 'agent')\n WHEN 'kernel' THEN json_object(\n 'operation',\n CASE executions.authority_kernel_operation\n WHEN 'ontology.recover'\n THEN json_object('recoveryId', executions.executor_id, 'type', 'ontology.recover')\n ELSE json_object('indexingId', executions.executor_id, 'type', 'ontology.indexVectors')\n END,\n 'type', 'kernel'\n )\n ELSE json_object(\n 'id', executions.authority_primitive_id,\n 'kind', executions.executor_kind,\n 'runId', executions.executor_id,\n 'type', 'primitive'\n )\n END\n OR outbox.envelope ->> '$.topic' IS NOT CASE substr(outbox.envelope ->> '$.type', 1, 4)\n WHEN 'obje' THEN 'objects'\n WHEN 'link' THEN 'links'\n WHEN 'tele' THEN 'telemetry'\n END\n OR outbox.envelope ->> '$.partitionKey' IS NOT CASE outbox.envelope ->> '$.topic'\n WHEN 'objects' THEN (outbox.envelope ->> '$.payload.objectTypeId') || ':' ||\n (outbox.envelope ->> '$.payload.primaryId')\n WHEN 'links' THEN (outbox.envelope ->> '$.payload.sourceTypeId') || ':' ||\n (outbox.envelope ->> '$.payload.sourceId') || ':' ||\n (outbox.envelope ->> '$.payload.linkId')\n WHEN 'telemetry' THEN (outbox.envelope ->> '$.payload.objectTypeId') || ':' ||\n (outbox.envelope ->> '$.payload.objectId') || ':' ||\n (outbox.envelope ->> '$.payload.propertyId')\n END\n OR (\n outbox.envelope ->> '$.type' IN ('object.created', 'link.created')\n AND (\n (SELECT COUNT(*) FROM json_each(outbox.envelope, '$.payload.propertyChanges'))\n IS NOT (SELECT COUNT(*) FROM json_each(outbox.envelope, '$.payload.properties'))\n OR EXISTS (\n SELECT 1\n FROM json_each(outbox.envelope, '$.payload.propertyChanges') AS change\n LEFT JOIN json_each(outbox.envelope, '$.payload.properties') AS property\n ON property.key = change.key\n WHERE property.key IS NULL\n OR change.value ->> '$.operation' IS NOT 'created'\n OR json_type(change.value, '$.after') IS NOT property.type\n OR change.value ->> '$.after' IS NOT property.value\n OR (SELECT COUNT(*) FROM json_each(change.value)) IS NOT 2\n )\n )\n )`\n )\n .get() as { readonly mismatched: number }\n return row.mismatched\n}\n\nfunction checksum(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\")\n}\n\n/**\n * Reads migration history without creating anything. `null` means there is no history\n * to read, which is a state and not a failure.\n *\n * `new Database(path)` creates the file, and `withSqliteDatabase` additionally mkdirs\n * its parent — fine on the way to a migration, wrong for a probe. So: `existsSync`\n * first, then open `readonly` so even a mistake below cannot write. `:memory:` is\n * always empty on a fresh connection, so there is nothing to report.\n */\nasync function readSqliteHistory(\n path: string,\n adapterId: string\n): Promise<readonly MigrationRecord[] | null> {\n if (path === \":memory:\" || !existsSync(path)) {\n return null\n }\n\n const db = new Database(path, { readonly: true })\n try {\n const table = db\n .query(\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'sixb_migrations'\")\n .get()\n if (!table) {\n return null\n }\n\n return db\n .query(\"SELECT * FROM sixb_migrations WHERE adapter_id = ? ORDER BY version\")\n .all(adapterId)\n .map(rowToMigrationRecord)\n } finally {\n db.close()\n }\n}\n\nasync function withSqliteDatabase<T>(path: string, run: (db: Database) => Promise<T>): Promise<T> {\n if (path !== \":memory:\") mkdirSync(dirname(path), { recursive: true })\n const db = new Database(path)\n\n try {\n return await run(db)\n } finally {\n db.close()\n }\n}\n\nfunction rollbackQuietly(db: Database): void {\n try {\n db.run(\"ROLLBACK\")\n } catch {\n // Ignore rollback errors so the original migration failure is preserved.\n }\n}\n\nimport executionRequesterGroupsSql from \"./migrations/037-execution-requester-groups.sql\" with {\n type: \"text\",\n}\n\nimport connectorOptionalPkceSql from \"./migrations/039-connector-optional-pkce.sql\" with {\n type: \"text\",\n}\nimport fileUploadSessionsSql from \"./migrations/048-file-upload-sessions.sql\" with { type: \"text\" }\nimport fileDownloadGrantsSql from \"./migrations/058-file-download-grants.sql\" with { type: \"text\" }\nimport drainedSourceVersionsSql from \"./migrations/059-drained-source-versions.sql\" with {\n type: \"text\",\n}\nimport terminalActionRunsSql from \"./migrations/060-terminal-action-runs.sql\" with { type: \"text\" }\nimport dropAuthAudienceSql from \"./migrations/061-drop-auth-audience.sql\" with { type: \"text\" }\nimport artifactsSql from \"./migrations/062-artifacts.sql\" with { type: \"text\" }\nimport dropOutputDiagnosticsSql from \"./migrations/063-drop-output-diagnostics.sql\" with {\n type: \"text\",\n}\nimport activitySql from \"./migrations/064-activity.sql\" with { type: \"text\" }\nimport activityTimelineSql from \"./migrations/065-activity-timeline.sql\" with { type: \"text\" }\nimport activityInteractionsSql from \"./migrations/066-activity-interactions.sql\" with {\n type: \"text\",\n}\n",
7
+ "import type { Database } from \"bun:sqlite\"\nimport { Database as SqliteDatabase } from \"bun:sqlite\"\nimport { mkdirSync } from \"node:fs\"\nimport { dirname } from \"node:path\"\nimport { freshSqliteDatabase } from \"./migrations\"\n\nexport interface SqliteStoreConnection {\n readonly db: Database\n readonly ownsConnection: boolean\n}\n\nexport interface SqliteStoreConnectionOptions {\n readonly path?: string\n readonly connection?: SqliteStoreConnection\n readonly readonly?: boolean\n}\n\nexport function openSqliteStoreConnection(\n options: SqliteStoreConnectionOptions = {}\n): SqliteStoreConnection {\n if (options.connection) {\n return {\n db: options.connection.db,\n ownsConnection: false,\n }\n }\n\n const path = options.path ?? \":memory:\"\n if (path !== \":memory:\" && !options.readonly) mkdirSync(dirname(path), { recursive: true })\n // A file is brought up to date by its migrators; a writable in-memory database starts with the\n // whole schema.\n const db =\n path === \":memory:\" && !options.readonly\n ? freshSqliteDatabase()\n : new SqliteDatabase(path, options.readonly ? { readonly: true } : undefined)\n db.run(\"PRAGMA foreign_keys = ON\")\n db.run(\"PRAGMA busy_timeout = 5000\")\n return { db, ownsConnection: true }\n}\n\nexport function closeSqliteStoreConnection(connection: SqliteStoreConnection): void {\n if (connection.ownsConnection) {\n connection.db.close()\n }\n}\n\nconst activeImmediateTransactions = new WeakSet<Database>()\nconst activeDeferredReadTransactions = new WeakSet<Database>()\n\nexport function runImmediateTransaction<T>(db: Database, run: () => T): T {\n if (activeImmediateTransactions.has(db)) {\n return run()\n }\n\n db.run(\"BEGIN IMMEDIATE\")\n activeImmediateTransactions.add(db)\n\n try {\n const result = run()\n db.run(\"COMMIT\")\n return result\n } catch (error) {\n rollbackQuietly(db)\n throw error\n } finally {\n activeImmediateTransactions.delete(db)\n }\n}\n\n/** Lets timers and request handlers run between bounded synchronous SQLite chunks. */\nexport function yieldSqliteEventLoop(): Promise<void> {\n return new Promise((resolve) => setImmediate(resolve))\n}\n\nexport async function runImmediateTransactionAsync<T>(\n db: Database,\n run: () => Promise<T> | T\n): Promise<T> {\n if (activeImmediateTransactions.has(db)) {\n return run()\n }\n\n db.run(\"BEGIN IMMEDIATE\")\n activeImmediateTransactions.add(db)\n\n try {\n const result = await run()\n db.run(\"COMMIT\")\n return result\n } catch (error) {\n rollbackQuietly(db)\n throw error\n } finally {\n activeImmediateTransactions.delete(db)\n }\n}\n\n/**\n * Run a multi-statement read against one proven SQLite snapshot.\n *\n * A provider-owned immediate transaction already has a stable snapshot and may be reused. Any\n * other pre-existing transaction is rejected because this provider cannot prove who owns it or\n * which lifecycle will close it.\n */\nexport function runDeferredReadTransaction<T>(db: Database, run: () => T): T {\n if (activeImmediateTransactions.has(db) || activeDeferredReadTransactions.has(db)) {\n return run()\n }\n if (db.inTransaction) {\n throw new Error(\n \"[SixbSqlite] Scoped object reads cannot join an unverified SQLite transaction.\"\n )\n }\n\n db.run(\"BEGIN DEFERRED\")\n activeDeferredReadTransactions.add(db)\n try {\n const result = run()\n db.run(\"COMMIT\")\n return result\n } catch (error) {\n rollbackQuietly(db)\n throw error\n } finally {\n activeDeferredReadTransactions.delete(db)\n }\n}\n\nfunction rollbackQuietly(db: Database): void {\n try {\n db.run(\"ROLLBACK\")\n } catch {\n // Preserve the original SQLite storage failure.\n }\n}\n",
8
+ "import { Database } from \"bun:sqlite\"\nimport { createHash } from \"node:crypto\"\nimport { existsSync, mkdirSync } from \"node:fs\"\nimport { dirname } from \"node:path\"\nimport type { StorageMigrator } from \"@sixb/core\"\nimport type {\n MigrationHistoryStore,\n MigrationRecord,\n MigrationSet,\n MigrationStep,\n MigrationStepOptions,\n} from \"@sixb/core/storage\"\nimport {\n defineMigrations,\n describeMigrationHistory,\n runMigrationSet,\n step,\n} from \"@sixb/core/storage\"\nimport initialSchemaSql from \"./migrations/001-initial-schema.sql\" with { type: \"text\" }\nimport workflowRunOutputSql from \"./migrations/002-workflow-run-output.sql\" with { type: \"text\" }\nimport mergeSyncRunsSql from \"./migrations/003-merge-sync-runs.sql\" with { type: \"text\" }\nimport executionsSql from \"./migrations/004-executions.sql\" with { type: \"text\" }\nimport workflowExecutionsSql from \"./migrations/005-workflow-executions.sql\" with { type: \"text\" }\nimport narrowOntologySourceRootIndexSql from \"./migrations/006-narrow-ontology-source-root-index.sql\" with {\n type: \"text\",\n}\nimport splitOverridesSql from \"./migrations/007-split-overrides.sql\" with { type: \"text\" }\nimport actionExecutionsSql from \"./migrations/008-action-executions.sql\" with { type: \"text\" }\nimport agentExecutionsSql from \"./migrations/009-agent-executions.sql\" with { type: \"text\" }\nimport aiUsageAccountingFoundationSql from \"./migrations/010-ai-usage-accounting-foundation.sql\" with {\n type: \"text\",\n}\nimport syncFailureRecordSql from \"./migrations/011-sync-failure-record.sql\" with { type: \"text\" }\nimport pipelineFailureRecordSql from \"./migrations/012-pipeline-failure-record.sql\" with {\n type: \"text\",\n}\nimport workflowFailureRecordSql from \"./migrations/013-workflow-failure-record.sql\" with {\n type: \"text\",\n}\nimport agentFailureRecordSql from \"./migrations/014-agent-failure-record.sql\" with { type: \"text\" }\nimport projectionFailureRecordSql from \"./migrations/015-projection-failure-record.sql\" with {\n type: \"text\",\n}\nimport webhookRunFailureRecordSql from \"./migrations/016-webhook-run-failure-record.sql\" with {\n type: \"text\",\n}\nimport actionFailureRecordSql from \"./migrations/017-action-failure-record.sql\" with {\n type: \"text\",\n}\nimport ontologyOutboxFailureRecordSql from \"./migrations/018-ontology-outbox-failure-record.sql\" with {\n type: \"text\",\n}\nimport webhookDeliveryFailureRecordSql from \"./migrations/019-webhook-delivery-failure-record.sql\" with {\n type: \"text\",\n}\nimport dropRunUsageProjectionsSql from \"./migrations/020-drop-run-usage-projections.sql\" with {\n type: \"text\",\n}\nimport syncPipelineExecutionsSql from \"./migrations/021-sync-pipeline-executions.sql\" with {\n type: \"text\",\n}\nimport projectionExecutionsSql from \"./migrations/022-projection-executions.sql\" with {\n type: \"text\",\n}\nimport webhookExecutionsSql from \"./migrations/023-webhook-executions.sql\" with { type: \"text\" }\nimport ontologyCommitExecutionsSql from \"./migrations/024-ontology-commit-executions.sql\" with {\n type: \"text\",\n}\nimport connectorConnectionsSql from \"./migrations/025-connector-connections.sql\" with {\n type: \"text\",\n}\nimport aiCostAccountingSql from \"./migrations/026-ai-cost-accounting.sql\" with { type: \"text\" }\nimport agentContextCheckpointsSql from \"./migrations/027-agent-context-checkpoints.sql\" with {\n type: \"text\",\n}\nimport objectOverrideEditTimesSql from \"./migrations/028-object-override-edit-times.sql\" with {\n type: \"text\",\n}\nimport modelAccountingSql from \"./migrations/029-model-accounting.sql\" with { type: \"text\" }\nimport aiUsageLimitsSql from \"./migrations/030-ai-usage-limits.sql\" with { type: \"text\" }\nimport subagentRunsSql from \"./migrations/031-subagent-runs.sql\" with { type: \"text\" }\nimport conversationRunSpecSql from \"./migrations/032-conversation-run-spec.sql\" with {\n type: \"text\",\n}\nimport retireAgentDefinitionsSql from \"./migrations/033-retire-agent-definitions.sql\" with {\n type: \"text\",\n}\nimport deviceAuthorizationsSql from \"./migrations/034-device-authorizations.sql\" with {\n type: \"text\",\n}\nimport shareGrantsSql from \"./migrations/035-share-grants.sql\" with { type: \"text\" }\nimport shareSessionsSql from \"./migrations/036-share-sessions.sql\" with { type: \"text\" }\nimport projectionSourceRootsSql from \"./migrations/038-projection-source-roots.sql\" with {\n type: \"text\",\n}\nimport outboxPublicationOrderSql from \"./migrations/040-outbox-publication-order.sql\" with {\n type: \"text\",\n}\nimport agentThreadWorkspacesSql from \"./migrations/041-agent-thread-workspaces.sql\" with {\n type: \"text\",\n}\nimport vectorProfilesSql from \"./migrations/042-vector-profiles.sql\" with { type: \"text\" }\nimport vectorIndexingSql from \"./migrations/043-vector-indexing.sql\" with { type: \"text\" }\nimport vectorBatchingSql from \"./migrations/044-vector-batching.sql\" with { type: \"text\" }\nimport agentThreadSandboxStateSql from \"./migrations/045-agent-thread-sandbox-state.sql\" with {\n type: \"text\",\n}\nimport workflowInterventionPrincipalsSql from \"./migrations/046-workflow-intervention-principals.sql\" with {\n type: \"text\",\n}\nimport ontologyCommitAttributionSql from \"./migrations/047-ontology-commit-attribution.sql\" with {\n type: \"text\",\n}\nimport nativeSessionsSql from \"./migrations/049-native-sessions.sql\" with { type: \"text\" }\nimport directoryGroupMembershipsSql from \"./migrations/050-directory-group-memberships.sql\" with {\n type: \"text\",\n}\nimport projectionRunSupersessionSql from \"./migrations/051-projection-run-supersession.sql\" with {\n type: \"text\",\n}\nimport compactSourceStorageSql from \"./migrations/052-compact-source-storage.sql\" with {\n type: \"text\",\n}\nimport replacementPlansSql from \"./migrations/053-replacement-plans.sql\" with { type: \"text\" }\nimport slimOntologyOutboxSql from \"./migrations/054-slim-ontology-outbox.sql\" with { type: \"text\" }\nimport commitTouchesSql from \"./migrations/055-commit-touches.sql\" with { type: \"text\" }\nimport audioTranscriptionSql from \"./migrations/056-audio-transcription.sql\" with { type: \"text\" }\nimport rerankingModelKindSql from \"./migrations/057-reranking-model-kind.sql\" with { type: \"text\" }\n\nconst MIGRATIONS_TABLE_SQL = `\n CREATE TABLE IF NOT EXISTS sixb_migrations (\n adapter_id TEXT NOT NULL,\n version INTEGER NOT NULL,\n id TEXT NOT NULL,\n checksum TEXT,\n status TEXT NOT NULL,\n started_at TEXT NOT NULL,\n finished_at TEXT,\n PRIMARY KEY (adapter_id, version)\n );\n`\n\nexport const SQLITE_STORAGE_ADAPTER_ID = \"SixbSqliteStorage\"\nexport const SQLITE_STORAGE_FILE = \"storage.sqlite\"\n\nexport const sqliteStorageMigrations = defineMigrations({\n adapterId: SQLITE_STORAGE_ADAPTER_ID,\n steps: [\n sqliteSql(\"001-initial-schema\", initialSchemaSql),\n sqliteSql(\"002-workflow-run-output\", workflowRunOutputSql),\n sqliteSql(\"003-merge-sync-runs\", mergeSyncRunsSql),\n sqliteSql(\"004-executions\", executionsSql),\n sqliteSql(\"005-workflow-executions\", workflowExecutionsSql),\n sqliteSql(\"006-narrow-ontology-source-root-index\", narrowOntologySourceRootIndexSql),\n sqliteSql(\"007-split-overrides\", splitOverridesSql),\n sqliteSql(\"008-action-executions\", actionExecutionsSql),\n sqliteSql(\"009-agent-executions\", agentExecutionsSql),\n sqliteSql(\"010-ai-usage-accounting-foundation\", aiUsageAccountingFoundationSql),\n sqliteSql(\"011-sync-failure-record\", syncFailureRecordSql),\n sqliteSql(\"012-pipeline-failure-record\", pipelineFailureRecordSql),\n sqliteSql(\"013-workflow-failure-record\", workflowFailureRecordSql),\n sqliteSql(\"014-agent-failure-record\", agentFailureRecordSql),\n sqliteSql(\"015-projection-failure-record\", projectionFailureRecordSql),\n sqliteSql(\"016-webhook-run-failure-record\", webhookRunFailureRecordSql),\n sqliteSql(\"017-action-failure-record\", actionFailureRecordSql),\n sqliteSql(\"018-ontology-outbox-failure-record\", ontologyOutboxFailureRecordSql),\n sqliteSql(\"019-webhook-delivery-failure-record\", webhookDeliveryFailureRecordSql),\n sqliteSql(\"020-drop-run-usage-projections\", dropRunUsageProjectionsSql),\n sqliteSql(\"021-sync-pipeline-executions\", syncPipelineExecutionsSql),\n sqliteStep(\n \"022-projection-executions\",\n (db) => {\n if (db.query(\"SELECT 1 FROM projection_runs LIMIT 1\").get()) {\n throw new Error(\n \"[SixbSqliteStorage] Projection execution migration cannot preserve legacy runs with unknown authority.\"\n )\n }\n db.run(projectionExecutionsSql)\n },\n { checksum: checksum(projectionExecutionsSql) }\n ),\n sqliteStep(\n \"023-webhook-executions\",\n (db) => {\n const hasRuns = db.query(\"SELECT 1 FROM webhook_runs LIMIT 1\").get()\n const hasDeliveries = db.query(\"SELECT 1 FROM webhook_deliveries LIMIT 1\").get()\n if (hasRuns || hasDeliveries) {\n throw new Error(\n \"[SixbSqliteStorage] Webhook execution migration cannot preserve legacy runs or deliveries with unknown authority.\"\n )\n }\n db.run(webhookExecutionsSql)\n },\n { checksum: checksum(webhookExecutionsSql) }\n ),\n sqliteStep(\n \"024-ontology-commit-executions\",\n (db) => {\n if (db.query(\"SELECT 1 FROM ontology_commits LIMIT 1\").get()) {\n throw new Error(\n \"[SixbSqliteStorage] Ontology commit execution migration cannot preserve commits with unknown authority.\"\n )\n }\n db.run(ontologyCommitExecutionsSql)\n },\n { checksum: checksum(ontologyCommitExecutionsSql) }\n ),\n sqliteSql(\"025-connector-connections\", connectorConnectionsSql),\n sqliteSql(\"026-ai-cost-accounting\", aiCostAccountingSql),\n sqliteSql(\"027-agent-context-checkpoints\", agentContextCheckpointsSql),\n sqliteSql(\"028-object-override-edit-times\", objectOverrideEditTimesSql),\n sqliteSql(\"029-model-accounting\", modelAccountingSql),\n sqliteSql(\"030-ai-usage-limits\", aiUsageLimitsSql),\n sqliteSql(\"031-subagent-runs\", subagentRunsSql),\n sqliteSql(\"032-conversation-run-spec\", conversationRunSpecSql),\n sqliteSql(\"033-retire-agent-definitions\", retireAgentDefinitionsSql),\n sqliteSql(\"034-device-authorizations\", deviceAuthorizationsSql),\n sqliteSql(\"035-share-grants\", shareGrantsSql),\n sqliteSql(\"036-share-sessions\", shareSessionsSql),\n sqliteSql(\"037-execution-requester-groups\", executionRequesterGroupsSql),\n sqliteSql(\"038-projection-source-roots\", projectionSourceRootsSql),\n sqliteSql(\"039-connector-optional-pkce\", connectorOptionalPkceSql),\n sqliteSql(\"040-outbox-publication-order\", outboxPublicationOrderSql),\n sqliteSql(\"041-agent-thread-workspaces\", agentThreadWorkspacesSql),\n sqliteSql(\"042-vector-profiles\", vectorProfilesSql),\n sqliteSql(\"043-vector-indexing\", vectorIndexingSql),\n sqliteSql(\"044-vector-batching\", vectorBatchingSql),\n sqliteSql(\"045-agent-thread-sandbox-state\", agentThreadSandboxStateSql),\n sqliteSql(\"046-workflow-intervention-principals\", workflowInterventionPrincipalsSql),\n sqliteSql(\"047-ontology-commit-attribution\", ontologyCommitAttributionSql),\n sqliteSql(\"048-file-upload-sessions\", fileUploadSessionsSql),\n sqliteSql(\"049-native-sessions\", nativeSessionsSql),\n sqliteSql(\"050-directory-group-memberships\", directoryGroupMembershipsSql),\n sqliteSql(\"051-projection-run-supersession\", projectionRunSupersessionSql),\n sqliteStep(\n \"052-compact-source-storage\",\n (db) => {\n // SQLite has no procedural block to check the copy in SQL: count around it instead.\n const before = sourceStorageCounts(db)\n db.run(compactSourceStorageSql)\n const after = sourceStorageCounts(db)\n if (\n after.versions !== before.versions ||\n after.roots !== before.roots ||\n after.rows !== before.rows\n ) {\n throw new Error(\n \"[SixbSqliteStorage] Source versions, roots or rows were lost while compacting source storage.\"\n )\n }\n },\n { checksum: checksum(compactSourceStorageSql) }\n ),\n sqliteSql(\"053-replacement-plans\", replacementPlansSql),\n sqliteStep(\n \"054-slim-ontology-outbox\",\n (db) => {\n // SQLite has no procedural block to refuse the conversion in SQL: check before it.\n const mismatched = unrebuildableOutboxEvents(db)\n if (mismatched > 0) {\n throw new Error(\n `[SixbSqliteStorage] ${mismatched} outbox events would not rebuild from their commit.`\n )\n }\n db.run(slimOntologyOutboxSql)\n },\n { checksum: checksum(slimOntologyOutboxSql) }\n ),\n sqliteSql(\"055-commit-touches\", commitTouchesSql),\n sqliteSql(\"056-audio-transcription\", audioTranscriptionSql),\n sqliteSql(\"057-reranking-model-kind\", rerankingModelKindSql),\n sqliteSql(\"058-file-download-grants\", fileDownloadGrantsSql),\n sqliteSql(\"059-drained-source-versions\", drainedSourceVersionsSql),\n sqliteSql(\"060-terminal-action-runs\", terminalActionRunsSql),\n sqliteSql(\"061-drop-auth-audience\", dropAuthAudienceSql),\n sqliteSql(\"062-artifacts\", artifactsSql),\n sqliteSql(\"063-drop-output-diagnostics\", dropOutputDiagnosticsSql),\n sqliteSql(\"064-activity\", activitySql),\n sqliteSql(\"065-activity-timeline\", activityTimelineSql),\n sqliteSql(\"066-activity-interactions\", activityInteractionsSql),\n sqliteSql(\"067-artifact-kinds\", artifactKindsSql),\n sqliteSql(\"068-artifact-state\", artifactStateSql),\n sqliteSql(\"069-agent-thread-participants\", agentThreadParticipantsSql),\n sqliteSql(\"070-forked-context-checkpoints\", forkedContextCheckpointsSql),\n sqliteSql(\"071-unique-values\", uniqueValuesSql),\n sqliteSql(\"072-generated-media-usage\", generatedMediaUsageSql),\n sqliteSql(\"073-model-call-files\", modelCallFilesSql),\n sqliteSql(\"074-agent-memory\", agentMemorySql),\n sqliteSql(\"075-artifact-threads\", artifactThreadsSql),\n sqliteSql(\"076-agent-approvals\", agentApprovalsSql),\n sqliteSql(\"077-agent-approval-resume\", agentApprovalResumeSql),\n sqliteStep(\n \"078-subagent-threads\",\n (db) => {\n // Bun runs a script past a statement that fails and reports only the last one's error, so\n // a refused copy would go unnoticed and the rebuild would drop the rows: count around it.\n const before = subagentThreadCounts(db)\n db.run(subagentThreadsSql)\n const after = subagentThreadCounts(db)\n if (\n after.runs !== before.runs ||\n after.threads !== before.threads + before.threadless ||\n after.messages !== before.messages + before.threadless ||\n after.threadless !== 0\n ) {\n throw new Error(\n \"[SixbSqliteStorage] Agent runs, threads or messages were lost while giving sub-agents their threads.\"\n )\n }\n },\n { checksum: checksum(subagentThreadsSql) }\n ),\n sqliteSql(\"079-subagent-questions\", subagentQuestionsSql),\n ],\n})\n\nexport function sqliteStoragePath(basePath: string): string {\n return `${basePath}/${SQLITE_STORAGE_FILE}`\n}\n\nexport function sqliteSql(id: string, sqlText: string): MigrationStep<Database> {\n return sqliteStep(\n id,\n (db) => {\n db.run(sqlText)\n },\n { checksum: checksum(sqlText) }\n )\n}\n\nexport function sqliteStep(\n id: string,\n up: (db: Database) => void | Promise<void>,\n options: MigrationStepOptions = {}\n): MigrationStep<Database> {\n return step<Database>(id, up, options)\n}\n\n// Replaying every migration costs a few hundred milliseconds, and in-memory databases are made\n// often (each test's storage, for one). The schema is built once per process and each new database\n// starts as a copy of it.\nlet freshSchema: Uint8Array | undefined\n\n/** A new in-memory database holding the current schema, as replaying every migration leaves it. */\nexport function freshSqliteDatabase(): Database {\n if (!freshSchema) {\n const template = new Database(\":memory:\")\n try {\n template.run(\"PRAGMA foreign_keys = ON\")\n installFreshSqliteSchema(template)\n freshSchema = template.serialize()\n } finally {\n template.close()\n }\n }\n return Database.deserialize(freshSchema)\n}\n\nfunction installFreshSqliteSchema(db: Database): void {\n for (const migration of sqliteStorageMigrations.steps) {\n const installed = migration.up(db)\n if (installed instanceof Promise) {\n throw new Error(\n `[${sqliteStorageMigrations.adapterId}] Fresh SQLite schema installation must be synchronous`\n )\n }\n }\n}\n\nexport function createSqliteStorageMigrators(basePath: string): readonly StorageMigrator[] {\n return [\n createSqliteMigrator({\n path: sqliteStoragePath(basePath),\n migrations: sqliteStorageMigrations,\n }),\n ]\n}\n\nexport function createSqliteMigrator(params: {\n readonly path: string\n readonly migrations: MigrationSet<Database>\n}): StorageMigrator {\n return {\n adapterId: params.migrations.adapterId,\n latestVersion: params.migrations.latestVersion,\n async status() {\n return describeMigrationHistory({\n migrations: params.migrations,\n rows: await readSqliteHistory(params.path, params.migrations.adapterId),\n })\n },\n async migrate() {\n return withSqliteDatabase(params.path, (db) =>\n runMigrationSet({\n context: db,\n migrations: params.migrations,\n state: sqliteMigrationHistoryStore(db),\n })\n )\n },\n }\n}\n\nexport async function migrateSqliteStorage(basePath: string): Promise<void> {\n mkdirSync(basePath, { recursive: true })\n\n for (const migrator of createSqliteStorageMigrators(basePath)) {\n await migrator.migrate()\n }\n}\n\nfunction sqliteMigrationHistoryStore(db: Database): MigrationHistoryStore {\n return {\n ensure() {\n db.run(MIGRATIONS_TABLE_SQL)\n },\n readHistory(adapterId) {\n return db\n .query(\"SELECT * FROM sixb_migrations WHERE adapter_id = ? ORDER BY version\")\n .all(adapterId)\n .map(rowToMigrationRecord)\n },\n markStarted(adapterId, migration, at) {\n db.query(`\n INSERT INTO sixb_migrations (\n adapter_id, version, id, checksum, status, started_at, finished_at\n ) VALUES (?, ?, ?, ?, 'started', ?, NULL)\n ON CONFLICT(adapter_id, version) DO UPDATE SET\n id = excluded.id,\n checksum = excluded.checksum,\n status = excluded.status,\n started_at = excluded.started_at,\n finished_at = NULL\n `).run(adapterId, migration.version, migration.id, migration.checksum ?? null, at)\n },\n markApplied(adapterId, migration, at) {\n db.query(`\n UPDATE sixb_migrations\n SET status = 'applied', finished_at = ?\n WHERE adapter_id = ? AND version = ?\n `).run(at, adapterId, migration.version)\n },\n async transaction(run) {\n // SQLite cannot rebuild a referenced parent table while foreign-key enforcement is active,\n // even when the replacement satisfies every deferred reference. Migrations therefore run\n // with enforcement paused, validate the complete schema before commit, then restore it.\n db.run(\"PRAGMA foreign_keys = OFF\")\n db.run(\"BEGIN\")\n\n try {\n const result = await run()\n const violations = db.query(\"PRAGMA foreign_key_check\").all()\n if (violations.length > 0) {\n throw new Error(\n `[${SQLITE_STORAGE_ADAPTER_ID}] Migration produced ${violations.length} foreign-key violation(s).`\n )\n }\n db.run(\"COMMIT\")\n return result\n } catch (error) {\n rollbackQuietly(db)\n throw error\n } finally {\n db.run(\"PRAGMA foreign_keys = ON\")\n }\n },\n }\n}\n\nfunction rowToMigrationRecord(row: unknown): MigrationRecord {\n const migration = row as {\n adapter_id: string\n version: number\n id: string\n checksum: string | null\n status: \"started\" | \"applied\"\n started_at: string\n finished_at: string | null\n }\n\n return {\n adapterId: migration.adapter_id,\n version: migration.version,\n id: migration.id,\n checksum: migration.checksum ?? undefined,\n status: migration.status,\n startedAt: migration.started_at,\n finishedAt: migration.finished_at ?? undefined,\n }\n}\n\nfunction sourceStorageCounts(db: Database): {\n readonly versions: number\n readonly roots: number\n readonly rows: number\n} {\n return db\n .query(`SELECT (SELECT count(*) FROM ontology_sources) AS versions,\n (SELECT count(*) FROM ontology_source_roots) AS roots,\n (SELECT count(*) FROM ontology_source_rows) AS rows`)\n .get() as { readonly versions: number; readonly roots: number; readonly rows: number }\n}\n\nfunction subagentThreadCounts(db: Database): {\n readonly runs: number\n readonly threads: number\n readonly messages: number\n /** Child runs without a thread. */\n readonly threadless: number\n} {\n return db\n .query(`SELECT (SELECT count(*) FROM agent_runs) AS runs,\n (SELECT count(*) FROM agent_threads) AS threads,\n (SELECT count(*) FROM agent_messages) AS messages,\n (SELECT count(*) FROM agent_runs WHERE kind = 'subagent' AND thread_id IS NULL) AS threadless`)\n .get() as {\n readonly runs: number\n readonly threads: number\n readonly messages: number\n readonly threadless: number\n }\n}\n\n/**\n * Stored events that would not rebuild exactly from their commit and execution. Who asked and what\n * wrote are derived from the execution exactly as 047 derived the commit's copies; both sides were\n * written as canonical JSON, so equal JSON compares as equal text.\n */\nfunction unrebuildableOutboxEvents(db: Database): number {\n const row = db\n .query(\n `SELECT COUNT(*) AS mismatched\n FROM ontology_outbox AS outbox\n LEFT JOIN ontology_commits AS commits\n ON commits.project_id = outbox.project_id AND commits.id = outbox.commit_id\n LEFT JOIN executions\n ON executions.project_id = commits.project_id AND executions.id = commits.execution_id\n WHERE executions.id IS NULL\n OR outbox.envelope ->> '$.id' IS NOT outbox.id\n OR outbox.envelope ->> '$.commitOrdinal' IS NOT outbox.commit_ordinal\n OR outbox.envelope ->> '$.commitId' IS NOT commits.id\n OR outbox.envelope ->> '$.projectId' IS NOT commits.project_id\n OR outbox.envelope ->> '$.schemaVersion' IS NOT 1\n OR outbox.envelope ->> '$.occurredAt' IS NOT commits.committed_at\n OR outbox.envelope -> '$.origin' IS NOT json(commits.origin)\n OR outbox.envelope ->> '$.correlationId' IS NOT executions.correlation_id\n OR outbox.envelope -> '$.requestedBy' IS NOT CASE\n WHEN executions.requested_by_user_id IS NOT NULL\n THEN json_object('id', executions.requested_by_user_id, 'type', 'user')\n WHEN executions.requested_by_service_account_id IS NOT NULL\n THEN json_object('id', executions.requested_by_service_account_id, 'type', 'serviceAccount')\n END\n OR outbox.envelope -> '$.executor' IS NOT CASE executions.executor_kind\n WHEN 'request' THEN json_object('requestId', executions.executor_id, 'type', 'request')\n WHEN 'agent' THEN json_object('runId', executions.executor_id, 'type', 'agent')\n WHEN 'kernel' THEN json_object(\n 'operation',\n CASE executions.authority_kernel_operation\n WHEN 'ontology.recover'\n THEN json_object('recoveryId', executions.executor_id, 'type', 'ontology.recover')\n ELSE json_object('indexingId', executions.executor_id, 'type', 'ontology.indexVectors')\n END,\n 'type', 'kernel'\n )\n ELSE json_object(\n 'id', executions.authority_primitive_id,\n 'kind', executions.executor_kind,\n 'runId', executions.executor_id,\n 'type', 'primitive'\n )\n END\n OR outbox.envelope ->> '$.topic' IS NOT CASE substr(outbox.envelope ->> '$.type', 1, 4)\n WHEN 'obje' THEN 'objects'\n WHEN 'link' THEN 'links'\n WHEN 'tele' THEN 'telemetry'\n END\n OR outbox.envelope ->> '$.partitionKey' IS NOT CASE outbox.envelope ->> '$.topic'\n WHEN 'objects' THEN (outbox.envelope ->> '$.payload.objectTypeId') || ':' ||\n (outbox.envelope ->> '$.payload.primaryId')\n WHEN 'links' THEN (outbox.envelope ->> '$.payload.sourceTypeId') || ':' ||\n (outbox.envelope ->> '$.payload.sourceId') || ':' ||\n (outbox.envelope ->> '$.payload.linkId')\n WHEN 'telemetry' THEN (outbox.envelope ->> '$.payload.objectTypeId') || ':' ||\n (outbox.envelope ->> '$.payload.objectId') || ':' ||\n (outbox.envelope ->> '$.payload.propertyId')\n END\n OR (\n outbox.envelope ->> '$.type' IN ('object.created', 'link.created')\n AND (\n (SELECT COUNT(*) FROM json_each(outbox.envelope, '$.payload.propertyChanges'))\n IS NOT (SELECT COUNT(*) FROM json_each(outbox.envelope, '$.payload.properties'))\n OR EXISTS (\n SELECT 1\n FROM json_each(outbox.envelope, '$.payload.propertyChanges') AS change\n LEFT JOIN json_each(outbox.envelope, '$.payload.properties') AS property\n ON property.key = change.key\n WHERE property.key IS NULL\n OR change.value ->> '$.operation' IS NOT 'created'\n OR json_type(change.value, '$.after') IS NOT property.type\n OR change.value ->> '$.after' IS NOT property.value\n OR (SELECT COUNT(*) FROM json_each(change.value)) IS NOT 2\n )\n )\n )`\n )\n .get() as { readonly mismatched: number }\n return row.mismatched\n}\n\nfunction checksum(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\")\n}\n\n/**\n * Reads migration history without creating anything. `null` means there is no history\n * to read, which is a state and not a failure.\n *\n * `new Database(path)` creates the file, and `withSqliteDatabase` additionally mkdirs\n * its parent — fine on the way to a migration, wrong for a probe. So: `existsSync`\n * first, then open `readonly` so even a mistake below cannot write. `:memory:` is\n * always empty on a fresh connection, so there is nothing to report.\n */\nasync function readSqliteHistory(\n path: string,\n adapterId: string\n): Promise<readonly MigrationRecord[] | null> {\n if (path === \":memory:\" || !existsSync(path)) {\n return null\n }\n\n const db = new Database(path, { readonly: true })\n try {\n const table = db\n .query(\"SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'sixb_migrations'\")\n .get()\n if (!table) {\n return null\n }\n\n return db\n .query(\"SELECT * FROM sixb_migrations WHERE adapter_id = ? ORDER BY version\")\n .all(adapterId)\n .map(rowToMigrationRecord)\n } finally {\n db.close()\n }\n}\n\nasync function withSqliteDatabase<T>(path: string, run: (db: Database) => Promise<T>): Promise<T> {\n if (path !== \":memory:\") mkdirSync(dirname(path), { recursive: true })\n const db = new Database(path)\n\n try {\n return await run(db)\n } finally {\n db.close()\n }\n}\n\nfunction rollbackQuietly(db: Database): void {\n try {\n db.run(\"ROLLBACK\")\n } catch {\n // Ignore rollback errors so the original migration failure is preserved.\n }\n}\n\nimport executionRequesterGroupsSql from \"./migrations/037-execution-requester-groups.sql\" with {\n type: \"text\",\n}\n\nimport connectorOptionalPkceSql from \"./migrations/039-connector-optional-pkce.sql\" with {\n type: \"text\",\n}\nimport fileUploadSessionsSql from \"./migrations/048-file-upload-sessions.sql\" with { type: \"text\" }\nimport fileDownloadGrantsSql from \"./migrations/058-file-download-grants.sql\" with { type: \"text\" }\nimport drainedSourceVersionsSql from \"./migrations/059-drained-source-versions.sql\" with {\n type: \"text\",\n}\nimport terminalActionRunsSql from \"./migrations/060-terminal-action-runs.sql\" with { type: \"text\" }\nimport dropAuthAudienceSql from \"./migrations/061-drop-auth-audience.sql\" with { type: \"text\" }\nimport artifactsSql from \"./migrations/062-artifacts.sql\" with { type: \"text\" }\nimport dropOutputDiagnosticsSql from \"./migrations/063-drop-output-diagnostics.sql\" with {\n type: \"text\",\n}\nimport activitySql from \"./migrations/064-activity.sql\" with { type: \"text\" }\nimport activityTimelineSql from \"./migrations/065-activity-timeline.sql\" with { type: \"text\" }\nimport activityInteractionsSql from \"./migrations/066-activity-interactions.sql\" with {\n type: \"text\",\n}\nimport artifactKindsSql from \"./migrations/067-artifact-kinds.sql\" with { type: \"text\" }\nimport artifactStateSql from \"./migrations/068-artifact-state.sql\" with { type: \"text\" }\nimport agentThreadParticipantsSql from \"./migrations/069-agent-thread-participants.sql\" with {\n type: \"text\",\n}\nimport forkedContextCheckpointsSql from \"./migrations/070-forked-context-checkpoints.sql\" with {\n type: \"text\",\n}\nimport uniqueValuesSql from \"./migrations/071-unique-values.sql\" with { type: \"text\" }\nimport generatedMediaUsageSql from \"./migrations/072-generated-media-usage.sql\" with {\n type: \"text\",\n}\nimport modelCallFilesSql from \"./migrations/073-model-call-files.sql\" with { type: \"text\" }\nimport agentMemorySql from \"./migrations/074-agent-memory.sql\" with { type: \"text\" }\nimport artifactThreadsSql from \"./migrations/075-artifact-threads.sql\" with { type: \"text\" }\nimport agentApprovalsSql from \"./migrations/076-agent-approvals.sql\" with { type: \"text\" }\nimport agentApprovalResumeSql from \"./migrations/077-agent-approval-resume.sql\" with {\n type: \"text\",\n}\nimport subagentThreadsSql from \"./migrations/078-subagent-threads.sql\" with { type: \"text\" }\nimport subagentQuestionsSql from \"./migrations/079-subagent-questions.sql\" with { type: \"text\" }\n",
9
9
  "import type { Database, SQLQueryBindings } from \"bun:sqlite\"\nimport {\n ACTIVITY_MAX_VISIT_MS,\n type ActivitySourceState,\n activityActor,\n activityCalendarDays,\n parseActivityAttribution,\n planActivityAppend,\n type StoredActivityEvent,\n serializeActivityAttribution,\n validateActivityAppend,\n} from \"@sixb/core/internal/storage\"\nimport type {\n ActivityCalendarInput,\n ActivityCursor,\n ActivityDay,\n ActivityInteraction,\n ActivityPageView,\n ActivityPeriodInput,\n ActivitySessionVisits,\n ActivityStorage,\n ActivitySummary,\n ActivityUsersPage,\n ActivityVisit,\n ActivityVisitsPage,\n AppendActivityInput,\n AppendActivityResult,\n ListActivitySessionVisitsInput,\n ListActivityUsersInput,\n ListActivityVisitsInput,\n ReadActivityVisitInput,\n StoredActivityVisitPage,\n} from \"@sixb/core/storage\"\nimport { runImmediateTransaction, type SqliteStoreConnection } from \"./transactions\"\n\nconst VISIT_COLUMNS = `\n v.id, v.actor_type, v.user_id, v.grant_id, v.started_at, v.last_seen_at, v.page_views,\n v.interactions, v.attribution\n`\n\n// Sorts after every stored timestamp, so a first page starts from the newest row.\nconst NO_CURSOR = { at: \"9999-12-31T23:59:59.999Z\", id: \"\" }\n\n/** SQLite activity. The immediate transaction is the source lock; the policy decides the rest. */\nexport class SqliteActivityStorage implements ActivityStorage {\n private readonly db: Database\n\n constructor(connection: SqliteStoreConnection) {\n this.db = connection.db\n }\n\n async append(input: AppendActivityInput): Promise<AppendActivityResult> {\n validateActivityAppend(input)\n\n return runImmediateTransaction(this.db, () => {\n const plan = planActivityAppend(input, this.source(input), this.storedEvents(input))\n if (plan.status !== \"append\") {\n return { status: plan.status === \"duplicate\" ? \"accepted\" : \"throttled\", accepted: 0 }\n }\n\n const { state } = plan\n const lastSeenAt = iso(state.lastSeenAt)\n\n if (plan.newVisit) {\n this.run(\n `\n INSERT INTO activity_visits (\n project_id, id, actor_type, user_id, grant_id, session_id,\n started_at, last_seen_at, page_views, interactions, attribution\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `,\n input.projectId,\n state.visitId,\n input.actor.type,\n input.actor.type === \"user\" ? input.actor.userId : null,\n input.actor.type === \"share\" ? input.actor.grantId : null,\n input.sessionId,\n lastSeenAt,\n lastSeenAt,\n plan.pageViews.length,\n plan.interactions.length,\n plan.newVisit.attribution === null\n ? null\n : serializeActivityAttribution(plan.newVisit.attribution)\n )\n } else {\n this.run(\n `\n UPDATE activity_visits\n SET\n last_seen_at = ?,\n page_views = page_views + ?,\n interactions = interactions + ?\n WHERE project_id = ? AND id = ?\n `,\n lastSeenAt,\n plan.pageViews.length,\n plan.interactions.length,\n input.projectId,\n state.visitId\n )\n }\n\n for (const pageView of plan.pageViews) {\n this.run(\n `\n INSERT INTO activity_page_views (\n project_id, visit_id, sequence, id, route, received_at, attribution\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n `,\n input.projectId,\n pageView.visitId,\n pageView.sequence,\n pageView.id,\n pageView.route,\n pageView.receivedAt.toISOString(),\n serializeActivityAttribution(pageView.attribution)\n )\n }\n\n for (const interaction of plan.interactions) {\n this.run(\n `\n INSERT INTO activity_interactions (\n project_id, visit_id, sequence, id, name, route, received_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n `,\n input.projectId,\n interaction.visitId,\n interaction.sequence,\n interaction.id,\n interaction.name,\n interaction.route,\n interaction.receivedAt.toISOString()\n )\n }\n\n this.run(\n `\n INSERT INTO activity_sources (\n project_id, actor_type, session_id, visit_id, last_seen_at, sequence,\n window_start, window_count\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (project_id, actor_type, session_id) DO UPDATE SET\n visit_id = excluded.visit_id,\n last_seen_at = excluded.last_seen_at,\n sequence = excluded.sequence,\n window_start = excluded.window_start,\n window_count = excluded.window_count\n `,\n input.projectId,\n input.actor.type,\n input.sessionId,\n state.visitId,\n lastSeenAt,\n state.sequence,\n iso(state.windowStart),\n state.windowCount\n )\n\n return { status: \"accepted\", accepted: plan.accepted }\n })\n }\n\n async list(input: ListActivityVisitsInput): Promise<ActivityVisitsPage> {\n const period = overlapping(input)\n const before = cursorOf(input.before)\n const rows = this.all<VisitRow>(\n `\n SELECT ${VISIT_COLUMNS}\n FROM activity_visits v\n WHERE ${period.where}\n AND (v.last_seen_at < ? OR (v.last_seen_at = ? AND v.id < ?))\n ORDER BY v.last_seen_at DESC, v.id DESC\n LIMIT ?\n `,\n ...period.params,\n before.at,\n before.at,\n before.id,\n input.limit + 1\n )\n\n return {\n visits: rows.slice(0, input.limit).map(visitFromRow),\n hasMore: rows.length > input.limit,\n }\n }\n\n async users(input: ListActivityUsersInput): Promise<ActivityUsersPage> {\n const period = overlapping(input)\n const before = cursorOf(input.before)\n const rows = this.all<UserRow>(\n `\n SELECT\n v.user_id,\n MAX(v.last_seen_at) AS last_seen_at,\n COUNT(DISTINCT v.id) AS visits,\n COUNT(p.id) AS page_views\n FROM activity_visits v\n LEFT JOIN activity_page_views p\n ON p.project_id = v.project_id\n AND p.visit_id = v.id\n AND p.received_at >= ?\n AND p.received_at < ?\n WHERE ${period.where} AND v.actor_type = 'user'\n GROUP BY v.user_id\n HAVING MAX(v.last_seen_at) < ? OR (MAX(v.last_seen_at) = ? AND v.user_id < ?)\n ORDER BY last_seen_at DESC, v.user_id DESC\n LIMIT ?\n `,\n input.from.toISOString(),\n input.to.toISOString(),\n ...period.params,\n before.at,\n before.at,\n before.id,\n input.limit + 1\n )\n\n return {\n users: rows.slice(0, input.limit).map((row) => ({\n userId: row.user_id,\n lastSeenAt: new Date(row.last_seen_at),\n visits: Number(row.visits),\n pageViews: Number(row.page_views),\n })),\n hasMore: rows.length > input.limit,\n }\n }\n\n async summarize(input: ActivityPeriodInput): Promise<ActivitySummary> {\n const period = overlapping(input)\n const [row] = this.all<SummaryRow>(\n `\n SELECT\n COUNT(DISTINCT v.user_id) AS users,\n COUNT(DISTINCT v.id) AS visits,\n COUNT(DISTINCT CASE WHEN v.actor_type = 'share' THEN v.id END) AS shared_visits,\n COUNT(p.id) AS page_views\n FROM activity_visits v\n LEFT JOIN activity_page_views p\n ON p.project_id = v.project_id\n AND p.visit_id = v.id\n AND p.received_at >= ?\n AND p.received_at < ?\n WHERE ${period.where}\n `,\n input.from.toISOString(),\n input.to.toISOString(),\n ...period.params\n )\n\n return {\n users: Number(row?.users ?? 0),\n visits: Number(row?.visits ?? 0),\n sharedVisits: Number(row?.shared_visits ?? 0),\n pageViews: Number(row?.page_views ?? 0),\n }\n }\n\n async calendar(input: ActivityCalendarInput): Promise<readonly ActivityDay[]> {\n const period = overlapping(input)\n const visits = this.all<{ started_at: string; last_seen_at: string }>(\n `\n SELECT v.started_at, v.last_seen_at\n FROM activity_visits v\n WHERE ${period.where}\n `,\n ...period.params\n )\n const days = this.all<{ day: string; page_views: number }>(\n `\n SELECT substr(p.received_at, 1, 10) AS day, COUNT(*) AS page_views\n FROM activity_visits v\n JOIN activity_page_views p ON p.project_id = v.project_id AND p.visit_id = v.id\n WHERE ${period.where}\n AND p.received_at >= ?\n AND p.received_at < ?\n GROUP BY day\n `,\n ...period.params,\n input.from.toISOString(),\n input.to.toISOString()\n )\n\n return activityCalendarDays(\n input,\n visits.map((visit) => ({\n startedAt: new Date(visit.started_at),\n lastSeenAt: new Date(visit.last_seen_at),\n })),\n new Map(days.map((row) => [row.day, Number(row.page_views)]))\n )\n }\n\n async read(input: ReadActivityVisitInput): Promise<StoredActivityVisitPage | null> {\n const [visit] = this.all<VisitRow & { readonly session_id: string }>(\n `\n SELECT ${VISIT_COLUMNS}, v.session_id\n FROM activity_visits v\n WHERE v.project_id = ? AND v.id = ?\n `,\n input.projectId,\n input.id\n )\n if (!visit) {\n return null\n }\n\n // Page views and interactions share the visit's sequence, so one bound covers both.\n const rows = this.all<EventRow>(\n `\n SELECT id, visit_id, sequence, route, NULL AS name, received_at\n FROM activity_page_views\n WHERE project_id = ? AND visit_id = ?\n UNION ALL\n SELECT id, visit_id, sequence, route, name, received_at\n FROM activity_interactions\n WHERE project_id = ? AND visit_id = ?\n ORDER BY sequence\n LIMIT ?\n `,\n input.projectId,\n input.id,\n input.projectId,\n input.id,\n input.limit + 1\n )\n\n const pageViews: ActivityPageView[] = []\n const interactions: ActivityInteraction[] = []\n for (const row of rows.slice(0, input.limit)) {\n if (row.name === null) {\n pageViews.push(pageViewFromRow(row))\n } else {\n interactions.push({ ...pageViewFromRow(row), name: row.name })\n }\n }\n\n return {\n visit: visitFromRow(visit),\n sessionId: visit.session_id,\n pageViews,\n interactions,\n hasMore: rows.length > input.limit,\n }\n }\n\n async sessionVisits(\n input: ListActivitySessionVisitsInput\n ): Promise<readonly ActivitySessionVisits[]> {\n if (input.sessionIds.length === 0) {\n return []\n }\n\n // A session opens a visit per return after inactivity, so each has a few to rank.\n const rows = this.all<SessionVisitRow>(\n `\n SELECT *\n FROM (\n SELECT\n ${VISIT_COLUMNS},\n v.session_id,\n ROW_NUMBER() OVER (\n PARTITION BY v.session_id ORDER BY v.started_at DESC, v.id DESC\n ) AS position,\n COUNT(*) OVER (PARTITION BY v.session_id) AS total\n FROM activity_visits v\n WHERE v.project_id = ?\n AND v.actor_type = 'user'\n AND v.session_id IN (SELECT value FROM json_each(?))\n AND v.user_id = ?\n )\n WHERE position <= ?\n ORDER BY session_id, position\n `,\n input.projectId,\n JSON.stringify(input.sessionIds),\n input.userId,\n input.limit\n )\n\n const bySession = new Map<string, { visits: number; latest: ActivityVisit[] }>()\n for (const row of rows) {\n const session = bySession.get(row.session_id) ?? { visits: Number(row.total), latest: [] }\n session.latest.push(visitFromRow(row))\n bySession.set(row.session_id, session)\n }\n\n return [...bySession].map(([sessionId, session]) => ({ sessionId, ...session }))\n }\n\n private source(input: AppendActivityInput): ActivitySourceState | undefined {\n const [row] = this.all<SourceRow>(\n `\n SELECT\n s.visit_id, v.started_at AS visit_started_at, s.last_seen_at, s.sequence,\n s.window_start, s.window_count\n FROM activity_sources s\n LEFT JOIN activity_visits v ON v.project_id = s.project_id AND v.id = s.visit_id\n WHERE s.project_id = ? AND s.actor_type = ? AND s.session_id = ?\n `,\n input.projectId,\n input.actor.type,\n input.sessionId\n )\n if (!row) {\n return undefined\n }\n\n // A deleted visit leaves its source behind; the next batch starts another visit.\n return {\n visitId: row.visit_id,\n visitStartedAt: row.visit_started_at === null ? null : Date.parse(row.visit_started_at),\n lastSeenAt: Date.parse(row.last_seen_at),\n sequence: Number(row.sequence),\n windowStart: Date.parse(row.window_start),\n windowCount: Number(row.window_count),\n }\n }\n\n /** The session's page views and interactions with an id of the batch, to recognize retries. */\n private storedEvents(input: AppendActivityInput): StoredActivityEvent[] {\n const ids = JSON.stringify(input.events.map((event) => event.id))\n const rows = this.all<{\n id: string\n route: string\n name: string | null\n attribution: string | null\n }>(\n `\n SELECT p.id, p.route, NULL AS name, p.attribution\n FROM activity_page_views p\n JOIN activity_visits v ON v.project_id = p.project_id AND v.id = p.visit_id\n WHERE p.project_id = ?\n AND p.id IN (SELECT value FROM json_each(?))\n AND v.actor_type = ?\n AND v.session_id = ?\n UNION ALL\n SELECT i.id, i.route, i.name, NULL AS attribution\n FROM activity_interactions i\n JOIN activity_visits v ON v.project_id = i.project_id AND v.id = i.visit_id\n WHERE i.project_id = ?\n AND i.id IN (SELECT value FROM json_each(?))\n AND v.actor_type = ?\n AND v.session_id = ?\n `,\n input.projectId,\n ids,\n input.actor.type,\n input.sessionId,\n input.projectId,\n ids,\n input.actor.type,\n input.sessionId\n )\n\n return rows.map((row) => {\n if (row.name !== null) {\n return { id: row.id, route: row.route, name: row.name }\n }\n\n const attribution = parseActivityAttribution(row.attribution)\n return { id: row.id, route: row.route, ...(attribution ? { attribution } : {}) }\n })\n }\n\n private run(sql: string, ...params: SQLQueryBindings[]): void {\n this.db.query<unknown, SQLQueryBindings[]>(sql).run(...params)\n }\n\n private all<T>(sql: string, ...params: SQLQueryBindings[]): T[] {\n return this.db.query<T, SQLQueryBindings[]>(sql).all(...params)\n }\n}\n\ninterface SourceRow {\n readonly visit_id: string\n readonly visit_started_at: string | null\n readonly last_seen_at: string\n readonly sequence: number\n readonly window_start: string\n readonly window_count: number\n}\n\ninterface VisitRow {\n readonly id: string\n readonly actor_type: string\n readonly user_id: string | null\n readonly grant_id: string | null\n readonly started_at: string\n readonly last_seen_at: string\n readonly page_views: number\n readonly interactions: number\n readonly attribution: string | null\n}\n\ninterface SessionVisitRow extends VisitRow {\n readonly session_id: string\n readonly total: number\n}\n\ninterface UserRow {\n readonly user_id: string\n readonly last_seen_at: string\n readonly visits: number\n readonly page_views: number\n}\n\ninterface SummaryRow {\n readonly users: number\n readonly visits: number\n readonly shared_visits: number\n readonly page_views: number\n}\n\ninterface PageViewRow {\n readonly id: string\n readonly visit_id: string\n readonly sequence: number\n readonly route: string\n readonly received_at: string\n}\n\n/** A page view or, with a name, an interaction. */\ninterface EventRow extends PageViewRow {\n readonly name: string | null\n}\n\n/**\n * The visits `v` active in the period, and only the account's when one is asked for. A visit lasts\n * less than a day, so it started at most a day before the period: that bounds the index range.\n */\nfunction overlapping(input: ActivityPeriodInput | ActivityCalendarInput): {\n readonly where: string\n readonly params: SQLQueryBindings[]\n} {\n const conditions = [\n \"v.project_id = ?\",\n \"v.started_at >= ?\",\n \"v.started_at < ?\",\n \"v.last_seen_at >= ?\",\n ]\n const params: SQLQueryBindings[] = [\n input.projectId,\n new Date(input.from.getTime() - ACTIVITY_MAX_VISIT_MS).toISOString(),\n input.to.toISOString(),\n input.from.toISOString(),\n ]\n\n if (input.userId !== undefined) {\n conditions.push(\"v.user_id = ?\")\n params.push(input.userId)\n }\n\n return { where: conditions.join(\" AND \"), params }\n}\n\nfunction cursorOf(cursor: ActivityCursor | undefined): { at: string; id: string } {\n return cursor ? { at: cursor.at.toISOString(), id: cursor.id } : NO_CURSOR\n}\n\nfunction visitFromRow(row: VisitRow): ActivityVisit {\n return {\n id: row.id,\n actor: activityActor(row.actor_type, row.user_id, row.grant_id),\n attribution: parseActivityAttribution(row.attribution),\n startedAt: new Date(row.started_at),\n lastSeenAt: new Date(row.last_seen_at),\n pageViews: Number(row.page_views),\n interactions: Number(row.interactions),\n }\n}\n\nfunction pageViewFromRow(row: PageViewRow): ActivityPageView {\n return {\n id: row.id,\n visitId: row.visit_id,\n sequence: Number(row.sequence),\n route: row.route,\n receivedAt: new Date(row.received_at),\n }\n}\n\nfunction iso(epochMs: number): string {\n return new Date(epochMs).toISOString()\n}\n",
10
- "import type { Database } from \"bun:sqlite\"\nimport {\n agentContextCheckpointMatchesCreateInput,\n assertAgentContextCheckpointAnchors,\n assertAgentContextCheckpointAuthority,\n assertAgentContextCheckpointReplayState,\n assertCreateAgentContextCheckpointInput,\n} from \"@sixb/core/internal/agent-run-storage-provider\"\nimport {\n type AgentContextCheckpointRecord,\n type AgentContextCheckpointStore,\n AgentStorageError,\n type CreateAgentContextCheckpointInput,\n} from \"@sixb/core/storage\"\nimport {\n type AgentContextCheckpointRow,\n type AgentMessageRow,\n type AgentRunRow,\n type AgentThreadRow,\n rowToContextCheckpointRecord,\n rowToMessageRecord,\n rowToRunRecord,\n rowToThreadRecord,\n} from \"./rows\"\n\nconst SQLITE_CHECKPOINT_RUN_ID_BATCH_SIZE = 500\n\nexport class SqliteAgentContextCheckpointStore implements AgentContextCheckpointStore {\n constructor(private readonly db: Database) {}\n\n async create(input: CreateAgentContextCheckpointInput): Promise<AgentContextCheckpointRecord> {\n assertCreateAgentContextCheckpointInput(input, \"SixbSqlite\")\n\n return this.db.transaction(() => {\n const runRow = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.createdByRunId) as AgentRunRow | null\n const threadRow = this.db\n .query(\"SELECT * FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.threadId) as AgentThreadRow | null\n assertAgentContextCheckpointAuthority({\n create: input,\n run: runRow ? rowToRunRecord(runRow) : null,\n thread: threadRow ? rowToThreadRecord(threadRow) : null,\n prefix: \"SixbSqlite\",\n })\n\n const latest = this.findLatest(input.projectId, input.threadId)\n const headRow = this.db\n .query(\n \"SELECT COALESCE(MAX(seq), 0) AS seq FROM agent_messages WHERE project_id = ? AND thread_id = ?\"\n )\n .get(input.projectId, input.threadId) as { seq: number }\n\n const existingForRun = this.db\n .query(\n \"SELECT * FROM agent_context_checkpoints WHERE project_id = ? AND created_by_run_id = ?\"\n )\n .get(input.projectId, input.createdByRunId) as AgentContextCheckpointRow | null\n if (existingForRun) {\n const record = rowToContextCheckpointRecord(existingForRun)\n if (agentContextCheckpointMatchesCreateInput(record, input)) {\n assertAgentContextCheckpointReplayState({\n create: input,\n existing: record,\n latest,\n headSeq: headRow.seq,\n prefix: \"SixbSqlite\",\n })\n return record\n }\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Agent run '${input.createdByRunId}' already created a different context checkpoint.`\n )\n }\n\n const duplicateId = this.db\n .query(\"SELECT 1 FROM agent_context_checkpoints WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id)\n if (duplicateId) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Agent context checkpoint '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const firstRetainedRow = this.db\n .query(\n \"SELECT * FROM agent_messages WHERE project_id = ? AND thread_id = ? AND seq > ? ORDER BY seq ASC LIMIT 1\"\n )\n .get(input.projectId, input.threadId, input.summarizedThroughSeq) as AgentMessageRow | null\n assertAgentContextCheckpointAnchors({\n create: input,\n latest,\n headSeq: headRow.seq,\n firstRetained: firstRetainedRow ? rowToMessageRecord(firstRetainedRow) : null,\n prefix: \"SixbSqlite\",\n })\n\n const createdAt = input.createdAt ?? new Date()\n this.db\n .query(\n `\n INSERT INTO agent_context_checkpoints (\n project_id,\n id,\n thread_id,\n created_by_run_id,\n previous_checkpoint_id,\n reason,\n summary,\n summary_format_version,\n summarized_through_seq,\n observed_head_seq,\n estimated_input_tokens_before,\n estimated_input_tokens_after,\n summary_model_id,\n created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.threadId,\n input.createdByRunId,\n input.expectedPreviousCheckpointId,\n input.reason,\n input.summary,\n input.summaryFormatVersion,\n input.summarizedThroughSeq,\n input.observedHeadSeq,\n input.estimatedInputTokensBefore,\n input.estimatedInputTokensAfter,\n input.summaryModelId,\n createdAt.toISOString()\n )\n\n return this.requireById(input.projectId, input.id)\n })()\n }\n\n async getLatest(input: {\n readonly projectId: string\n readonly threadId: string\n }): Promise<AgentContextCheckpointRecord | null> {\n return this.findLatest(input.projectId, input.threadId)\n }\n\n async getByRunIds(input: {\n readonly projectId: string\n readonly runIds: readonly string[]\n }): Promise<readonly AgentContextCheckpointRecord[]> {\n const runIds = [...new Set(input.runIds)]\n if (runIds.length === 0) return []\n\n const rows: AgentContextCheckpointRow[] = []\n for (let offset = 0; offset < runIds.length; offset += SQLITE_CHECKPOINT_RUN_ID_BATCH_SIZE) {\n const batch = runIds.slice(offset, offset + SQLITE_CHECKPOINT_RUN_ID_BATCH_SIZE)\n const placeholders = batch.map(() => \"?\").join(\", \")\n rows.push(\n ...(this.db\n .query(\n `SELECT * FROM agent_context_checkpoints WHERE project_id = ? AND created_by_run_id IN (${placeholders})`\n )\n .all(input.projectId, ...batch) as AgentContextCheckpointRow[])\n )\n }\n const byRunId = new Map(\n rows.map((row) => [row.created_by_run_id, rowToContextCheckpointRecord(row)] as const)\n )\n return runIds.flatMap((runId) => {\n const checkpoint = byRunId.get(runId)\n return checkpoint ? [checkpoint] : []\n })\n }\n\n private findLatest(projectId: string, threadId: string): AgentContextCheckpointRecord | null {\n const row = this.db\n .query(\n `\n SELECT * FROM agent_context_checkpoints\n WHERE project_id = ? AND thread_id = ?\n ORDER BY summarized_through_seq DESC, created_at DESC, id DESC\n LIMIT 1\n `\n )\n .get(projectId, threadId) as AgentContextCheckpointRow | null\n return row ? rowToContextCheckpointRecord(row) : null\n }\n\n private requireById(projectId: string, id: string): AgentContextCheckpointRecord {\n const row = this.db\n .query(\"SELECT * FROM agent_context_checkpoints WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentContextCheckpointRow | null\n if (!row) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Failed to load agent context checkpoint '${id}' for project '${projectId}'.`\n )\n }\n return rowToContextCheckpointRecord(row)\n }\n}\n",
11
- "import type { Database } from \"bun:sqlite\"\nimport type { AgentMessagePart, Principal } from \"@sixb/core\"\nimport { snapshotAgentThreadSandboxParams } from \"@sixb/core/internal/agent-run-storage-provider\"\nimport { parseSixbFailure } from \"@sixb/core/internal/errors\"\nimport {\n AGENT_RUN_FAILURE_CODES,\n type AgentContextCheckpointRecord,\n type AgentMessageRecord,\n type AgentRunDiagnostic,\n type AgentRunRecord,\n type AgentThreadRecord,\n type AgentThreadSandboxState,\n type ConversationAgentRunSpec,\n coerceAgentRunFinishReason,\n type SubagentRunResult,\n type SubagentRunSpec,\n} from \"@sixb/core/storage\"\nimport type { SqliteValue } from \"../run-list-query\"\n\n// ── row shapes (snake_case, as stored) ──────────────────────────────────────────────────────────\n\nexport interface AgentThreadRow {\n project_id: string\n id: string\n owner_principal_type: Principal[\"type\"]\n owner_principal_id: string\n title: string | null\n sandbox_params: string | null\n sandbox_state: string | null\n status: AgentThreadRecord[\"status\"]\n active_run_id: string | null\n last_message_at: string | null\n message_count: number\n created_at: string\n updated_at: string\n}\n\nexport interface AgentRunRow {\n project_id: string\n id: string\n execution_id: string\n kind: AgentRunRecord[\"kind\"]\n thread_id: string | null\n trigger_message_id: string | null\n parent_run_id: string | null\n spawn_key: string | null\n spec: string | null\n result: string | null\n status: AgentRunRecord[\"status\"]\n model_id: string | null\n finish_reason: string | null\n error: string | null\n diagnostics: string | null\n attempt: number\n execution_token: string | null\n execution_queue_lease_expires_at: string | null\n created_at: string\n started_at: string | null\n completed_at: string | null\n}\n\nexport interface AgentMessageRow {\n project_id: string\n id: string\n thread_id: string\n run_id: string | null\n role: AgentMessageRecord[\"role\"]\n author_principal_type: Principal[\"type\"] | null\n author_principal_id: string | null\n seq: number\n parts: string\n metadata: string | null\n content_version: number\n created_at: string\n completed_at: string | null\n}\n\nexport interface AgentContextCheckpointRow {\n project_id: string\n id: string\n thread_id: string\n created_by_run_id: string\n previous_checkpoint_id: string | null\n reason: AgentContextCheckpointRecord[\"reason\"]\n summary: string\n summary_format_version: number\n summarized_through_seq: number\n observed_head_seq: number\n estimated_input_tokens_before: number\n estimated_input_tokens_after: number\n summary_model_id: string\n created_at: string\n}\n\n// ── row → record mappers ────────────────────────────────────────────────────────────────────────\n\nexport function rowToThreadRecord(row: AgentThreadRow): AgentThreadRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n ownerPrincipal: { type: row.owner_principal_type, id: row.owner_principal_id },\n title: row.title ?? undefined,\n ...(row.sandbox_state == null\n ? {}\n : {\n sandboxState: JSON.parse(row.sandbox_state) as AgentThreadSandboxState,\n }),\n ...(row.sandbox_params == null\n ? {}\n : { sandboxParams: snapshotAgentThreadSandboxParams(JSON.parse(row.sandbox_params)) }),\n status: row.status,\n activeRunId: row.active_run_id,\n lastMessageAt: row.last_message_at ? new Date(row.last_message_at) : undefined,\n messageCount: row.message_count,\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n }\n}\n\nexport function rowToRunRecord(row: AgentRunRow): AgentRunRecord {\n const base = {\n id: row.id,\n projectId: row.project_id,\n executionId: row.execution_id,\n status: row.status,\n modelId: row.model_id ?? undefined,\n finishReason: coerceAgentRunFinishReason(row.finish_reason),\n error: row.error === null ? undefined : parseSixbFailure(row.error, AGENT_RUN_FAILURE_CODES),\n diagnostics:\n row.diagnostics === null ? undefined : (JSON.parse(row.diagnostics) as AgentRunDiagnostic[]),\n attempt: row.attempt,\n execution:\n row.execution_token && row.execution_queue_lease_expires_at\n ? {\n token: row.execution_token,\n queueLeaseExpiresAt: new Date(row.execution_queue_lease_expires_at),\n }\n : undefined,\n createdAt: new Date(row.created_at),\n startedAt: row.started_at ? new Date(row.started_at) : undefined,\n completedAt: row.completed_at ? new Date(row.completed_at) : undefined,\n }\n if (row.kind === \"conversation\") {\n if (!row.thread_id || !row.trigger_message_id) {\n throw new Error(\n `[SixbSqlite] Conversational Agent run '${row.id}' has invalid persisted fields.`\n )\n }\n return {\n ...base,\n kind: \"conversation\",\n threadId: row.thread_id,\n triggerMessageId: row.trigger_message_id,\n ...(row.spec === null ? {} : { spec: JSON.parse(row.spec) as ConversationAgentRunSpec }),\n }\n }\n if (!row.parent_run_id || !row.spawn_key || row.spec === null) {\n throw new Error(`[SixbSqlite] Subagent run '${row.id}' has invalid persisted fields.`)\n }\n return {\n ...base,\n kind: \"subagent\",\n parentRunId: row.parent_run_id,\n spawnKey: row.spawn_key,\n spec: JSON.parse(row.spec) as SubagentRunSpec,\n ...(row.result === null ? {} : { result: JSON.parse(row.result) as SubagentRunResult }),\n }\n}\n\nexport function rowToMessageRecord(row: AgentMessageRow): AgentMessageRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n threadId: row.thread_id,\n runId: row.run_id,\n role: row.role,\n authorPrincipal: principalFromColumns(row.author_principal_type, row.author_principal_id),\n seq: row.seq,\n parts: JSON.parse(row.parts) as AgentMessagePart[],\n // A null/absent column and an explicit JSON `null` both mean \"no metadata\" (jsonb cannot tell\n // SQL NULL from a json null on read, so both backends normalise to `undefined` for parity).\n metadata: row.metadata === null ? undefined : (JSON.parse(row.metadata) ?? undefined),\n contentVersion: row.content_version,\n createdAt: new Date(row.created_at),\n completedAt: row.completed_at ? new Date(row.completed_at) : undefined,\n }\n}\n\nexport function rowToContextCheckpointRecord(\n row: AgentContextCheckpointRow\n): AgentContextCheckpointRecord {\n if (row.summary_format_version !== 1) {\n throw new Error(\n `[SixbSqlite] Unsupported agent context checkpoint summary format version '${row.summary_format_version}'.`\n )\n }\n return {\n id: row.id,\n projectId: row.project_id,\n threadId: row.thread_id,\n createdByRunId: row.created_by_run_id,\n previousCheckpointId: row.previous_checkpoint_id ?? undefined,\n reason: row.reason,\n summary: row.summary,\n summaryFormatVersion: 1,\n summarizedThroughSeq: row.summarized_through_seq,\n observedHeadSeq: row.observed_head_seq,\n estimatedInputTokensBefore: row.estimated_input_tokens_before,\n estimatedInputTokensAfter: row.estimated_input_tokens_after,\n summaryModelId: row.summary_model_id,\n createdAt: new Date(row.created_at),\n }\n}\n\nfunction principalFromColumns(\n type: Principal[\"type\"] | null | undefined,\n id: string | null | undefined\n): Principal | undefined {\n return type && id ? { type, id } : undefined\n}\n\n// ── offset pagination (threads / messages order by their own column, not started_at) ─────────────\n\nexport function queryAgentList<TRow>(input: {\n readonly db: Database\n readonly table: \"agent_threads\" | \"agent_messages\"\n readonly whereClauses: readonly string[]\n readonly args: readonly SqliteValue[]\n readonly orderBy: string\n readonly limit?: number\n readonly offset?: number\n}): { readonly rows: readonly TRow[]; readonly total: number; readonly hasMore: boolean } {\n const where = `WHERE ${input.whereClauses.join(\" AND \")}`\n const offset = input.offset ?? 0\n\n const totalRow = input.db\n .query(`SELECT COUNT(*) AS count FROM ${input.table} ${where}`)\n .get(...input.args) as { count: number }\n\n let query = `SELECT * FROM ${input.table} ${where} ORDER BY ${input.orderBy}`\n const queryArgs = [...input.args]\n\n if (input.limit !== undefined) {\n query += \" LIMIT ? OFFSET ?\"\n queryArgs.push(input.limit, offset)\n } else if (offset > 0) {\n query += \" LIMIT -1 OFFSET ?\"\n queryArgs.push(offset)\n }\n\n const rows = input.db.query(query).all(...queryArgs) as TRow[]\n const total = totalRow.count\n return { rows, total, hasMore: offset + rows.length < total }\n}\n",
12
- "import type { Database } from \"bun:sqlite\"\nimport { AGENT_MESSAGE_CONTENT_VERSION } from \"@sixb/core/internal/agents\"\nimport {\n type AgentMessageRecord,\n type AgentMessageStore,\n AgentStorageError,\n type AppendAgentMessageInput,\n type DeleteAgentMessagesByRunInput,\n type ListAgentMessagesInput,\n type ListAgentMessagesResult,\n} from \"@sixb/core/storage\"\nimport type { SqliteValue } from \"../run-list-query\"\nimport { isUniqueConstraintError } from \"../storage-errors\"\nimport { type AgentMessageRow, queryAgentList, rowToMessageRecord } from \"./rows\"\n\nexport class SqliteAgentMessageStore implements AgentMessageStore {\n constructor(private readonly db: Database) {}\n\n async append(input: AppendAgentMessageInput): Promise<AgentMessageRecord> {\n const createdAt = input.createdAt ?? new Date()\n\n return this.db.transaction(() => {\n const thread = this.db\n .query(\"SELECT 1 AS present FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.threadId) as { present: number } | null\n\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[SixbSqlite] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n\n if (input.runId !== null) {\n const run = this.db\n .query(\"SELECT 1 AS present FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.runId) as { present: number } | null\n\n if (!run) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[SixbSqlite] Agent run '${input.runId}' not found for project '${input.projectId}'.`\n )\n }\n }\n\n const seqRow = this.db\n .query(\n \"SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM agent_messages WHERE project_id = ? AND thread_id = ?\"\n )\n .get(input.projectId, input.threadId) as { next: number }\n\n try {\n this.db\n .query(\n `\n INSERT INTO agent_messages (\n project_id,\n id,\n thread_id,\n run_id,\n role,\n author_principal_type,\n author_principal_id,\n seq,\n parts,\n metadata,\n content_version,\n created_at,\n completed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.threadId,\n input.runId,\n input.role,\n input.authorPrincipal?.type ?? null,\n input.authorPrincipal?.id ?? null,\n seqRow.next,\n JSON.stringify(input.parts),\n input.metadata === undefined ? null : JSON.stringify(input.metadata),\n AGENT_MESSAGE_CONTENT_VERSION,\n createdAt.toISOString(),\n input.completedAt ? input.completedAt.toISOString() : null\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Agent message '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n throw error\n }\n\n this.db\n .query(\n `\n UPDATE agent_threads\n SET message_count = message_count + 1, last_message_at = ?, updated_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(createdAt.toISOString(), createdAt.toISOString(), input.projectId, input.threadId)\n\n return this.requireMessage(input.projectId, input.id)\n })()\n }\n\n async deleteByRunId(input: DeleteAgentMessagesByRunInput): Promise<number> {\n return this.db.transaction(() => {\n const thread = this.db\n .query(\"SELECT 1 AS present FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.threadId) as { present: number } | null\n\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[SixbSqlite] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n\n const deleted = this.db\n .query(\"DELETE FROM agent_messages WHERE project_id = ? AND thread_id = ? AND run_id = ?\")\n .run(input.projectId, input.threadId, input.runId)\n if (deleted.changes === 0) {\n return 0\n }\n\n const updatedAt = new Date().toISOString()\n this.db\n .query(\n `\n UPDATE agent_threads\n SET\n message_count = (\n SELECT COUNT(*) FROM agent_messages WHERE project_id = ? AND thread_id = ?\n ),\n last_message_at = (\n SELECT created_at FROM agent_messages\n WHERE project_id = ? AND thread_id = ?\n ORDER BY seq DESC\n LIMIT 1\n ),\n updated_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.projectId,\n input.threadId,\n input.projectId,\n input.threadId,\n updatedAt,\n input.projectId,\n input.threadId\n )\n\n return deleted.changes\n })()\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentMessageRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM agent_messages WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as AgentMessageRow | null\n\n return row ? rowToMessageRecord(row) : null\n }\n\n async list(input: ListAgentMessagesInput): Promise<ListAgentMessagesResult> {\n if (input.roles !== undefined && input.roles.length === 0) {\n return { messages: [], hasMore: false, total: 0 }\n }\n\n const whereClauses = [\"project_id = ?\", \"thread_id = ?\"]\n const args: SqliteValue[] = [input.projectId, input.threadId]\n\n if (input.afterSeq !== undefined) {\n whereClauses.push(\"seq > ?\")\n args.push(input.afterSeq)\n }\n\n if (input.roles) {\n whereClauses.push(`role IN (${input.roles.map(() => \"?\").join(\", \")})`)\n args.push(...input.roles)\n }\n\n const dir = input.order === \"desc\" ? \"DESC\" : \"ASC\"\n const { rows, total, hasMore } = queryAgentList<AgentMessageRow>({\n db: this.db,\n table: \"agent_messages\",\n whereClauses,\n args,\n orderBy: `seq ${dir}`,\n limit: input.limit,\n offset: input.offset,\n })\n\n return { messages: rows.map(rowToMessageRecord), hasMore, total }\n }\n\n private requireMessage(projectId: string, id: string): AgentMessageRecord {\n const row = this.db\n .query(\"SELECT * FROM agent_messages WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentMessageRow | null\n\n if (!row) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Failed to load agent message '${id}' for project '${projectId}'.`\n )\n }\n\n return rowToMessageRecord(row)\n }\n}\n",
10
+ "import type { Database } from \"bun:sqlite\"\nimport type { Principal } from \"@sixb/core\"\nimport {\n agentApprovalCallKey,\n assertAgentApprovalCaller,\n assertRequestAgentApprovalInput,\n newAgentApprovalRecord,\n} from \"@sixb/core/internal/agent-run-storage-provider\"\nimport {\n type AgentApprovalCall,\n type AgentApprovalCursor,\n type AgentApprovalMode,\n type AgentApprovalOutcome,\n type AgentApprovalRecord,\n type AgentApprovalStore,\n AgentStorageError,\n type DecideAgentApprovalInput,\n type DecideAgentApprovalResult,\n type ListAgentApprovalsInput,\n type ListAgentApprovalsResult,\n type MarkAgentApprovalsReportedInput,\n type RequestAgentApprovalInput,\n type RequestAgentApprovalResult,\n type SettleAgentApprovalsInput,\n type StopAgentApprovalsInput,\n type StopAgentApprovalsResult,\n} from \"@sixb/core/storage\"\nimport { runImmediateTransaction } from \"../transactions\"\nimport { type AgentRunRow, rowToRunRecord } from \"./rows\"\n\ninterface AgentApprovalRow {\n readonly project_id: string\n readonly id: string\n readonly thread_id: string\n readonly run_id: string\n readonly caller_run_id: string\n readonly requested_by_type: Principal[\"type\"]\n readonly requested_by_id: string\n readonly mode: AgentApprovalRecord[\"mode\"]\n readonly call_key: string\n readonly call: string\n readonly status: AgentApprovalRecord[\"status\"]\n readonly created_at: string\n readonly expires_at: string\n readonly decided_at: string | null\n readonly decided_by_type: Principal[\"type\"] | null\n readonly decided_by_id: string | null\n readonly outcome: string | null\n readonly reported_in_message_id: string | null\n readonly raised_mode: AgentApprovalMode | null\n readonly turn_stopped_at: string | null\n readonly execution_claimed_at: string | null\n}\n\nconst LIVE_CALL = `\n SELECT * FROM agent_approvals\n WHERE project_id = ? AND thread_id = ? AND call_key = ?\n AND status IN ('pending', 'approved', 'denied')\n`\n\nexport class SqliteAgentApprovalStore implements AgentApprovalStore {\n constructor(private readonly db: Database) {}\n\n async request(input: RequestAgentApprovalInput): Promise<RequestAgentApprovalResult> {\n assertRequestAgentApprovalInput(input, \"SixbSqlite\")\n\n return runImmediateTransaction(this.db, () => {\n const threadId = assertAgentApprovalCaller({\n request: input,\n turn: this.run(input.projectId, input.runId),\n caller: this.run(input.projectId, input.callerRunId),\n prefix: \"SixbSqlite\",\n })\n const callKey = agentApprovalCallKey(input.call)\n const live = this.db\n .query(LIVE_CALL)\n .get(input.projectId, threadId, callKey) as AgentApprovalRow | null\n if (live) return { approval: rowToApproval(live), created: false }\n\n if (this.row(input.projectId, input.id)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Agent approval '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n const approval = newAgentApprovalRecord(input, threadId)\n this.db\n .query(\n `INSERT INTO agent_approvals (\n project_id, id, thread_id, run_id, caller_run_id, requested_by_type, requested_by_id,\n mode, call_key, call, status, created_at, expires_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`\n )\n .run(\n approval.projectId,\n approval.id,\n approval.threadId,\n approval.runId,\n approval.callerRunId,\n approval.requestedBy.type,\n approval.requestedBy.id,\n approval.mode,\n approval.callKey,\n JSON.stringify(approval.call),\n approval.createdAt.toISOString(),\n approval.expiresAt.toISOString()\n )\n return { approval, created: true }\n })\n }\n\n async decide(input: DecideAgentApprovalInput): Promise<DecideAgentApprovalResult | null> {\n const decidedAt = (input.decidedAt ?? new Date()).toISOString()\n\n return runImmediateTransaction(this.db, () => {\n const current = this.row(input.projectId, input.id)\n if (!current) return null\n if (current.status !== \"pending\") return { approval: rowToApproval(current), decided: false }\n\n if (current.expires_at <= decidedAt) {\n this.db\n .query(\"UPDATE agent_approvals SET status = 'expired' WHERE project_id = ? AND id = ?\")\n .run(input.projectId, input.id)\n } else {\n this.db\n .query(\n `UPDATE agent_approvals\n SET status = ?, decided_at = ?, decided_by_type = ?, decided_by_id = ?, raised_mode = ?\n WHERE project_id = ? AND id = ?`\n )\n .run(\n input.decision,\n decidedAt,\n input.decidedBy.type,\n input.decidedBy.id,\n input.decision === \"approved\" ? (input.raisedMode ?? null) : null,\n input.projectId,\n input.id\n )\n }\n const approval = this.require(input.projectId, input.id)\n return { approval, decided: approval.status === input.decision }\n })\n }\n\n async recordOutcome(input: {\n readonly projectId: string\n readonly id: string\n readonly outcome: AgentApprovalOutcome\n }): Promise<AgentApprovalRecord> {\n return runImmediateTransaction(this.db, () => {\n const current = this.row(input.projectId, input.id)\n if (current?.status !== \"approved\") {\n throw new AgentStorageError(\n \"invalid_state\",\n current\n ? `[SixbSqlite] Agent approval '${input.id}' is not approved (status '${current.status}').`\n : `[SixbSqlite] Agent approval '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n if (current.outcome !== null) return rowToApproval(current)\n\n this.db\n .query(\"UPDATE agent_approvals SET outcome = ? WHERE project_id = ? AND id = ?\")\n .run(JSON.stringify(input.outcome), input.projectId, input.id)\n return this.require(input.projectId, input.id)\n })\n }\n\n async settle(input: SettleAgentApprovalsInput): Promise<readonly AgentApprovalRecord[]> {\n const rows = this.db\n .query(\n `UPDATE agent_approvals SET status = ?\n WHERE project_id = ? AND thread_id = ? AND status = 'pending'\n RETURNING *`\n )\n .all(input.status, input.projectId, input.threadId) as AgentApprovalRow[]\n return rows.map(rowToApproval).sort(compareApprovals)\n }\n\n async stop(input: StopAgentApprovalsInput): Promise<StopAgentApprovalsResult> {\n const stoppedAt = (input.stoppedAt ?? new Date()).toISOString()\n const clauses = [\n \"project_id = ?\",\n \"thread_id = ?\",\n \"reported_in_message_id IS NULL\",\n \"(status = 'pending' OR turn_stopped_at IS NULL)\",\n ]\n const params: string[] = [input.projectId, input.threadId]\n if (input.runId !== undefined) {\n clauses.push(\"run_id = ?\")\n params.push(input.runId)\n }\n if (input.requestedBy !== undefined) {\n clauses.push(\"requested_by_type = ? AND requested_by_id = ?\")\n params.push(input.requestedBy.type, input.requestedBy.id)\n }\n\n return runImmediateTransaction(this.db, () => {\n const matched = this.db\n .query(`SELECT * FROM agent_approvals WHERE ${clauses.join(\" AND \")}`)\n .all(...params) as AgentApprovalRow[]\n const update = this.db.query(\n `UPDATE agent_approvals\n SET status = CASE WHEN status = 'pending' THEN 'cancelled' ELSE status END,\n turn_stopped_at = COALESCE(turn_stopped_at, ?)\n WHERE project_id = ? AND id = ?`\n )\n for (const row of matched) update.run(stoppedAt, input.projectId, row.id)\n\n const cancelled = matched\n .filter((row) => row.status === \"pending\")\n .map((row) => this.require(input.projectId, row.id))\n const stopped = matched.filter((row) => row.turn_stopped_at === null).length\n return { cancelled: cancelled.sort(compareApprovals), stopped }\n })\n }\n\n async holdsRun(input: { readonly projectId: string; readonly runId: string }): Promise<boolean> {\n return sqliteHoldsRun(this.db, input.projectId, input.runId)\n }\n\n async claimExecution(input: {\n readonly projectId: string\n readonly id: string\n readonly claimedAt: Date\n readonly staleBefore: Date\n }): Promise<AgentApprovalRecord | null> {\n const row = this.db\n .query(\n `UPDATE agent_approvals SET execution_claimed_at = ?\n WHERE project_id = ? AND id = ? AND status = 'approved' AND outcome IS NULL\n AND COALESCE(execution_claimed_at, decided_at) <= ?\n RETURNING *`\n )\n .get(\n input.claimedAt.toISOString(),\n input.projectId,\n input.id,\n input.staleBefore.toISOString()\n ) as AgentApprovalRow | null\n return row ? rowToApproval(row) : null\n }\n\n async listRepairable(input: {\n readonly projectId: string\n readonly claimableBefore: Date\n readonly after?: AgentApprovalCursor\n readonly limit: number\n }): Promise<readonly AgentApprovalRecord[]> {\n const afterAt = input.after?.createdAt.toISOString() ?? null\n const afterId = input.after?.id ?? \"\"\n // Each half of the OR matches one partial index.\n const rows = this.db\n .query(\n `SELECT * FROM agent_approvals\n WHERE project_id = ?\n AND (\n (status = 'approved' AND outcome IS NULL\n AND COALESCE(execution_claimed_at, decided_at) <= ?)\n OR (status IN ('approved', 'denied') AND reported_in_message_id IS NULL\n AND turn_stopped_at IS NULL)\n )\n AND (? IS NULL OR created_at > ? OR (created_at = ? AND id > ?))\n ORDER BY created_at, id\n LIMIT ?`\n )\n .all(\n input.projectId,\n input.claimableBefore.toISOString(),\n afterAt,\n afterAt,\n afterAt,\n afterId,\n input.limit\n ) as AgentApprovalRow[]\n return rows.map(rowToApproval)\n }\n\n async expireDue(input: {\n readonly projectId: string\n readonly now: Date\n readonly limit?: number\n }): Promise<readonly AgentApprovalRecord[]> {\n const rows = this.db\n .query(\n `UPDATE agent_approvals SET status = 'expired'\n WHERE project_id = ? AND id IN (\n SELECT id FROM agent_approvals\n WHERE project_id = ? AND status = 'pending' AND expires_at <= ?\n ORDER BY created_at, id\n LIMIT ?\n )\n RETURNING *`\n )\n .all(\n input.projectId,\n input.projectId,\n input.now.toISOString(),\n input.limit ?? -1\n ) as AgentApprovalRow[]\n return rows.map(rowToApproval).sort(compareApprovals)\n }\n\n async markReported(input: MarkAgentApprovalsReportedInput): Promise<readonly string[]> {\n const ids = [...new Set(input.ids)]\n if (ids.length === 0) return []\n\n const rows = this.db\n .query(\n `UPDATE agent_approvals SET reported_in_message_id = ?\n WHERE project_id = ? AND thread_id = ? AND reported_in_message_id IS NULL\n AND (? = 0 OR turn_stopped_at IS NULL)\n AND id IN (${ids.map(() => \"?\").join(\", \")})\n RETURNING id`\n )\n .all(\n input.messageId,\n input.projectId,\n input.threadId,\n input.resuming === true ? 1 : 0,\n ...ids\n ) as { id: string }[]\n const marked = new Set(rows.map((row) => row.id))\n return ids.filter((id) => marked.has(id))\n }\n\n async getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<AgentApprovalRecord | null> {\n const row = this.row(params.projectId, params.id)\n return row ? rowToApproval(row) : null\n }\n\n async list(input: ListAgentApprovalsInput): Promise<ListAgentApprovalsResult> {\n if (input.statuses?.length === 0) return { approvals: [], hasMore: false, total: 0 }\n\n const { where, params } = listFilter(input)\n const offset = input.offset ?? 0\n return this.db.transaction(() => {\n const counted = this.db\n .query(`SELECT COUNT(*) AS total FROM agent_approvals WHERE ${where}`)\n .get(...params) as { total: number }\n const rows = this.db\n .query(\n `SELECT * FROM agent_approvals WHERE ${where}\n ORDER BY created_at, id LIMIT ? OFFSET ?`\n )\n .all(...params, input.limit ?? -1, offset) as AgentApprovalRow[]\n return {\n approvals: rows.map(rowToApproval),\n hasMore: offset + rows.length < counted.total,\n total: counted.total,\n }\n })()\n }\n\n private run(projectId: string, id: string) {\n const row = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentRunRow | null\n return row ? rowToRunRecord(row) : null\n }\n\n private row(projectId: string, id: string): AgentApprovalRow | null {\n return this.db\n .query(\"SELECT * FROM agent_approvals WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentApprovalRow | null\n }\n\n private require(projectId: string, id: string): AgentApprovalRecord {\n const row = this.row(projectId, id)\n if (!row) throw new Error(`[SixbSqlite] Agent approval '${id}' disappeared.`)\n return rowToApproval(row)\n }\n}\n\n/** The `list` predicate, as the in-memory store's `agentApprovalMatches` reads it. */\nfunction listFilter(input: ListAgentApprovalsInput): {\n readonly where: string\n readonly params: readonly (string | number)[]\n} {\n const clauses = [\"project_id = ?\"]\n const params: (string | number)[] = [input.projectId]\n if (input.threadId !== undefined) {\n clauses.push(\"thread_id = ?\")\n params.push(input.threadId)\n }\n if (input.runId !== undefined) {\n clauses.push(\"run_id = ?\")\n params.push(input.runId)\n }\n if (input.requestedBy !== undefined) {\n clauses.push(\"requested_by_type = ? AND requested_by_id = ?\")\n params.push(input.requestedBy.type, input.requestedBy.id)\n }\n if (input.statuses !== undefined) {\n clauses.push(`status IN (${input.statuses.map(() => \"?\").join(\", \")})`)\n params.push(...input.statuses)\n }\n if (input.reported !== undefined) {\n clauses.push(`reported_in_message_id IS ${input.reported ? \"NOT NULL\" : \"NULL\"}`)\n }\n return { where: clauses.join(\" AND \"), params }\n}\n\nfunction rowToApproval(row: AgentApprovalRow): AgentApprovalRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n threadId: row.thread_id,\n runId: row.run_id,\n callerRunId: row.caller_run_id,\n requestedBy: { type: row.requested_by_type, id: row.requested_by_id },\n mode: row.mode,\n callKey: row.call_key,\n call: JSON.parse(row.call) as AgentApprovalCall,\n status: row.status,\n createdAt: new Date(row.created_at),\n expiresAt: new Date(row.expires_at),\n ...(row.decided_at === null ? {} : { decidedAt: new Date(row.decided_at) }),\n ...(row.decided_by_type === null || row.decided_by_id === null\n ? {}\n : { decidedBy: { type: row.decided_by_type, id: row.decided_by_id } }),\n ...(row.outcome === null ? {} : { outcome: JSON.parse(row.outcome) as AgentApprovalOutcome }),\n ...(row.reported_in_message_id === null\n ? {}\n : { reportedInMessageId: row.reported_in_message_id }),\n ...(row.raised_mode === null ? {} : { raisedMode: row.raised_mode }),\n ...(row.turn_stopped_at === null ? {} : { turnStoppedAt: new Date(row.turn_stopped_at) }),\n ...(row.execution_claimed_at === null\n ? {}\n : { executionClaimedAt: new Date(row.execution_claimed_at) }),\n }\n}\n\n/**\n * Whether a run holds a call: an approval of its, or one it made for its turn, pending or decided\n * and not reported yet. `holdsRun` and the paused finish of `runs.finish` both ask this.\n */\nexport function sqliteHoldsRun(db: Database, projectId: string, runId: string): boolean {\n const held = db\n .query(\n `SELECT id FROM agent_approvals\n WHERE project_id = ? AND (run_id = ? OR caller_run_id = ?)\n AND status IN ('pending', 'approved', 'denied') AND reported_in_message_id IS NULL\n LIMIT 1`\n )\n .get(projectId, runId, runId)\n return held !== null\n}\n\nfunction compareApprovals(left: AgentApprovalRecord, right: AgentApprovalRecord): number {\n return left.createdAt.getTime() - right.createdAt.getTime() || left.id.localeCompare(right.id)\n}\n",
11
+ "import type { Database } from \"bun:sqlite\"\nimport type { AgentMessagePart, Principal } from \"@sixb/core\"\nimport { snapshotAgentThreadSandboxParams } from \"@sixb/core/internal/agent-run-storage-provider\"\nimport { parseSixbFailure } from \"@sixb/core/internal/errors\"\nimport {\n AGENT_RUN_FAILURE_CODES,\n type AgentContextCheckpointRecord,\n type AgentMessageRecord,\n type AgentRunDiagnostic,\n type AgentRunRecord,\n type AgentThreadParticipantRecord,\n type AgentThreadRecord,\n type AgentThreadSandboxState,\n type ConversationAgentRunSpec,\n coerceAgentRunFinishReason,\n type SubagentRunResult,\n type SubagentRunSpec,\n} from \"@sixb/core/storage\"\nimport type { SqliteValue } from \"../run-list-query\"\n\n// ── row shapes (snake_case, as stored) ──────────────────────────────────────────────────────────\n\nexport interface AgentThreadRow {\n project_id: string\n id: string\n kind: AgentThreadRecord[\"kind\"]\n parent_thread_id: string | null\n parent_run_id: string | null\n spawn_key: string | null\n owner_principal_type: Principal[\"type\"]\n owner_principal_id: string\n title: string | null\n sandbox_params: string | null\n sandbox_state: string | null\n status: AgentThreadRecord[\"status\"]\n active_run_id: string | null\n last_message_at: string | null\n message_count: number\n created_at: string\n updated_at: string\n}\n\nexport interface AgentThreadParticipantRow {\n project_id: string\n thread_id: string\n principal_type: \"user\"\n principal_id: string\n added_at: string\n added_by_type: Principal[\"type\"]\n added_by_id: string\n}\n\nexport interface AgentRunRow {\n project_id: string\n id: string\n execution_id: string\n kind: AgentRunRecord[\"kind\"]\n thread_id: string | null\n trigger_message_id: string | null\n parent_run_id: string | null\n spawn_key: string | null\n spec: string | null\n result: string | null\n status: AgentRunRecord[\"status\"]\n model_id: string | null\n finish_reason: string | null\n error: string | null\n diagnostics: string | null\n attempt: number\n execution_token: string | null\n execution_queue_lease_expires_at: string | null\n created_at: string\n started_at: string | null\n completed_at: string | null\n}\n\nexport interface AgentMessageRow {\n project_id: string\n id: string\n thread_id: string\n run_id: string | null\n role: AgentMessageRecord[\"role\"]\n author_principal_type: Principal[\"type\"] | null\n author_principal_id: string | null\n seq: number\n parts: string\n metadata: string | null\n content_version: number\n created_at: string\n completed_at: string | null\n}\n\nexport interface AgentContextCheckpointRow {\n project_id: string\n id: string\n thread_id: string\n created_by_run_id: string\n previous_checkpoint_id: string | null\n reason: AgentContextCheckpointRecord[\"reason\"]\n summary: string\n summary_format_version: number\n summarized_through_seq: number\n observed_head_seq: number\n estimated_input_tokens_before: number\n estimated_input_tokens_after: number\n summary_model_id: string\n created_at: string\n}\n\n// ── row → record mappers ────────────────────────────────────────────────────────────────────────\n\nexport function rowToThreadRecord(row: AgentThreadRow): AgentThreadRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n kind: row.kind,\n ...(row.parent_thread_id && row.parent_run_id && row.spawn_key\n ? {\n parent: {\n threadId: row.parent_thread_id,\n spawnedBy: row.parent_run_id,\n key: row.spawn_key,\n },\n }\n : {}),\n ownerPrincipal: { type: row.owner_principal_type, id: row.owner_principal_id },\n title: row.title ?? undefined,\n ...(row.sandbox_state == null\n ? {}\n : {\n sandboxState: JSON.parse(row.sandbox_state) as AgentThreadSandboxState,\n }),\n ...(row.sandbox_params == null\n ? {}\n : { sandboxParams: snapshotAgentThreadSandboxParams(JSON.parse(row.sandbox_params)) }),\n status: row.status,\n activeRunId: row.active_run_id,\n lastMessageAt: row.last_message_at ? new Date(row.last_message_at) : undefined,\n messageCount: row.message_count,\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n }\n}\n\nexport function rowToRunRecord(row: AgentRunRow): AgentRunRecord {\n const base = {\n id: row.id,\n projectId: row.project_id,\n executionId: row.execution_id,\n status: row.status,\n modelId: row.model_id ?? undefined,\n finishReason: coerceAgentRunFinishReason(row.finish_reason),\n error: row.error === null ? undefined : parseSixbFailure(row.error, AGENT_RUN_FAILURE_CODES),\n diagnostics:\n row.diagnostics === null ? undefined : (JSON.parse(row.diagnostics) as AgentRunDiagnostic[]),\n attempt: row.attempt,\n execution:\n row.execution_token && row.execution_queue_lease_expires_at\n ? {\n token: row.execution_token,\n queueLeaseExpiresAt: new Date(row.execution_queue_lease_expires_at),\n }\n : undefined,\n createdAt: new Date(row.created_at),\n startedAt: row.started_at ? new Date(row.started_at) : undefined,\n completedAt: row.completed_at ? new Date(row.completed_at) : undefined,\n }\n if (row.kind === \"conversation\") {\n if (!row.thread_id || !row.trigger_message_id) {\n throw new Error(\n `[SixbSqlite] Conversational Agent run '${row.id}' has invalid persisted fields.`\n )\n }\n return {\n ...base,\n kind: \"conversation\",\n threadId: row.thread_id,\n triggerMessageId: row.trigger_message_id,\n ...(row.spec === null ? {} : { spec: JSON.parse(row.spec) as ConversationAgentRunSpec }),\n }\n }\n if (\n !row.thread_id ||\n !row.trigger_message_id ||\n !row.parent_run_id ||\n !row.spawn_key ||\n row.spec === null\n ) {\n throw new Error(`[SixbSqlite] Subagent run '${row.id}' has invalid persisted fields.`)\n }\n return {\n ...base,\n kind: \"subagent\",\n threadId: row.thread_id,\n triggerMessageId: row.trigger_message_id,\n parentRunId: row.parent_run_id,\n spawnKey: row.spawn_key,\n spec: JSON.parse(row.spec) as SubagentRunSpec,\n ...(row.result === null ? {} : { result: JSON.parse(row.result) as SubagentRunResult }),\n }\n}\n\nexport function rowToMessageRecord(row: AgentMessageRow): AgentMessageRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n threadId: row.thread_id,\n runId: row.run_id,\n role: row.role,\n authorPrincipal: principalFromColumns(row.author_principal_type, row.author_principal_id),\n seq: row.seq,\n parts: JSON.parse(row.parts) as AgentMessagePart[],\n // A null/absent column and an explicit JSON `null` both mean \"no metadata\" (jsonb cannot tell\n // SQL NULL from a json null on read, so both backends normalise to `undefined` for parity).\n metadata: row.metadata === null ? undefined : (JSON.parse(row.metadata) ?? undefined),\n contentVersion: row.content_version,\n createdAt: new Date(row.created_at),\n completedAt: row.completed_at ? new Date(row.completed_at) : undefined,\n }\n}\n\nexport function rowToContextCheckpointRecord(\n row: AgentContextCheckpointRow\n): AgentContextCheckpointRecord {\n if (row.summary_format_version !== 1) {\n throw new Error(\n `[SixbSqlite] Unsupported agent context checkpoint summary format version '${row.summary_format_version}'.`\n )\n }\n return {\n id: row.id,\n projectId: row.project_id,\n threadId: row.thread_id,\n createdByRunId: row.created_by_run_id,\n previousCheckpointId: row.previous_checkpoint_id ?? undefined,\n reason: row.reason,\n summary: row.summary,\n summaryFormatVersion: 1,\n summarizedThroughSeq: row.summarized_through_seq,\n observedHeadSeq: row.observed_head_seq,\n estimatedInputTokensBefore: row.estimated_input_tokens_before,\n estimatedInputTokensAfter: row.estimated_input_tokens_after,\n summaryModelId: row.summary_model_id,\n createdAt: new Date(row.created_at),\n }\n}\n\nexport function rowToParticipantRecord(\n row: AgentThreadParticipantRow\n): AgentThreadParticipantRecord {\n return {\n projectId: row.project_id,\n threadId: row.thread_id,\n principal: { type: \"user\", id: row.principal_id },\n addedAt: new Date(row.added_at),\n addedBy: { type: row.added_by_type, id: row.added_by_id },\n }\n}\n\nfunction principalFromColumns(\n type: Principal[\"type\"] | null | undefined,\n id: string | null | undefined\n): Principal | undefined {\n return type && id ? { type, id } : undefined\n}\n\n// ── offset pagination (threads / messages order by their own column, not started_at) ─────────────\n\nexport function queryAgentList<TRow>(input: {\n readonly db: Database\n readonly table: \"agent_threads\" | \"agent_messages\"\n readonly whereClauses: readonly string[]\n readonly args: readonly SqliteValue[]\n readonly orderBy: string\n readonly limit?: number\n readonly offset?: number\n}): { readonly rows: readonly TRow[]; readonly total: number; readonly hasMore: boolean } {\n const where = `WHERE ${input.whereClauses.join(\" AND \")}`\n const offset = input.offset ?? 0\n\n const totalRow = input.db\n .query(`SELECT COUNT(*) AS count FROM ${input.table} ${where}`)\n .get(...input.args) as { count: number }\n\n let query = `SELECT * FROM ${input.table} ${where} ORDER BY ${input.orderBy}`\n const queryArgs = [...input.args]\n\n if (input.limit !== undefined) {\n query += \" LIMIT ? OFFSET ?\"\n queryArgs.push(input.limit, offset)\n } else if (offset > 0) {\n query += \" LIMIT -1 OFFSET ?\"\n queryArgs.push(offset)\n }\n\n const rows = input.db.query(query).all(...queryArgs) as TRow[]\n const total = totalRow.count\n return { rows, total, hasMore: offset + rows.length < total }\n}\n",
12
+ "import type { Database } from \"bun:sqlite\"\nimport {\n agentContextCheckpointMatchesCreateInput,\n assertAgentContextCheckpointAnchors,\n assertAgentContextCheckpointAuthority,\n assertAgentContextCheckpointReplayState,\n assertCreateAgentContextCheckpointInput,\n} from \"@sixb/core/internal/agent-run-storage-provider\"\nimport {\n type AgentContextCheckpointRecord,\n type AgentContextCheckpointStore,\n AgentStorageError,\n type CreateAgentContextCheckpointInput,\n} from \"@sixb/core/storage\"\nimport {\n type AgentContextCheckpointRow,\n type AgentMessageRow,\n type AgentRunRow,\n type AgentThreadRow,\n rowToContextCheckpointRecord,\n rowToMessageRecord,\n rowToRunRecord,\n rowToThreadRecord,\n} from \"./rows\"\n\nconst SQLITE_CHECKPOINT_RUN_ID_BATCH_SIZE = 500\n\nexport class SqliteAgentContextCheckpointStore implements AgentContextCheckpointStore {\n constructor(private readonly db: Database) {}\n\n async create(input: CreateAgentContextCheckpointInput): Promise<AgentContextCheckpointRecord> {\n assertCreateAgentContextCheckpointInput(input, \"SixbSqlite\")\n\n return this.db.transaction(() => {\n const runRow = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.createdByRunId) as AgentRunRow | null\n const threadRow = this.db\n .query(\"SELECT * FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.threadId) as AgentThreadRow | null\n assertAgentContextCheckpointAuthority({\n create: input,\n run: runRow ? rowToRunRecord(runRow) : null,\n thread: threadRow ? rowToThreadRecord(threadRow) : null,\n prefix: \"SixbSqlite\",\n })\n\n const latest = this.findLatest(input.projectId, input.threadId)\n const headRow = this.db\n .query(\n \"SELECT COALESCE(MAX(seq), 0) AS seq FROM agent_messages WHERE project_id = ? AND thread_id = ?\"\n )\n .get(input.projectId, input.threadId) as { seq: number }\n\n const existingForRun = this.db\n .query(\n \"SELECT * FROM agent_context_checkpoints WHERE project_id = ? AND thread_id = ? AND created_by_run_id = ?\"\n )\n .get(\n input.projectId,\n input.threadId,\n input.createdByRunId\n ) as AgentContextCheckpointRow | null\n if (existingForRun) {\n const record = rowToContextCheckpointRecord(existingForRun)\n if (agentContextCheckpointMatchesCreateInput(record, input)) {\n assertAgentContextCheckpointReplayState({\n create: input,\n existing: record,\n latest,\n headSeq: headRow.seq,\n prefix: \"SixbSqlite\",\n })\n return record\n }\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Agent run '${input.createdByRunId}' already created a different context checkpoint.`\n )\n }\n\n const duplicateId = this.db\n .query(\"SELECT 1 FROM agent_context_checkpoints WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id)\n if (duplicateId) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Agent context checkpoint '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n const firstRetainedRow = this.db\n .query(\n \"SELECT * FROM agent_messages WHERE project_id = ? AND thread_id = ? AND seq > ? ORDER BY seq ASC LIMIT 1\"\n )\n .get(input.projectId, input.threadId, input.summarizedThroughSeq) as AgentMessageRow | null\n assertAgentContextCheckpointAnchors({\n create: input,\n latest,\n headSeq: headRow.seq,\n firstRetained: firstRetainedRow ? rowToMessageRecord(firstRetainedRow) : null,\n prefix: \"SixbSqlite\",\n })\n\n const createdAt = input.createdAt ?? new Date()\n this.db\n .query(\n `\n INSERT INTO agent_context_checkpoints (\n project_id,\n id,\n thread_id,\n created_by_run_id,\n previous_checkpoint_id,\n reason,\n summary,\n summary_format_version,\n summarized_through_seq,\n observed_head_seq,\n estimated_input_tokens_before,\n estimated_input_tokens_after,\n summary_model_id,\n created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.threadId,\n input.createdByRunId,\n input.expectedPreviousCheckpointId,\n input.reason,\n input.summary,\n input.summaryFormatVersion,\n input.summarizedThroughSeq,\n input.observedHeadSeq,\n input.estimatedInputTokensBefore,\n input.estimatedInputTokensAfter,\n input.summaryModelId,\n createdAt.toISOString()\n )\n\n return this.requireById(input.projectId, input.id)\n })()\n }\n\n async getLatest(input: {\n readonly projectId: string\n readonly threadId: string\n }): Promise<AgentContextCheckpointRecord | null> {\n return this.findLatest(input.projectId, input.threadId)\n }\n\n async getByRunIds(input: {\n readonly projectId: string\n readonly threadId: string\n readonly runIds: readonly string[]\n }): Promise<readonly AgentContextCheckpointRecord[]> {\n const runIds = [...new Set(input.runIds)]\n if (runIds.length === 0) return []\n\n const rows: AgentContextCheckpointRow[] = []\n for (let offset = 0; offset < runIds.length; offset += SQLITE_CHECKPOINT_RUN_ID_BATCH_SIZE) {\n const batch = runIds.slice(offset, offset + SQLITE_CHECKPOINT_RUN_ID_BATCH_SIZE)\n const placeholders = batch.map(() => \"?\").join(\", \")\n rows.push(\n ...(this.db\n .query(\n `SELECT * FROM agent_context_checkpoints WHERE project_id = ? AND thread_id = ? AND created_by_run_id IN (${placeholders})`\n )\n .all(input.projectId, input.threadId, ...batch) as AgentContextCheckpointRow[])\n )\n }\n const byRunId = new Map(\n rows.map((row) => [row.created_by_run_id, rowToContextCheckpointRecord(row)] as const)\n )\n return runIds.flatMap((runId) => {\n const checkpoint = byRunId.get(runId)\n return checkpoint ? [checkpoint] : []\n })\n }\n\n private findLatest(projectId: string, threadId: string): AgentContextCheckpointRecord | null {\n const row = this.db\n .query(\n `\n SELECT * FROM agent_context_checkpoints\n WHERE project_id = ? AND thread_id = ?\n ORDER BY summarized_through_seq DESC, created_at DESC, id DESC\n LIMIT 1\n `\n )\n .get(projectId, threadId) as AgentContextCheckpointRow | null\n return row ? rowToContextCheckpointRecord(row) : null\n }\n\n private requireById(projectId: string, id: string): AgentContextCheckpointRecord {\n const row = this.db\n .query(\"SELECT * FROM agent_context_checkpoints WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentContextCheckpointRow | null\n if (!row) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Failed to load agent context checkpoint '${id}' for project '${projectId}'.`\n )\n }\n return rowToContextCheckpointRecord(row)\n }\n}\n",
13
+ "import type { Database } from \"bun:sqlite\"\nimport type { Principal } from \"@sixb/core\"\nimport {\n agentMemoryConflicts,\n agentMemoryHistoryCutoff,\n assertSaveAgentMemoryInput,\n type LatestAgentMemoryFile,\n} from \"@sixb/core/internal/agent-run-storage-provider\"\nimport type {\n AgentMemoryRepoRecord,\n AgentMemoryRevisionRecord,\n AgentMemoryStore,\n ListAgentMemoryRevisionsInput,\n ListAgentMemoryRevisionsResult,\n SaveAgentMemoryInput,\n SaveAgentMemoryResult,\n} from \"@sixb/core/storage\"\nimport { runImmediateTransaction } from \"../transactions\"\n\ninterface RevisionRow {\n readonly revision: number\n readonly message: string\n readonly author_principal_type: Principal[\"type\"]\n readonly author_principal_id: string\n readonly source: string | null\n readonly created_at: string\n}\n\n/** Each path's highest-revision version, the deleted ones included. */\nconst LATEST_FILES = `\n SELECT f.path, f.revision, f.contents FROM agent_memory_files f\n WHERE f.project_id = ? AND f.repo_id = ? AND f.revision = (\n SELECT MAX(l.revision) FROM agent_memory_files l\n WHERE l.project_id = f.project_id AND l.repo_id = f.repo_id AND l.path = f.path\n )\n`\n\nexport class SqliteAgentMemoryStore implements AgentMemoryStore {\n constructor(private readonly db: Database) {}\n\n async get(input: {\n projectId: string\n repoId: string\n asOf?: Date\n revision?: number\n }): Promise<AgentMemoryRepoRecord> {\n return this.db.transaction(() => {\n const revision = this.head(input.projectId, input.repoId, input.asOf, input.revision)\n const files = this.db\n .query(\n `SELECT f.path, f.contents FROM agent_memory_files f\n WHERE f.project_id = ? AND f.repo_id = ? AND f.contents IS NOT NULL AND f.revision = (\n SELECT MAX(l.revision) FROM agent_memory_files l\n WHERE l.project_id = f.project_id AND l.repo_id = f.repo_id AND l.path = f.path\n AND l.revision <= ?\n )\n ORDER BY f.path`\n )\n .all(input.projectId, input.repoId, revision) as { path: string; contents: string }[]\n return { revision, files: files.map(({ path, contents }) => ({ path, contents })) }\n })()\n }\n\n async save(input: SaveAgentMemoryInput): Promise<SaveAgentMemoryResult> {\n assertSaveAgentMemoryInput(input, \"SixbSqlite\")\n return runImmediateTransaction(this.db, () => {\n const head = this.head(input.projectId, input.repoId)\n const paths = input.changes.map((change) => change.path)\n const latest = this.db\n .query(`${LATEST_FILES} AND f.path IN (${paths.map(() => \"?\").join(\", \")})`)\n .all(input.projectId, input.repoId, ...paths) as (LatestAgentMemoryFile & {\n path: string\n })[]\n const conflicts = agentMemoryConflicts(\n input,\n head,\n new Map(latest.map((file) => [file.path, file]))\n )\n if (conflicts.length > 0) return { saved: false, revision: head, conflicts }\n\n const revision = head + 1\n const createdAt = input.createdAt ?? new Date()\n this.db\n .query(\n `INSERT INTO agent_memory_revisions (\n project_id, repo_id, revision, message, author_principal_type, author_principal_id,\n source, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`\n )\n .run(\n input.projectId,\n input.repoId,\n revision,\n input.message,\n input.author.type,\n input.author.id,\n input.source ?? null,\n createdAt.toISOString()\n )\n const insertFile = this.db.query(\n `INSERT INTO agent_memory_files (project_id, repo_id, path, revision, contents)\n VALUES (?, ?, ?, ?, ?)`\n )\n for (const change of input.changes) {\n insertFile.run(input.projectId, input.repoId, change.path, revision, change.contents)\n }\n this.db\n .query(\n `DELETE FROM agent_memory_files AS f\n WHERE f.project_id = ? AND f.repo_id = ? AND f.revision IN (\n SELECT revision FROM agent_memory_revisions\n WHERE project_id = ? AND repo_id = ? AND created_at < ?\n ) AND EXISTS (\n SELECT 1 FROM agent_memory_files n\n WHERE n.project_id = f.project_id AND n.repo_id = f.repo_id AND n.path = f.path\n AND n.revision > f.revision\n )`\n )\n .run(\n input.projectId,\n input.repoId,\n input.projectId,\n input.repoId,\n agentMemoryHistoryCutoff(createdAt).toISOString()\n )\n return { saved: true, revision }\n })\n }\n\n async listRevisions(\n input: ListAgentMemoryRevisionsInput\n ): Promise<ListAgentMemoryRevisionsResult> {\n return this.db.transaction(() => {\n const { total } = this.db\n .query(\n \"SELECT COUNT(*) AS total FROM agent_memory_revisions WHERE project_id = ? AND repo_id = ?\"\n )\n .get(input.projectId, input.repoId) as { total: number }\n const offset = input.offset ?? 0\n const rows = this.db\n .query(\n `SELECT revision, message, author_principal_type, author_principal_id, source, created_at\n FROM agent_memory_revisions WHERE project_id = ? AND repo_id = ?\n ORDER BY revision DESC LIMIT ? OFFSET ?`\n )\n .all(input.projectId, input.repoId, input.limit ?? -1, offset) as RevisionRow[]\n const changes = this.db\n .query(\n `SELECT revision, path, contents IS NULL AS deleted FROM agent_memory_files\n WHERE project_id = ? AND repo_id = ? AND revision IN (${rows.map(() => \"?\").join(\", \")})\n ORDER BY path`\n )\n .all(input.projectId, input.repoId, ...rows.map((row) => row.revision)) as {\n revision: number\n path: string\n deleted: number\n }[]\n const revisions = rows.map(\n (row): AgentMemoryRevisionRecord => ({\n revision: row.revision,\n message: row.message,\n author: { type: row.author_principal_type, id: row.author_principal_id },\n ...(row.source === null ? {} : { source: row.source }),\n changes: changes\n .filter((change) => change.revision === row.revision)\n .map((change) => ({ path: change.path, deleted: change.deleted === 1 })),\n createdAt: new Date(row.created_at),\n })\n )\n return { revisions, hasMore: offset + rows.length < total, total }\n })()\n }\n\n async delete(input: { projectId: string; repoId: string }): Promise<void> {\n // File versions go with their revisions through ON DELETE CASCADE.\n this.db\n .query(\"DELETE FROM agent_memory_revisions WHERE project_id = ? AND repo_id = ?\")\n .run(input.projectId, input.repoId)\n }\n\n /** The highest revision, or the highest saved by `asOf` and up to `upTo`. */\n private head(projectId: string, repoId: string, asOf?: Date, upTo?: number): number {\n const at = asOf?.toISOString() ?? null\n const row = this.db\n .query(\n `SELECT COALESCE(MAX(revision), 0) AS revision FROM agent_memory_revisions\n WHERE project_id = ? AND repo_id = ? AND (? IS NULL OR created_at <= ?)\n AND (? IS NULL OR revision <= ?)`\n )\n .get(projectId, repoId, at, at, upTo ?? null, upTo ?? null) as {\n revision: number\n }\n return row.revision\n }\n}\n",
14
+ "import type { Database } from \"bun:sqlite\"\nimport { countsAsThreadMessage } from \"@sixb/core/internal/agent-run-storage-provider\"\nimport { AGENT_MESSAGE_CONTENT_VERSION } from \"@sixb/core/internal/agents\"\nimport {\n type AgentMessageRecord,\n type AgentMessageStore,\n AgentStorageError,\n type AppendAgentMessageInput,\n type DeleteAgentMessagesByRunInput,\n type ListAgentMessagesInput,\n type ListAgentMessagesResult,\n} from \"@sixb/core/storage\"\nimport type { SqliteValue } from \"../run-list-query\"\nimport { isUniqueConstraintError } from \"../storage-errors\"\nimport { type AgentMessageRow, queryAgentList, rowToMessageRecord } from \"./rows\"\n\nexport class SqliteAgentMessageStore implements AgentMessageStore {\n constructor(private readonly db: Database) {}\n\n async append(input: AppendAgentMessageInput): Promise<AgentMessageRecord> {\n const createdAt = input.createdAt ?? new Date()\n\n return this.db.transaction(() => {\n const thread = this.db\n .query(\"SELECT 1 AS present FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.threadId) as { present: number } | null\n\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[SixbSqlite] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n\n if (input.runId !== null) {\n const run = this.db\n .query(\"SELECT 1 AS present FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.runId) as { present: number } | null\n\n if (!run) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[SixbSqlite] Agent run '${input.runId}' not found for project '${input.projectId}'.`\n )\n }\n }\n\n const seqRow = this.db\n .query(\n \"SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM agent_messages WHERE project_id = ? AND thread_id = ?\"\n )\n .get(input.projectId, input.threadId) as { next: number }\n\n try {\n this.db\n .query(\n `\n INSERT INTO agent_messages (\n project_id,\n id,\n thread_id,\n run_id,\n role,\n author_principal_type,\n author_principal_id,\n seq,\n parts,\n metadata,\n content_version,\n created_at,\n completed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.threadId,\n input.runId,\n input.role,\n input.authorPrincipal?.type ?? null,\n input.authorPrincipal?.id ?? null,\n seqRow.next,\n JSON.stringify(input.parts),\n input.metadata === undefined ? null : JSON.stringify(input.metadata),\n AGENT_MESSAGE_CONTENT_VERSION,\n createdAt.toISOString(),\n input.completedAt ? input.completedAt.toISOString() : null\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Agent message '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n throw error\n }\n\n this.db\n .query(\n `\n UPDATE agent_threads\n SET message_count = message_count + ?, last_message_at = ?, updated_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n countsAsThreadMessage(input) ? 1 : 0,\n createdAt.toISOString(),\n createdAt.toISOString(),\n input.projectId,\n input.threadId\n )\n\n return this.requireMessage(input.projectId, input.id)\n })()\n }\n\n async deleteByRunId(input: DeleteAgentMessagesByRunInput): Promise<number> {\n return this.db.transaction(() => {\n const thread = this.db\n .query(\"SELECT 1 AS present FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.threadId) as { present: number } | null\n\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[SixbSqlite] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n\n const deleted = this.db\n .query(\n \"DELETE FROM agent_messages WHERE project_id = ? AND thread_id = ? AND run_id = ? RETURNING parts\"\n )\n .all(input.projectId, input.threadId, input.runId) as { parts: string }[]\n if (deleted.length === 0) {\n return 0\n }\n // The thread counts only the messages the conversation shows: take back the ones it counted.\n const counted = deleted.filter((row) =>\n countsAsThreadMessage({ parts: JSON.parse(row.parts) })\n ).length\n\n const updatedAt = new Date().toISOString()\n this.db\n .query(\n `\n UPDATE agent_threads\n SET\n message_count = MAX(message_count - ?, 0),\n last_message_at = (\n SELECT created_at FROM agent_messages\n WHERE project_id = ? AND thread_id = ?\n ORDER BY seq DESC\n LIMIT 1\n ),\n updated_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(counted, input.projectId, input.threadId, updatedAt, input.projectId, input.threadId)\n\n return deleted.length\n })()\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentMessageRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM agent_messages WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as AgentMessageRow | null\n\n return row ? rowToMessageRecord(row) : null\n }\n\n async list(input: ListAgentMessagesInput): Promise<ListAgentMessagesResult> {\n if (input.roles !== undefined && input.roles.length === 0) {\n return { messages: [], hasMore: false, total: 0 }\n }\n\n const whereClauses = [\"project_id = ?\", \"thread_id = ?\"]\n const args: SqliteValue[] = [input.projectId, input.threadId]\n\n if (input.afterSeq !== undefined) {\n whereClauses.push(\"seq > ?\")\n args.push(input.afterSeq)\n }\n\n if (input.roles) {\n whereClauses.push(`role IN (${input.roles.map(() => \"?\").join(\", \")})`)\n args.push(...input.roles)\n }\n\n const dir = input.order === \"desc\" ? \"DESC\" : \"ASC\"\n const { rows, total, hasMore } = queryAgentList<AgentMessageRow>({\n db: this.db,\n table: \"agent_messages\",\n whereClauses,\n args,\n orderBy: `seq ${dir}`,\n limit: input.limit,\n offset: input.offset,\n })\n\n return { messages: rows.map(rowToMessageRecord), hasMore, total }\n }\n\n private requireMessage(projectId: string, id: string): AgentMessageRecord {\n const row = this.db\n .query(\"SELECT * FROM agent_messages WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentMessageRow | null\n\n if (!row) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Failed to load agent message '${id}' for project '${projectId}'.`\n )\n }\n\n return rowToMessageRecord(row)\n }\n}\n",
13
15
  "export function isUniqueConstraintError(error: unknown): boolean {\n return error instanceof Error && error.message.includes(\"UNIQUE constraint failed\")\n}\n\nexport function isForeignKeyConstraintError(error: unknown): boolean {\n return error instanceof Error && error.message.includes(\"FOREIGN KEY constraint failed\")\n}\n",
14
- "import type { Database } from \"bun:sqlite\"\nimport {\n assertAgentRunExecution,\n assertConversationAgentRunSpec,\n assertCreateSubagentRunInput,\n assertSubagentRunResult,\n subagentRunMatchesCreateInput,\n} from \"@sixb/core/internal/agent-run-storage-provider\"\nimport { serializeSixbFailure } from \"@sixb/core/internal/errors\"\nimport {\n AGENT_RUN_FAILURE_CODES,\n type AgentRunRecord,\n type AgentRunStore,\n AgentStorageError,\n type ConfirmAgentRunExecutionOwnershipInput,\n type ConversationAgentRunRecord,\n type CreateAgentRunInput,\n type CreateSubagentRunInput,\n type ExecutionStorage,\n type FinishAgentRunInput,\n type FinishQueuedAgentRunInput,\n type ListAgentRunsInput,\n type ListAgentRunsResult,\n type ReclaimAgentRunInput,\n type StartAgentRunInput,\n type SubagentRunRecord,\n} from \"@sixb/core/storage\"\nimport {\n appendRunListFilters,\n hasEmptyStatuses,\n queryRunList,\n type SqliteValue,\n} from \"../run-list-query\"\nimport { isUniqueConstraintError } from \"../storage-errors\"\nimport { type AgentRunRow, rowToRunRecord } from \"./rows\"\n\nconst SQLITE_RUN_ID_BATCH_SIZE = 500\n\nexport class SqliteAgentRunStore implements AgentRunStore {\n constructor(\n private readonly db: Database,\n private readonly executions: ExecutionStorage\n ) {}\n\n async create(input: CreateAgentRunInput): Promise<ConversationAgentRunRecord> {\n assertConversationAgentRunSpec(input.spec, \"SixbSqlite\")\n const createdAt = input.createdAt ?? new Date()\n await assertAgentRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n })\n\n return this.db.transaction(() => {\n const thread = this.db\n .query(\"SELECT active_run_id FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.threadId) as { active_run_id: string | null } | null\n\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[SixbSqlite] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n if (thread.active_run_id !== null) {\n throw new AgentStorageError(\n \"active_run_exists\",\n `[SixbSqlite] Agent thread '${input.threadId}' already has an active run '${thread.active_run_id}'.`\n )\n }\n\n try {\n this.db\n .query(\n `\n INSERT INTO agent_runs (\n project_id,\n id,\n execution_id,\n kind,\n thread_id,\n trigger_message_id,\n spec,\n status,\n attempt,\n created_at\n ) VALUES (?, ?, ?, 'conversation', ?, ?, ?, 'queued', 0, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.executionId,\n input.threadId,\n input.triggerMessageId,\n JSON.stringify(input.spec),\n createdAt.toISOString()\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Agent run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n throw error\n }\n\n this.db\n .query(\n \"UPDATE agent_threads SET active_run_id = ?, updated_at = ? WHERE project_id = ? AND id = ?\"\n )\n .run(input.id, createdAt.toISOString(), input.projectId, input.threadId)\n\n const created = this.requireRun(input.projectId, input.id)\n if (created.kind !== \"conversation\") {\n throw new Error(`[SixbSqlite] Agent run insert '${input.id}' returned the wrong run kind.`)\n }\n return created\n })()\n }\n\n async createSubagent(input: CreateSubagentRunInput): Promise<SubagentRunRecord> {\n assertCreateSubagentRunInput(input, \"SixbSqlite\")\n const execution = await assertAgentRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n })\n\n return this.db.transaction(() => {\n const parentRow = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.parentRunId) as AgentRunRow | null\n if (!parentRow || parentRow.kind !== \"conversation\") {\n throw new AgentStorageError(\n \"run_not_found\",\n `[SixbSqlite] Parent Agent run '${input.parentRunId}' was not found.`\n )\n }\n\n const existingRow = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as AgentRunRow | null\n if (existingRow) {\n const existing = rowToRunRecord(existingRow)\n if (subagentRunMatchesCreateInput(existing, input)) return existing\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Subagent run '${input.id}' already exists with different immutable inputs.`\n )\n }\n if (parentRow.status !== \"running\") {\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Parent Agent run '${parentRow.id}' is not running (status '${parentRow.status}').`\n )\n }\n if (\n execution.source.type !== \"execution\" ||\n execution.source.executionId !== parentRow.execution_id\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[SixbSqlite] Subagent execution '${execution.id}' is not a child of parent execution '${parentRow.execution_id}'.`\n )\n }\n if (parentRow.execution_token !== input.parentExecutionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[SixbSqlite] Parent Agent run '${parentRow.id}' is no longer owned by this execution.`\n )\n }\n\n const count = this.db\n .query(\n `SELECT COUNT(*) AS count FROM agent_runs\n WHERE project_id = ? AND parent_run_id = ? AND status IN ('queued', 'running')`\n )\n .get(input.projectId, input.parentRunId) as { count: number }\n if (count.count >= input.maxActiveChildren) {\n throw new AgentStorageError(\n \"active_child_limit\",\n `[SixbSqlite] Agent run '${parentRow.id}' already has ${count.count} active subagents.`\n )\n }\n\n try {\n this.db\n .query(\n `\n INSERT INTO agent_runs (\n project_id, id, execution_id, kind, parent_run_id, spawn_key, spec,\n status, attempt, created_at\n ) VALUES (?, ?, ?, 'subagent', ?, ?, ?, 'queued', 0, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.executionId,\n input.parentRunId,\n input.spawnKey,\n JSON.stringify(input.spec),\n (input.createdAt ?? new Date()).toISOString()\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Subagent run '${input.id}' conflicts with an existing durable spawn.`\n )\n }\n throw error\n }\n\n const created = this.requireRun(input.projectId, input.id)\n if (created.kind !== \"subagent\") {\n throw new Error(`[SixbSqlite] Subagent insert '${input.id}' returned the wrong run kind.`)\n }\n return created\n })()\n }\n\n async start(input: StartAgentRunInput): Promise<AgentRunRecord> {\n const startedAt = input.startedAt ?? new Date()\n return this.db.transaction(() => {\n this.requireStatus(input.projectId, input.id, \"queued\")\n this.db\n .query(\n `\n UPDATE agent_runs\n SET\n status = 'running',\n model_id = ?,\n attempt = 1,\n execution_token = ?,\n execution_queue_lease_expires_at = ?,\n started_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.modelId ?? null,\n input.execution.token,\n input.execution.queueLeaseExpiresAt.toISOString(),\n startedAt.toISOString(),\n input.projectId,\n input.id\n )\n\n return this.requireRun(input.projectId, input.id)\n })()\n }\n\n async finishQueued(input: FinishQueuedAgentRunInput): Promise<AgentRunRecord> {\n const completedAt = input.completedAt ?? new Date()\n return this.db.transaction(() => {\n const run = this.requireStatus(input.projectId, input.id, \"queued\")\n this.db\n .query(\n `\n UPDATE agent_runs\n SET status = ?, error = ?, completed_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.status,\n input.error === undefined\n ? null\n : serializeSixbFailure(input.error, AGENT_RUN_FAILURE_CODES),\n completedAt.toISOString(),\n input.projectId,\n input.id\n )\n this.releaseThread(run, completedAt)\n return this.requireRun(input.projectId, input.id)\n })()\n }\n\n async reclaim(input: ReclaimAgentRunInput): Promise<AgentRunRecord> {\n return this.db.transaction(() => {\n this.requireRunning(input.projectId, input.id)\n this.db\n .query(\n `\n UPDATE agent_runs\n SET\n attempt = attempt + 1,\n execution_token = ?,\n execution_queue_lease_expires_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.execution.token,\n input.execution.queueLeaseExpiresAt.toISOString(),\n input.projectId,\n input.id\n )\n\n return this.requireRun(input.projectId, input.id)\n })()\n }\n\n async confirmExecutionOwnership(\n input: ConfirmAgentRunExecutionOwnershipInput\n ): Promise<AgentRunRecord> {\n return this.db.transaction(() => {\n const run = this.requireRunning(input.projectId, input.id)\n if (run.execution_token !== input.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[SixbSqlite] Execution token is no longer current on agent run '${input.id}'.`\n )\n }\n this.db\n .query(\n `\n UPDATE agent_runs\n SET execution_queue_lease_expires_at = MAX(execution_queue_lease_expires_at, ?)\n WHERE project_id = ? AND id = ?\n `\n )\n .run(input.queueLeaseExpiresAt.toISOString(), input.projectId, input.id)\n return this.requireRun(input.projectId, input.id)\n })()\n }\n\n async finish(input: FinishAgentRunInput): Promise<AgentRunRecord> {\n const completedAt = input.completedAt ?? new Date()\n const errorValue =\n input.status === \"succeeded\" || input.error === undefined\n ? null\n : serializeSixbFailure(input.error, AGENT_RUN_FAILURE_CODES)\n\n return this.db.transaction(() => {\n const run = this.requireRunning(input.projectId, input.id)\n\n if (run.execution_token !== input.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[SixbSqlite] Execution token is no longer current on agent run '${input.id}'.`\n )\n }\n if (input.status === \"succeeded\" && run.kind === \"subagent\") {\n assertSubagentRunResult(input.result, run.id, \"SixbSqlite\")\n }\n if (\n input.status === \"succeeded\" &&\n run.kind === \"conversation\" &&\n input.result !== undefined\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[SixbSqlite] Conversational Agent run '${run.id}' cannot persist a subagent result.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE agent_runs\n SET\n status = ?,\n model_id = COALESCE(?, model_id),\n finish_reason = ?,\n error = ?,\n diagnostics = ?,\n result = ?,\n execution_token = NULL,\n execution_queue_lease_expires_at = NULL,\n completed_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.status,\n input.modelId ?? null,\n input.finishReason ?? null,\n errorValue,\n input.diagnostics === undefined ? null : JSON.stringify(input.diagnostics),\n input.status === \"succeeded\" && input.result !== undefined\n ? JSON.stringify(input.result)\n : null,\n completedAt.toISOString(),\n input.projectId,\n input.id\n )\n\n this.releaseThread(run, completedAt)\n\n return this.requireRun(input.projectId, input.id)\n })()\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentRunRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as AgentRunRow | null\n\n return row ? rowToRunRecord(row) : null\n }\n\n async getByIds(params: {\n projectId: string\n ids: readonly string[]\n }): Promise<readonly AgentRunRecord[]> {\n const ids = [...new Set(params.ids)]\n if (ids.length === 0) {\n return []\n }\n\n const rows: AgentRunRow[] = []\n for (let offset = 0; offset < ids.length; offset += SQLITE_RUN_ID_BATCH_SIZE) {\n const batch = ids.slice(offset, offset + SQLITE_RUN_ID_BATCH_SIZE)\n const placeholders = batch.map(() => \"?\").join(\", \")\n rows.push(\n ...(this.db\n .query(`SELECT * FROM agent_runs WHERE project_id = ? AND id IN (${placeholders})`)\n .all(params.projectId, ...batch) as AgentRunRow[])\n )\n }\n const byId = new Map(rows.map((row) => [row.id, rowToRunRecord(row)]))\n return ids.flatMap((id) => {\n const run = byId.get(id)\n return run ? [run] : []\n })\n }\n\n async list(input: ListAgentRunsInput): Promise<ListAgentRunsResult> {\n if (hasEmptyStatuses(input) || input.kinds?.length === 0) {\n return { runs: [], hasMore: false, total: 0 }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n\n if (input.kinds) {\n whereClauses.push(`kind IN (${input.kinds.map(() => \"?\").join(\", \")})`)\n args.push(...input.kinds)\n }\n\n if (input.threadId) {\n whereClauses.push(\"thread_id = ?\")\n args.push(input.threadId)\n }\n\n if (input.parentRunId) {\n whereClauses.push(\"parent_run_id = ?\")\n args.push(input.parentRunId)\n }\n\n appendRunListFilters(whereClauses, args, input, \"COALESCE(started_at, created_at)\")\n\n const { rows, total, hasMore } = queryRunList<AgentRunRow>({\n db: this.db,\n tableName: \"agent_runs\",\n whereClauses,\n args,\n order: input.order,\n limit: input.limit,\n offset: input.offset,\n })\n\n return { runs: rows.map(rowToRunRecord), hasMore, total }\n }\n\n private requireRunning(projectId: string, id: string): AgentRunRow {\n return this.requireStatus(projectId, id, \"running\")\n }\n\n private requireStatus(\n projectId: string,\n id: string,\n status: AgentRunRecord[\"status\"]\n ): AgentRunRow {\n const row = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentRunRow | null\n\n if (!row) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[SixbSqlite] Agent run '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (row.status !== status) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Agent run '${id}' is not ${status} (status '${row.status}').`\n )\n }\n\n return row\n }\n\n private releaseThread(run: AgentRunRow, completedAt: Date): void {\n if (run.kind !== \"conversation\") return\n this.db\n .query(\n `\n UPDATE agent_threads\n SET active_run_id = NULL, updated_at = ?\n WHERE project_id = ? AND id = ? AND active_run_id = ?\n `\n )\n .run(completedAt.toISOString(), run.project_id, run.thread_id, run.id)\n }\n\n private requireRun(projectId: string, id: string): AgentRunRecord {\n const row = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentRunRow | null\n\n if (!row) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[SixbSqlite] Agent run '${id}' not found for project '${projectId}'.`\n )\n }\n\n return rowToRunRecord(row)\n }\n}\n",
16
+ "import type { Database } from \"bun:sqlite\"\nimport {\n agentRunMayHoldCalls,\n assertAgentRunExecution,\n assertAgentRunFinishPayload,\n assertAwaitingApprovalFinish,\n assertConversationAgentRunSpec,\n assertConversationThreadRow,\n assertCreateSubagentRunInput,\n assertSubagentThreadTakesRun,\n newSubagentThreadRecord,\n subagentRunMatchesCreateInput,\n} from \"@sixb/core/internal/agent-run-storage-provider\"\nimport { AGENT_MESSAGE_CONTENT_VERSION } from \"@sixb/core/internal/agents\"\nimport { serializeSixbFailure } from \"@sixb/core/internal/errors\"\nimport {\n AGENT_RUN_FAILURE_CODES,\n type AgentRunRecord,\n type AgentRunStore,\n AgentStorageError,\n type ConfirmAgentRunExecutionOwnershipInput,\n type ConversationAgentRunRecord,\n type CreateAgentRunInput,\n type CreateSubagentRunInput,\n type ExecutionStorage,\n type FinishAgentRunInput,\n type FinishQueuedAgentRunInput,\n type ListAgentRunsInput,\n type ListAgentRunsResult,\n type ListThreadSubagentsInput,\n type ReclaimAgentRunInput,\n type StartAgentRunInput,\n type SubagentRunRecord,\n} from \"@sixb/core/storage\"\nimport {\n appendRunListFilters,\n hasEmptyStatuses,\n queryRunList,\n type SqliteValue,\n} from \"../run-list-query\"\nimport { isUniqueConstraintError } from \"../storage-errors\"\nimport { sqliteHoldsRun } from \"./approvals\"\nimport { type AgentRunRow, type AgentThreadRow, rowToRunRecord, rowToThreadRecord } from \"./rows\"\n\nconst SQLITE_RUN_ID_BATCH_SIZE = 500\n\nexport class SqliteAgentRunStore implements AgentRunStore {\n constructor(\n private readonly db: Database,\n private readonly executions: ExecutionStorage\n ) {}\n\n async create(input: CreateAgentRunInput): Promise<ConversationAgentRunRecord> {\n assertConversationAgentRunSpec(input.spec, \"SixbSqlite\")\n const createdAt = input.createdAt ?? new Date()\n await assertAgentRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n })\n\n return this.db.transaction(() => {\n const thread = this.db\n .query(\"SELECT id, kind, active_run_id FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.threadId) as Pick<\n AgentThreadRow,\n \"id\" | \"kind\" | \"active_run_id\"\n > | null\n\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[SixbSqlite] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n assertConversationThreadRow(thread, \"takes turns\", \"SixbSqlite\")\n if (thread.active_run_id !== null) {\n throw new AgentStorageError(\n \"active_run_exists\",\n `[SixbSqlite] Agent thread '${input.threadId}' already has an active run '${thread.active_run_id}'.`\n )\n }\n\n try {\n this.db\n .query(\n `\n INSERT INTO agent_runs (\n project_id,\n id,\n execution_id,\n kind,\n thread_id,\n trigger_message_id,\n spec,\n status,\n attempt,\n created_at\n ) VALUES (?, ?, ?, 'conversation', ?, ?, ?, 'queued', 0, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.executionId,\n input.threadId,\n input.triggerMessageId,\n JSON.stringify(input.spec),\n createdAt.toISOString()\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Agent run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n throw error\n }\n\n this.db\n .query(\n \"UPDATE agent_threads SET active_run_id = ?, updated_at = ? WHERE project_id = ? AND id = ?\"\n )\n .run(input.id, createdAt.toISOString(), input.projectId, input.threadId)\n\n const created = this.requireRun(input.projectId, input.id)\n if (created.kind !== \"conversation\") {\n throw new Error(`[SixbSqlite] Agent run insert '${input.id}' returned the wrong run kind.`)\n }\n return created\n })()\n }\n\n async createSubagent(input: CreateSubagentRunInput): Promise<SubagentRunRecord> {\n assertCreateSubagentRunInput(input, \"SixbSqlite\")\n const execution = await assertAgentRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n })\n\n return this.db.transaction(() => {\n const parentRow = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.parentRunId) as AgentRunRow | null\n if (!parentRow || parentRow.kind !== \"conversation\") {\n throw new AgentStorageError(\n \"run_not_found\",\n `[SixbSqlite] Parent Agent run '${input.parentRunId}' was not found.`\n )\n }\n\n const existingRow = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as AgentRunRow | null\n if (existingRow) {\n const existing = rowToRunRecord(existingRow)\n if (subagentRunMatchesCreateInput(existing, input)) return existing\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Subagent run '${input.id}' already exists with different immutable inputs.`\n )\n }\n if (parentRow.status !== \"running\") {\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Parent Agent run '${parentRow.id}' is not running (status '${parentRow.status}').`\n )\n }\n if (\n execution.source.type !== \"execution\" ||\n execution.source.executionId !== parentRow.execution_id\n ) {\n throw new AgentStorageError(\n \"invalid_input\",\n `[SixbSqlite] Subagent execution '${execution.id}' is not a child of parent execution '${parentRow.execution_id}'.`\n )\n }\n if (parentRow.execution_token !== input.parentExecutionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[SixbSqlite] Parent Agent run '${parentRow.id}' is no longer owned by this execution.`\n )\n }\n\n const count = this.db\n .query(\n `SELECT COUNT(*) AS count FROM agent_runs\n WHERE project_id = ? AND parent_run_id = ? AND status IN ('queued', 'running')`\n )\n .get(input.projectId, input.parentRunId) as { count: number }\n if (count.count >= input.maxActiveChildren) {\n throw new AgentStorageError(\n \"active_child_limit\",\n `[SixbSqlite] Agent run '${parentRow.id}' already has ${count.count} active subagents.`\n )\n }\n\n const createdAt = input.createdAt ?? new Date()\n try {\n this.claimChildThread(input, parentRow, createdAt)\n this.db\n .query(\n `\n INSERT INTO agent_runs (\n project_id, id, execution_id, kind, thread_id, trigger_message_id, parent_run_id,\n spawn_key, spec, status, attempt, created_at\n ) VALUES (?, ?, ?, 'subagent', ?, ?, ?, ?, ?, 'queued', 0, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.executionId,\n input.thread.id,\n input.trigger.id,\n input.parentRunId,\n input.spawnKey,\n JSON.stringify(input.spec),\n createdAt.toISOString()\n )\n this.db\n .query(\n `\n INSERT INTO agent_messages (\n project_id, id, thread_id, run_id, role, seq, parts, metadata, content_version,\n created_at\n ) VALUES (\n ?, ?, ?, ?, 'user',\n (SELECT COALESCE(MAX(seq), 0) + 1 FROM agent_messages\n WHERE project_id = ? AND thread_id = ?),\n ?, ?, ?, ?\n )\n `\n )\n .run(\n input.projectId,\n input.trigger.id,\n input.thread.id,\n input.id,\n input.projectId,\n input.thread.id,\n JSON.stringify(input.trigger.parts),\n input.trigger.metadata === undefined ? null : JSON.stringify(input.trigger.metadata),\n AGENT_MESSAGE_CONTENT_VERSION,\n createdAt.toISOString()\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Subagent run '${input.id}' conflicts with an existing durable spawn.`\n )\n }\n throw error\n }\n\n const created = this.requireRun(input.projectId, input.id)\n if (created.kind !== \"subagent\") {\n throw new Error(`[SixbSqlite] Subagent insert '${input.id}' returned the wrong run kind.`)\n }\n return created\n })()\n }\n\n async start(input: StartAgentRunInput): Promise<AgentRunRecord> {\n const startedAt = input.startedAt ?? new Date()\n return this.db.transaction(() => {\n this.requireStatus(input.projectId, input.id, \"queued\")\n this.db\n .query(\n `\n UPDATE agent_runs\n SET\n status = 'running',\n model_id = ?,\n attempt = 1,\n execution_token = ?,\n execution_queue_lease_expires_at = ?,\n started_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.modelId ?? null,\n input.execution.token,\n input.execution.queueLeaseExpiresAt.toISOString(),\n startedAt.toISOString(),\n input.projectId,\n input.id\n )\n\n return this.requireRun(input.projectId, input.id)\n })()\n }\n\n async finishQueued(input: FinishQueuedAgentRunInput): Promise<AgentRunRecord> {\n const completedAt = input.completedAt ?? new Date()\n return this.db.transaction(() => {\n const run = this.requireStatus(input.projectId, input.id, \"queued\")\n this.db\n .query(\n `\n UPDATE agent_runs\n SET status = ?, error = ?, completed_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.status,\n input.error === undefined\n ? null\n : serializeSixbFailure(input.error, AGENT_RUN_FAILURE_CODES),\n completedAt.toISOString(),\n input.projectId,\n input.id\n )\n this.releaseThread(run, completedAt)\n return this.requireRun(input.projectId, input.id)\n })()\n }\n\n async reclaim(input: ReclaimAgentRunInput): Promise<AgentRunRecord> {\n return this.db.transaction(() => {\n this.requireRunning(input.projectId, input.id)\n this.db\n .query(\n `\n UPDATE agent_runs\n SET\n attempt = attempt + 1,\n execution_token = ?,\n execution_queue_lease_expires_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.execution.token,\n input.execution.queueLeaseExpiresAt.toISOString(),\n input.projectId,\n input.id\n )\n\n return this.requireRun(input.projectId, input.id)\n })()\n }\n\n async confirmExecutionOwnership(\n input: ConfirmAgentRunExecutionOwnershipInput\n ): Promise<AgentRunRecord> {\n return this.db.transaction(() => {\n const run = this.requireRunning(input.projectId, input.id)\n if (run.execution_token !== input.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[SixbSqlite] Execution token is no longer current on agent run '${input.id}'.`\n )\n }\n this.db\n .query(\n `\n UPDATE agent_runs\n SET execution_queue_lease_expires_at = MAX(execution_queue_lease_expires_at, ?)\n WHERE project_id = ? AND id = ?\n `\n )\n .run(input.queueLeaseExpiresAt.toISOString(), input.projectId, input.id)\n return this.requireRun(input.projectId, input.id)\n })()\n }\n\n async finish(input: FinishAgentRunInput): Promise<AgentRunRecord> {\n const completedAt = input.completedAt ?? new Date()\n const errorValue =\n input.status === \"succeeded\" || input.error === undefined\n ? null\n : serializeSixbFailure(input.error, AGENT_RUN_FAILURE_CODES)\n\n return this.db.transaction(() => {\n const run = this.requireRunning(input.projectId, input.id)\n\n if (run.execution_token !== input.executionToken) {\n throw new AgentStorageError(\n \"execution_lost\",\n `[SixbSqlite] Execution token is no longer current on agent run '${input.id}'.`\n )\n }\n assertAgentRunFinishPayload(run.kind, input, run.id, \"SixbSqlite\")\n if (input.finishReason === \"awaiting_approval\") {\n assertAwaitingApprovalFinish({\n runId: input.id,\n status: input.status,\n holdsApproval: sqliteHoldsRun(this.db, input.projectId, input.id),\n prefix: \"SixbSqlite\",\n })\n }\n\n this.db\n .query(\n `\n UPDATE agent_runs\n SET\n status = ?,\n model_id = COALESCE(?, model_id),\n finish_reason = ?,\n error = ?,\n diagnostics = ?,\n result = ?,\n execution_token = NULL,\n execution_queue_lease_expires_at = NULL,\n completed_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.status,\n input.modelId ?? null,\n input.finishReason ?? null,\n errorValue,\n input.diagnostics === undefined ? null : JSON.stringify(input.diagnostics),\n input.status === \"succeeded\" && input.result !== undefined\n ? JSON.stringify(input.result)\n : null,\n completedAt.toISOString(),\n input.projectId,\n input.id\n )\n\n this.releaseThread(run, completedAt)\n if (agentRunMayHoldCalls(rowToRunRecord(run)))\n this.settleApprovals(run.kind, input, completedAt)\n\n return this.requireRun(input.projectId, input.id)\n })()\n }\n\n /**\n * A turn that pauses keeps its calls for their decision. A turn that ends any other way cancels\n * the ones still waiting, a late one included, and never resumes on the rest. A child that fails\n * or is cancelled takes its own pending calls with it.\n */\n private settleApprovals(\n kind: AgentRunRecord[\"kind\"],\n input: FinishAgentRunInput,\n completedAt: Date\n ): void {\n if (input.finishReason === \"awaiting_approval\") return\n const turn = kind === \"conversation\"\n if (!turn && input.status === \"succeeded\") return\n\n this.db\n .query(\n `UPDATE agent_approvals SET status = 'cancelled'\n WHERE project_id = ? AND status = 'pending' AND (run_id = ? OR caller_run_id = ?)`\n )\n .run(input.projectId, input.id, input.id)\n if (!turn) return\n this.db\n .query(\n `UPDATE agent_approvals SET turn_stopped_at = ?\n WHERE project_id = ? AND run_id = ?\n AND reported_in_message_id IS NULL AND turn_stopped_at IS NULL`\n )\n .run(completedAt.toISOString(), input.projectId, input.id)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentRunRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as AgentRunRow | null\n\n return row ? rowToRunRecord(row) : null\n }\n\n async getByIds(params: {\n projectId: string\n ids: readonly string[]\n }): Promise<readonly AgentRunRecord[]> {\n const ids = [...new Set(params.ids)]\n if (ids.length === 0) {\n return []\n }\n\n const rows: AgentRunRow[] = []\n for (let offset = 0; offset < ids.length; offset += SQLITE_RUN_ID_BATCH_SIZE) {\n const batch = ids.slice(offset, offset + SQLITE_RUN_ID_BATCH_SIZE)\n const placeholders = batch.map(() => \"?\").join(\", \")\n rows.push(\n ...(this.db\n .query(`SELECT * FROM agent_runs WHERE project_id = ? AND id IN (${placeholders})`)\n .all(params.projectId, ...batch) as AgentRunRow[])\n )\n }\n const byId = new Map(rows.map((row) => [row.id, rowToRunRecord(row)]))\n return ids.flatMap((id) => {\n const run = byId.get(id)\n return run ? [run] : []\n })\n }\n\n async listThreadSubagents(\n input: ListThreadSubagentsInput\n ): Promise<readonly SubagentRunRecord[]> {\n // Reached through the turns of the conversation, by thread, then each turn's children by key\n // or, for a finish reason, by `idx_agent_runs_paused_on_question`.\n const filters: string[] = []\n const args: SqliteValue[] = [input.projectId, input.threadId]\n if (input.spawnKey !== undefined) {\n filters.push(\"AND child.spawn_key = ?\")\n args.push(input.spawnKey)\n }\n if (input.finishReason !== undefined) {\n filters.push(\"AND child.finish_reason = ?\")\n args.push(input.finishReason)\n }\n args.push(input.limit ?? 100)\n\n const rows = this.db\n .query(\n `SELECT child.* FROM agent_runs turn\n JOIN agent_runs child\n ON child.project_id = turn.project_id AND child.parent_run_id = turn.id\n WHERE turn.project_id = ? AND turn.thread_id = ? AND child.kind = 'subagent'\n ${filters.join(\" \")}\n ORDER BY COALESCE(turn.started_at, turn.created_at) DESC, turn.id DESC,\n child.created_at DESC, child.id DESC\n LIMIT ?`\n )\n .all(...args) as AgentRunRow[]\n return rows.flatMap((row) => {\n const run = rowToRunRecord(row)\n return run.kind === \"subagent\" ? [run] : []\n })\n }\n\n async list(input: ListAgentRunsInput): Promise<ListAgentRunsResult> {\n if (hasEmptyStatuses(input) || input.kinds?.length === 0) {\n return { runs: [], hasMore: false, total: 0 }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n\n if (input.kinds) {\n whereClauses.push(`kind IN (${input.kinds.map(() => \"?\").join(\", \")})`)\n args.push(...input.kinds)\n }\n\n if (input.threadId) {\n whereClauses.push(\"thread_id = ?\")\n args.push(input.threadId)\n }\n\n if (input.parentRunId) {\n whereClauses.push(\"parent_run_id = ?\")\n args.push(input.parentRunId)\n }\n\n appendRunListFilters(whereClauses, args, input, \"COALESCE(started_at, created_at)\")\n\n const { rows, total, hasMore } = queryRunList<AgentRunRow>({\n db: this.db,\n tableName: \"agent_runs\",\n whereClauses,\n args,\n order: input.order,\n limit: input.limit,\n offset: input.offset,\n })\n\n return { runs: rows.map(rowToRunRecord), hasMore, total }\n }\n\n private requireRunning(projectId: string, id: string): AgentRunRow {\n return this.requireStatus(projectId, id, \"running\")\n }\n\n private requireStatus(\n projectId: string,\n id: string,\n status: AgentRunRecord[\"status\"]\n ): AgentRunRow {\n const row = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentRunRow | null\n\n if (!row) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[SixbSqlite] Agent run '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (row.status !== status) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Agent run '${id}' is not ${status} (status '${row.status}').`\n )\n }\n\n return row\n }\n\n /**\n * The child's thread: its first run creates it, owned by the conversation's owner; a later run\n * takes it while it is idle. Either way the run is its active run.\n */\n private claimChildThread(\n input: CreateSubagentRunInput,\n parent: AgentRunRow,\n createdAt: Date\n ): void {\n if (!input.thread.create) {\n const row = this.db\n .query(\"SELECT * FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.thread.id) as AgentThreadRow | null\n assertSubagentThreadTakesRun(\n row ? rowToThreadRecord(row) : null,\n input,\n parent.thread_id ?? \"\",\n \"SixbSqlite\"\n )\n this.db\n .query(\n `\n UPDATE agent_threads\n SET active_run_id = ?, message_count = message_count + 1, last_message_at = ?,\n updated_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.id,\n createdAt.toISOString(),\n createdAt.toISOString(),\n input.projectId,\n input.thread.id\n )\n return\n }\n\n const conversation = this.db\n .query(\"SELECT * FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, parent.thread_id) as AgentThreadRow | null\n if (!conversation) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[SixbSqlite] Agent thread '${parent.thread_id}' not found for project '${input.projectId}'.`\n )\n }\n\n const thread = newSubagentThreadRecord(input, rowToThreadRecord(conversation), createdAt)\n this.db\n .query(\n `\n INSERT INTO agent_threads (\n project_id, id, kind, parent_thread_id, parent_run_id, spawn_key, owner_principal_type,\n owner_principal_id, status, active_run_id, last_message_at, message_count, created_at,\n updated_at\n ) VALUES (?, ?, 'subagent', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n thread.projectId,\n thread.id,\n conversation.id,\n input.parentRunId,\n input.spawnKey,\n thread.ownerPrincipal.type,\n thread.ownerPrincipal.id,\n thread.status,\n input.id,\n createdAt.toISOString(),\n thread.messageCount,\n createdAt.toISOString(),\n createdAt.toISOString()\n )\n }\n\n /** A turn releases its conversation, a child run its own thread. */\n private releaseThread(run: AgentRunRow, completedAt: Date): void {\n this.db\n .query(\n `\n UPDATE agent_threads\n SET active_run_id = NULL, updated_at = ?\n WHERE project_id = ? AND id = ? AND active_run_id = ?\n `\n )\n .run(completedAt.toISOString(), run.project_id, run.thread_id, run.id)\n }\n\n private requireRun(projectId: string, id: string): AgentRunRecord {\n const row = this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentRunRow | null\n\n if (!row) {\n throw new AgentStorageError(\n \"run_not_found\",\n `[SixbSqlite] Agent run '${id}' not found for project '${projectId}'.`\n )\n }\n\n return rowToRunRecord(row)\n }\n}\n",
15
17
  "import type { Database } from \"bun:sqlite\"\n\nexport type SqliteValue = string | number | null\n\ntype SqliteRunListTable =\n | \"agent_runs\"\n | \"pipeline_runs\"\n | \"pipeline_step_runs\"\n | \"sync_runs\"\n | \"webhook_runs\"\n | \"workflow_runs\"\n | \"workflow_node_runs\"\n | \"workflow_agent_node_runs\"\n\nexport function hasEmptyStatuses(input: { readonly statuses?: readonly unknown[] }): boolean {\n return input.statuses !== undefined && input.statuses.length === 0\n}\n\ntype StartedAtExpression =\n | \"started_at\"\n | \"COALESCE(started_at, created_at)\"\n | \"COALESCE(started_at, queued_at)\"\n\nexport function appendRunListFilters(\n whereClauses: string[],\n args: SqliteValue[],\n input: {\n readonly statuses?: readonly string[]\n readonly startedAfter?: Date\n readonly startedBefore?: Date\n },\n startedAtExpression: StartedAtExpression = \"started_at\"\n): void {\n if (input.statuses) {\n if (input.statuses.length === 0) {\n whereClauses.push(\"1 = 0\")\n } else {\n whereClauses.push(`status IN (${input.statuses.map(() => \"?\").join(\", \")})`)\n args.push(...input.statuses)\n }\n }\n\n if (input.startedAfter) {\n whereClauses.push(`${startedAtExpression} >= ?`)\n args.push(input.startedAfter.toISOString())\n }\n\n if (input.startedBefore) {\n whereClauses.push(`${startedAtExpression} <= ?`)\n args.push(input.startedBefore.toISOString())\n }\n}\n\nexport function queryRunList<TRow>(input: {\n readonly db: Database\n readonly tableName: SqliteRunListTable\n readonly whereClauses: readonly string[]\n readonly args: readonly SqliteValue[]\n readonly order?: \"asc\" | \"desc\"\n readonly limit?: number\n readonly offset?: number\n}): { readonly rows: readonly TRow[]; readonly total: number; readonly hasMore: boolean } {\n const where = `WHERE ${input.whereClauses.join(\" AND \")}`\n const order = input.order === \"asc\" ? \"ASC\" : \"DESC\"\n const offset = input.offset ?? 0\n\n const totalRow = input.db\n .query(`SELECT COUNT(*) AS count FROM ${input.tableName} ${where}`)\n .get(...input.args) as { count: number }\n\n const orderColumn =\n input.tableName === \"agent_runs\"\n ? \"COALESCE(started_at, created_at)\"\n : input.tableName === \"sync_runs\" || input.tableName === \"pipeline_runs\"\n ? \"COALESCE(started_at, queued_at)\"\n : input.tableName === \"workflow_agent_node_runs\"\n ? \"created_at\"\n : \"started_at\"\n const idColumn = input.tableName === \"workflow_agent_node_runs\" ? \"node_run_id\" : \"id\"\n let query = `\n SELECT * FROM ${input.tableName}\n ${where}\n ORDER BY ${orderColumn} ${order}, ${idColumn} ${order}\n `\n const queryArgs = [...input.args]\n\n if (input.limit !== undefined) {\n query += \" LIMIT ? OFFSET ?\"\n queryArgs.push(input.limit, offset)\n } else if (offset > 0) {\n query += \" LIMIT -1 OFFSET ?\"\n queryArgs.push(offset)\n }\n\n const rows = input.db.query(query).all(...queryArgs) as TRow[]\n const total = totalRow.count\n\n return {\n rows,\n total,\n hasMore: offset + rows.length < total,\n }\n}\n",
16
- "import type { Database } from \"bun:sqlite\"\nimport {\n snapshotAgentThreadSandboxParams,\n transitionAgentThreadSandbox,\n} from \"@sixb/core/internal/agent-run-storage-provider\"\nimport {\n AgentStorageError,\n type AgentThreadRecord,\n type AgentThreadSandboxState,\n type AgentThreadStore,\n type CreateAgentThreadInput,\n type ListAgentThreadsInput,\n type ListAgentThreadsResult,\n type TransitionAgentThreadSandboxInput,\n} from \"@sixb/core/storage\"\nimport type { SqliteValue } from \"../run-list-query\"\nimport { isUniqueConstraintError } from \"../storage-errors\"\nimport {\n type AgentRunRow,\n type AgentThreadRow,\n queryAgentList,\n rowToRunRecord,\n rowToThreadRecord,\n} from \"./rows\"\n\nexport class SqliteAgentThreadStore implements AgentThreadStore {\n constructor(private readonly db: Database) {}\n\n async transitionSandbox(\n input: TransitionAgentThreadSandboxInput\n ): Promise<AgentThreadSandboxState> {\n return this.db\n .transaction(() => {\n const run =\n input.action === \"recreate\"\n ? null\n : (this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.runId) as AgentRunRow | null)\n const thread = this.requireThread(input.projectId, input.id)\n const state = transitionAgentThreadSandbox(thread, run ? rowToRunRecord(run) : null, input)\n this.db\n .query(\"UPDATE agent_threads SET sandbox_state = ? WHERE project_id = ? AND id = ?\")\n .run(JSON.stringify(state), input.projectId, input.id)\n return state\n })\n .immediate()\n }\n\n async create(input: CreateAgentThreadInput): Promise<AgentThreadRecord> {\n const sandboxParams =\n input.sandboxParams === undefined\n ? null\n : JSON.stringify(snapshotAgentThreadSandboxParams(input.sandboxParams))\n const createdAt = input.createdAt ?? new Date()\n const updatedAt = input.updatedAt ?? createdAt\n\n try {\n this.db\n .query(\n `\n INSERT INTO agent_threads (\n project_id,\n id,\n owner_principal_type,\n owner_principal_id,\n title,\n sandbox_params,\n status,\n active_run_id,\n last_message_at,\n message_count,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL, 0, ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.ownerPrincipal.type,\n input.ownerPrincipal.id,\n input.title ?? null,\n sandboxParams,\n input.status ?? \"active\",\n createdAt.toISOString(),\n updatedAt.toISOString()\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Agent thread '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n throw error\n }\n\n return this.requireThread(input.projectId, input.id)\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentThreadRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as AgentThreadRow | null\n\n return row ? rowToThreadRecord(row) : null\n }\n\n async getByIds(params: {\n readonly projectId: string\n readonly ids: readonly string[]\n }): Promise<readonly AgentThreadRecord[]> {\n const ids = [...new Set(params.ids)]\n if (ids.length === 0) {\n return []\n }\n\n const rows = this.db\n .query(\n `\n SELECT *\n FROM agent_threads\n WHERE project_id = ?\n AND id IN (SELECT value FROM json_each(?))\n `\n )\n .all(params.projectId, JSON.stringify(ids)) as AgentThreadRow[]\n\n const byId = new Map(rows.map((row) => [row.id, row]))\n return ids.flatMap((id) => {\n const row = byId.get(id)\n return row ? [rowToThreadRecord(row)] : []\n })\n }\n\n async list(input: ListAgentThreadsInput): Promise<ListAgentThreadsResult> {\n if (input.statuses !== undefined && input.statuses.length === 0) {\n return { threads: [], hasMore: false, total: 0 }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n\n if (input.statuses) {\n whereClauses.push(`status IN (${input.statuses.map(() => \"?\").join(\", \")})`)\n args.push(...input.statuses)\n }\n\n if (input.ownerPrincipal) {\n whereClauses.push(\"owner_principal_type = ? AND owner_principal_id = ?\")\n args.push(input.ownerPrincipal.type, input.ownerPrincipal.id)\n }\n\n const dir = input.order === \"asc\" ? \"ASC\" : \"DESC\"\n const { rows, total, hasMore } = queryAgentList<AgentThreadRow>({\n db: this.db,\n table: \"agent_threads\",\n whereClauses,\n args,\n orderBy: `COALESCE(last_message_at, created_at) ${dir}, id ${dir}`,\n limit: input.limit,\n offset: input.offset,\n })\n\n return { threads: rows.map(rowToThreadRecord), hasMore, total }\n }\n\n private requireThread(projectId: string, id: string): AgentThreadRecord {\n const row = this.db\n .query(\"SELECT * FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentThreadRow | null\n\n if (!row) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Failed to load agent thread '${id}' for project '${projectId}'.`\n )\n }\n\n return rowToThreadRecord(row)\n }\n}\n",
17
- "import type { AgentStorage, ExecutionStorage } from \"@sixb/core/storage\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n type SqliteStoreConnection,\n} from \"../transactions\"\nimport { SqliteAgentContextCheckpointStore } from \"./checkpoints\"\nimport { SqliteAgentMessageStore } from \"./messages\"\nimport { SqliteAgentRunStore } from \"./runs\"\nimport { SqliteAgentThreadStore } from \"./threads\"\n\nexport interface SqliteAgentStorageOptions {\n /** Path to SQLite database file. Defaults to ':memory:' for in-memory database. */\n path?: string\n /** Internal shared connection used by bundled SqliteStorage. */\n connection?: SqliteStoreConnection\n /** Execution ledger used to validate immutable run ownership. */\n executions: ExecutionStorage\n}\n\n/**\n * SQLite-backed agent persistence: thread, run, message, and context-checkpoint sub-stores sharing\n * one connection. Cross-table writes run in SQLite transactions; the bundled {@link SqliteStorage}\n * serializes them for single-flight and checkpoint compare-and-swap safety.\n */\nexport class SqliteAgentStorage implements AgentStorage {\n readonly threads: SqliteAgentThreadStore\n readonly runs: SqliteAgentRunStore\n readonly messages: SqliteAgentMessageStore\n readonly checkpoints: SqliteAgentContextCheckpointStore\n\n private readonly connection: SqliteStoreConnection\n\n constructor(options: SqliteAgentStorageOptions) {\n this.connection = openSqliteStoreConnection(options)\n\n this.threads = new SqliteAgentThreadStore(this.connection.db)\n this.runs = new SqliteAgentRunStore(this.connection.db, options.executions)\n this.messages = new SqliteAgentMessageStore(this.connection.db)\n this.checkpoints = new SqliteAgentContextCheckpointStore(this.connection.db)\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n}\n",
18
- "import {\n type AiAccountingAggregateFragment,\n type AiAccountingRecordSetItem,\n aiModelCallCostDetails,\n aiModelCallCostMatchesUsage,\n buildAiAccountingOverviewFromFragments,\n directModelCallAttribution,\n normalizeAiAccountingQuery,\n normalizeAiModelCallAccountingQuery,\n normalizeAiModelCallCostRecord,\n parseAiModelCallCostDetails,\n toAccountingItem,\n} from \"@sixb/core/internal/ai-cost-storage-provider\"\nimport { normalizeModelProviderIds } from \"@sixb/core/models\"\nimport type { ReadonlyJsonObject } from \"@sixb/core/storage\"\nimport {\n type AiAccountingOverview,\n type AiCostStorage,\n AiCostStorageError,\n type AiCostSummary,\n type AiModelCallCostRecord,\n type AiModelCallUsageRecord,\n type ListAiModelCallAccountingInput,\n type ListAiModelCallAccountingResult,\n type ListAiModelCallGroupsInput,\n type ListAiModelCallGroupsResult,\n type QueryAiAccountingOverviewInput,\n type SummarizeAiCostExecutionsInput,\n} from \"@sixb/core/storage\"\nimport { listAiModelCallGroups } from \"./ai-cost-groups\"\nimport { requestedReasoningFromRow } from \"./ai-usage-storage\"\nimport { isUniqueConstraintError } from \"./storage-errors\"\nimport { runImmediateTransaction, type SqliteStoreConnection } from \"./transactions\"\n\n/** SQLite-backed immutable valuations stored in one append-only table. */\nexport class SqliteAiCostStorage implements AiCostStorage {\n constructor(private readonly connection: SqliteStoreConnection) {}\n\n async listModelCallGroups(\n input: ListAiModelCallGroupsInput\n ): Promise<ListAiModelCallGroupsResult> {\n return listAiModelCallGroups(this.connection, input)\n }\n\n async recordModelCallCost(input: AiModelCallCostRecord): Promise<void> {\n const record = normalizeAiModelCallCostRecord(input)\n runImmediateTransaction(this.connection.db, () => {\n const usage = this.findUsage(record.projectId, record.usageRecordId)\n if (!usage) throw missingUsage(record)\n assertCostMatchesUsage(record, usage)\n if (this.findCost(record.projectId, record.usageRecordId)) return\n try {\n this.insertCost(record)\n } catch (error) {\n if (!isUniqueConstraintError(error)) throw error\n if (!this.findCost(record.projectId, record.usageRecordId)) throw error\n }\n })\n }\n\n async summarizeExecutions(\n input: SummarizeAiCostExecutionsInput\n ): Promise<readonly AiCostSummary[]> {\n assertNonBlank(input.projectId, \"cost summary projectId\")\n for (const id of input.executionIds) assertNonBlank(id, \"cost summary executionId\")\n if (input.executionIds.length === 0) return []\n const rows = this.connection.db\n .query(\n `\n WITH requested AS (SELECT DISTINCT value AS execution_id FROM json_each(?))\n SELECT usage.execution_id,\n cost.status,\n cost.currency,\n CAST(cost.amount_nanos AS TEXT) AS amount_nanos\n FROM requested\n JOIN ai_model_call_usage AS usage\n ON usage.project_id = ? AND usage.execution_id = requested.execution_id\n LEFT JOIN ai_model_call_valuations AS cost\n ON cost.project_id = usage.project_id AND cost.usage_record_id = usage.id\n `\n )\n .all(JSON.stringify([...new Set(input.executionIds)]), input.projectId) as SummaryRow[]\n return aggregateSummaryRows(input.executionIds, rows)\n }\n\n async queryProjectOverview(input: QueryAiAccountingOverviewInput): Promise<AiAccountingOverview> {\n const query = normalizeAiAccountingQuery(input)\n const rows = this.connection.db\n .query(SQLITE_ACCOUNTING_OVERVIEW_SQL)\n .all(\n query.projectId,\n query.from.toISOString(),\n query.to.toISOString(),\n query.providerId ?? null,\n query.providerId ?? null,\n query.modelId ?? null,\n query.modelId ?? null,\n input.bucket\n ) as AggregateRow[]\n return buildAiAccountingOverviewFromFragments(input, rows.map(aggregateFragmentFromRow))\n }\n\n async listModelCalls(\n input: ListAiModelCallAccountingInput\n ): Promise<ListAiModelCallAccountingResult> {\n const query = normalizeAiModelCallAccountingQuery(input)\n const parameters = accountingListFilterParameters(query)\n const count = this.connection.db\n .query(SQLITE_ACCOUNTING_LIST_COUNT_SQL)\n .get(...parameters) as CountRow\n const rows = this.connection.db\n .query(SQLITE_ACCOUNTING_LIST_PAGE_SQL)\n .all(...parameters, query.limit, query.offset) as JoinedRow[]\n const items = rows.map((row) => toAccountingItem(accountingItemFromRow(row)))\n const total = safeSqlCount(count.total, \"model-call list total\")\n return structuredClone({\n items,\n total,\n hasMore: query.offset + items.length < total,\n })\n }\n\n private insertCost(record: AiModelCallCostRecord): void {\n const rated = record.status === \"rated\" ? record : undefined\n const details = aiModelCallCostDetails(record)\n this.connection.db\n .query(\n `INSERT INTO ai_model_call_valuations (\n project_id, usage_record_id, status, provider_id, model_id,\n currency, amount_nanos, reason, details, rated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`\n )\n .run(\n record.projectId,\n record.usageRecordId,\n record.status,\n record.billingIdentity?.providerId ?? null,\n record.billingIdentity?.modelId ?? null,\n rated?.money.currency ?? null,\n rated ? BigInt(rated.money.amountNanos) : null,\n record.status === \"unpriceable\" ? record.reason : null,\n JSON.stringify(details),\n record.ratedAt.toISOString()\n )\n }\n\n private findCost(projectId: string, usageId: string): AiModelCallCostRecord | null {\n const row = this.connection.db\n .query(\n `SELECT *, CAST(amount_nanos AS TEXT) AS amount_nanos\n FROM ai_model_call_valuations\n WHERE project_id = ? AND usage_record_id = ?`\n )\n .get(projectId, usageId) as ValuationRow | null\n return row ? rowToCost(row) : null\n }\n\n private findUsage(projectId: string, id: string): AiModelCallUsageRecord | null {\n const row = this.connection.db\n .query(\"SELECT * FROM ai_model_call_usage WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as UsageRow | null\n return row ? usageFromRow(row, []) : null\n }\n}\n\nconst SQLITE_ACCOUNTING_LIST_FILTER = `\n usage.project_id = ? AND usage.occurred_at >= ? AND usage.occurred_at < ?\n AND (? IS NULL OR usage.provider_id = ?)\n AND (? IS NULL OR usage.requested_model_id = ?)\n AND (? IS NULL OR usage.execution_id = ?)\n AND (\n ? IS NULL OR ? = CASE\n WHEN cost.status = 'rated' THEN 'rated'\n WHEN cost.status = 'unpriceable' THEN 'unpriceable'\n ELSE 'unvalued'\n END\n )\n`\n\nconst SQLITE_ACCOUNTING_LIST_COUNT_SQL = `\n SELECT CAST(COUNT(*) AS TEXT) AS total\n FROM ai_model_call_usage AS usage\n LEFT JOIN ai_model_call_valuations AS cost\n ON cost.project_id = usage.project_id AND cost.usage_record_id = usage.id\n WHERE ${SQLITE_ACCOUNTING_LIST_FILTER}\n`\n\nconst SQLITE_ACCOUNTING_LIST_PAGE_SQL = `\n SELECT usage.*,\n CASE\n WHEN direct_agent.kind = 'conversation' THEN 'agent'\n WHEN direct_agent.kind = 'subagent' THEN 'subagent'\n WHEN workflow_agent.node_run_id IS NOT NULL THEN 'workflowAgent'\n ELSE NULL\n END AS attribution_kind,\n workflow_node.node_id AS attribution_agent_step_id,\n direct_agent.id AS attribution_agent_run_id,\n direct_agent.thread_id AS attribution_thread_id,\n direct_agent.parent_run_id AS attribution_parent_run_id,\n workflow_agent.node_run_id AS attribution_node_run_id,\n workflow_node.workflow_id AS attribution_workflow_id,\n workflow_node.workflow_run_id AS attribution_workflow_run_id,\n execution.executor_kind, execution.executor_id, execution.authority_primitive_id AS primitive_id,\n COALESCE((\n SELECT json_group_array(group_id) FROM (\n SELECT group_id FROM ai_model_call_usage_groups\n WHERE project_id = usage.project_id AND usage_record_id = usage.id\n ORDER BY group_id\n )\n ), '[]') AS requester_group_ids,\n cost.status AS cost_status,\n cost.provider_id AS cost_provider_id,\n cost.model_id AS cost_model_id,\n cost.currency AS cost_currency,\n CAST(cost.amount_nanos AS TEXT) AS cost_amount_nanos,\n cost.reason AS cost_reason,\n cost.details AS cost_details,\n cost.rated_at AS cost_rated_at\n FROM ai_model_call_usage AS usage\n JOIN executions AS execution ON execution.project_id = usage.project_id AND execution.id = usage.execution_id\n LEFT JOIN agent_runs AS direct_agent\n ON direct_agent.project_id = usage.project_id\n AND direct_agent.execution_id = usage.execution_id\n LEFT JOIN workflow_agent_node_runs AS workflow_agent\n ON workflow_agent.project_id = usage.project_id\n AND workflow_agent.execution_id = usage.execution_id\n LEFT JOIN workflow_node_runs AS workflow_node\n ON workflow_node.project_id = workflow_agent.project_id\n AND workflow_node.id = workflow_agent.node_run_id\n LEFT JOIN ai_model_call_valuations AS cost\n ON cost.project_id = usage.project_id AND cost.usage_record_id = usage.id\n WHERE ${SQLITE_ACCOUNTING_LIST_FILTER}\n ORDER BY usage.occurred_at DESC, usage.id ASC\n LIMIT ? OFFSET ?\n`\n\nconst SQLITE_ACCOUNTING_OVERVIEW_SQL = `\n WITH classified AS (\n SELECT usage.provider_id,\n usage.requested_model_id,\n usage.occurred_at,\n usage.input_tokens,\n usage.output_tokens,\n usage.uncached_input_tokens,\n usage.cache_read_input_tokens,\n usage.cache_write_input_tokens,\n usage.text_output_tokens,\n usage.reasoning_output_tokens,\n usage.audio_duration_ms,\n usage.reporting_status,\n CASE\n WHEN direct_agent.kind = 'conversation' THEN 'agent'\n WHEN workflow_agent.node_run_id IS NOT NULL THEN 'workflowAgent'\n ELSE NULL\n END AS attribution_agent_kind,\n workflow_node.node_id AS attribution_agent_step_id,\n COALESCE(workflow_node.workflow_id,\n CASE WHEN execution.executor_kind = 'workflow' THEN execution.authority_primitive_id END\n ) AS attribution_workflow_id,\n CASE\n WHEN cost.status = 'rated' THEN 'rated'\n WHEN cost.status = 'unpriceable' THEN 'unpriceable'\n ELSE 'unvalued'\n END AS valuation_status,\n CASE WHEN cost.status = 'rated' THEN cost.currency ELSE NULL END AS amount_currency,\n CASE WHEN cost.status = 'rated' THEN cost.amount_nanos ELSE NULL END AS amount_nanos\n FROM ai_model_call_usage AS usage\n JOIN executions AS execution ON execution.project_id = usage.project_id AND execution.id = usage.execution_id\n LEFT JOIN agent_runs AS direct_agent\n ON direct_agent.project_id = usage.project_id\n AND direct_agent.execution_id = usage.execution_id\n LEFT JOIN workflow_agent_node_runs AS workflow_agent\n ON workflow_agent.project_id = usage.project_id\n AND workflow_agent.execution_id = usage.execution_id\n LEFT JOIN workflow_node_runs AS workflow_node\n ON workflow_node.project_id = workflow_agent.project_id\n AND workflow_node.id = workflow_agent.node_run_id\n LEFT JOIN ai_model_call_valuations AS cost\n ON cost.project_id = usage.project_id AND cost.usage_record_id = usage.id\n WHERE usage.project_id = ? AND usage.occurred_at >= ? AND usage.occurred_at < ?\n AND (? IS NULL OR usage.provider_id = ?)\n AND (? IS NULL OR usage.requested_model_id = ?)\n ), expanded AS (\n SELECT 'totals' AS dimension, NULL AS key_1, NULL AS key_2, NULL AS key_3, NULL AS bucket_start,\n classified.*\n FROM classified\n UNION ALL\n SELECT 'series', NULL, NULL, NULL,\n CASE ?\n WHEN 'hour' THEN strftime('%Y-%m-%dT%H:00:00.000Z', occurred_at)\n WHEN 'day' THEN strftime('%Y-%m-%dT00:00:00.000Z', occurred_at)\n ELSE strftime(\n '%Y-%m-%dT00:00:00.000Z',\n occurred_at,\n printf('-%d days', (CAST(strftime('%w', occurred_at) AS INTEGER) + 6) % 7)\n )\n END,\n classified.*\n FROM classified\n UNION ALL\n SELECT 'model', provider_id, requested_model_id, NULL, NULL, classified.* FROM classified\n UNION ALL\n SELECT 'agent', attribution_agent_kind, attribution_workflow_id, attribution_agent_step_id, NULL, classified.*\n FROM classified WHERE attribution_agent_kind IS NOT NULL\n UNION ALL\n SELECT 'workflow', attribution_workflow_id, NULL, NULL, NULL, classified.*\n FROM classified WHERE attribution_workflow_id IS NOT NULL\n )\n SELECT dimension,\n key_1,\n key_2,\n key_3,\n bucket_start,\n amount_currency,\n CAST(COUNT(*) AS TEXT) AS model_call_count,\n CAST(SUM(CASE WHEN reporting_status <> 'unavailable' THEN 1 ELSE 0 END) AS TEXT)\n AS reported_usage_call_count,\n CAST(SUM(CASE WHEN input_tokens IS NOT NULL AND output_tokens IS NOT NULL THEN 1 ELSE 0 END) AS TEXT)\n AS complete_usage_call_count,\n CAST(COUNT(input_tokens) AS TEXT) AS input_tokens_count,\n CAST(SUM(input_tokens) AS TEXT) AS input_tokens_sum,\n CAST(COUNT(output_tokens) AS TEXT) AS output_tokens_count,\n CAST(SUM(output_tokens) AS TEXT) AS output_tokens_sum,\n CAST(COUNT(uncached_input_tokens) AS TEXT) AS uncached_input_tokens_count,\n CAST(SUM(uncached_input_tokens) AS TEXT) AS uncached_input_tokens_sum,\n CAST(COUNT(cache_read_input_tokens) AS TEXT) AS cache_read_input_tokens_count,\n CAST(SUM(cache_read_input_tokens) AS TEXT) AS cache_read_input_tokens_sum,\n CAST(COUNT(cache_write_input_tokens) AS TEXT) AS cache_write_input_tokens_count,\n CAST(SUM(cache_write_input_tokens) AS TEXT) AS cache_write_input_tokens_sum,\n CAST(COUNT(text_output_tokens) AS TEXT) AS text_output_tokens_count,\n CAST(SUM(text_output_tokens) AS TEXT) AS text_output_tokens_sum,\n CAST(COUNT(reasoning_output_tokens) AS TEXT) AS reasoning_output_tokens_count,\n CAST(SUM(reasoning_output_tokens) AS TEXT) AS reasoning_output_tokens_sum,\n CAST(COUNT(audio_duration_ms) AS TEXT) AS audio_duration_ms_count,\n CAST(SUM(audio_duration_ms) AS TEXT) AS audio_duration_ms_sum,\n CAST(SUM(CASE WHEN valuation_status = 'rated' THEN 1 ELSE 0 END) AS TEXT)\n AS rated_call_count,\n CAST(SUM(CASE WHEN valuation_status = 'unpriceable' THEN 1 ELSE 0 END) AS TEXT)\n AS unpriceable_call_count,\n CAST(SUM(CASE WHEN valuation_status = 'unvalued' THEN 1 ELSE 0 END) AS TEXT)\n AS unvalued_call_count,\n CAST(SUM(amount_nanos / 1000000000000) AS TEXT) AS amount_high,\n CAST(SUM((amount_nanos / 1000000) % 1000000) AS TEXT) AS amount_middle,\n CAST(SUM(amount_nanos % 1000000) AS TEXT) AS amount_low\n FROM expanded\n GROUP BY dimension, key_1, key_2, key_3, bucket_start, amount_currency\n`\n\nfunction accountingListFilterParameters(\n query: ReturnType<typeof normalizeAiModelCallAccountingQuery>\n): readonly (string | null)[] {\n return [\n query.projectId,\n query.from.toISOString(),\n query.to.toISOString(),\n query.providerId ?? null,\n query.providerId ?? null,\n query.modelId ?? null,\n query.modelId ?? null,\n query.executionId ?? null,\n query.executionId ?? null,\n query.valuationStatus ?? null,\n query.valuationStatus ?? null,\n ]\n}\n\ninterface ValuationRow {\n readonly project_id: string\n readonly usage_record_id: string\n readonly status: \"rated\" | \"unpriceable\"\n readonly provider_id: string | null\n readonly model_id: string | null\n readonly currency: string | null\n readonly amount_nanos: string | null\n readonly reason: string | null\n readonly details: string\n readonly rated_at: string\n}\n\ninterface UsageRow {\n readonly project_id: string\n readonly id: string\n readonly execution_id: string\n readonly attempt: number\n readonly call_id: string\n readonly provider_id: string\n readonly requested_model_id: string\n readonly model_kind: AiModelCallUsageRecord[\"modelKind\"] | null\n readonly requested_reasoning: string | null\n readonly response_model_id: string | null\n readonly response_id: string\n readonly input_tokens: number | null\n readonly output_tokens: number | null\n readonly total_tokens: number | null\n readonly uncached_input_tokens: number | null\n readonly cache_read_input_tokens: number | null\n readonly cache_write_input_tokens: number | null\n readonly text_output_tokens: number | null\n readonly reasoning_output_tokens: number | null\n readonly audio_duration_ms: number | null\n readonly reporting_status: AiModelCallUsageRecord[\"usage\"][\"reportingStatus\"]\n readonly raw_usage: string | null\n readonly provider_ids: string | null\n readonly occurred_at: string\n readonly recorded_at: string\n}\n\ninterface JoinedRow extends UsageRow {\n readonly executor_kind: string | null\n readonly executor_id: string | null\n readonly primitive_id: string | null\n readonly attribution_kind: \"agent\" | \"subagent\" | \"workflowAgent\" | null\n readonly attribution_agent_step_id: string | null\n readonly attribution_agent_run_id: string | null\n readonly attribution_thread_id: string | null\n readonly attribution_parent_run_id: string | null\n readonly attribution_node_run_id: string | null\n readonly attribution_workflow_id: string | null\n readonly attribution_workflow_run_id: string | null\n readonly requester_group_ids: string\n readonly cost_status: ValuationRow[\"status\"] | null\n readonly cost_provider_id: string | null\n readonly cost_model_id: string | null\n readonly cost_currency: string | null\n readonly cost_amount_nanos: string | null\n readonly cost_reason: string | null\n readonly cost_details: string | null\n readonly cost_rated_at: string | null\n}\n\ninterface AggregateRow {\n readonly dimension: AiAccountingAggregateFragment[\"dimension\"]\n readonly key_1: string | null\n readonly key_2: string | null\n readonly key_3: string | null\n readonly bucket_start: string | null\n readonly amount_currency: string | null\n readonly model_call_count: string\n readonly reported_usage_call_count: string\n readonly complete_usage_call_count: string\n readonly input_tokens_count: string\n readonly input_tokens_sum: string | null\n readonly output_tokens_count: string\n readonly output_tokens_sum: string | null\n readonly uncached_input_tokens_count: string\n readonly uncached_input_tokens_sum: string | null\n readonly cache_read_input_tokens_count: string\n readonly cache_read_input_tokens_sum: string | null\n readonly cache_write_input_tokens_count: string\n readonly cache_write_input_tokens_sum: string | null\n readonly text_output_tokens_count: string\n readonly text_output_tokens_sum: string | null\n readonly reasoning_output_tokens_count: string\n readonly reasoning_output_tokens_sum: string | null\n readonly audio_duration_ms_count: string\n readonly audio_duration_ms_sum: string | null\n readonly rated_call_count: string\n readonly unpriceable_call_count: string\n readonly unvalued_call_count: string\n readonly amount_high: string | null\n readonly amount_middle: string | null\n readonly amount_low: string | null\n}\n\ninterface CountRow {\n readonly total: string\n}\n\ninterface SummaryRow {\n readonly execution_id: string\n readonly status: ValuationRow[\"status\"] | null\n readonly currency: string | null\n readonly amount_nanos: string | null\n}\n\nfunction aggregateFragmentFromRow(row: AggregateRow): AiAccountingAggregateFragment {\n const dimensionKeys =\n row.dimension === \"model\"\n ? { providerId: required(row.key_1), modelId: required(row.key_2) }\n : row.dimension === \"agent\"\n ? {\n agentKind: required(row.key_1) as \"agent\" | \"workflowAgent\",\n ...(row.key_1 === \"workflowAgent\"\n ? { workflowId: required(row.key_2), agentStepId: required(row.key_3) }\n : {}),\n }\n : row.dimension === \"workflow\"\n ? { workflowId: required(row.key_1) }\n : row.dimension === \"series\"\n ? { start: new Date(required(row.bucket_start)) }\n : {}\n return {\n dimension: row.dimension,\n ...dimensionKeys,\n modelCallCount: row.model_call_count,\n usage: {\n reportedCallCount: row.reported_usage_call_count,\n completeCallCount: row.complete_usage_call_count,\n inputTokens: meterFragment(row.input_tokens_count, row.input_tokens_sum),\n outputTokens: meterFragment(row.output_tokens_count, row.output_tokens_sum),\n uncachedInputTokens: meterFragment(\n row.uncached_input_tokens_count,\n row.uncached_input_tokens_sum\n ),\n cacheReadInputTokens: meterFragment(\n row.cache_read_input_tokens_count,\n row.cache_read_input_tokens_sum\n ),\n cacheWriteInputTokens: meterFragment(\n row.cache_write_input_tokens_count,\n row.cache_write_input_tokens_sum\n ),\n textOutputTokens: meterFragment(row.text_output_tokens_count, row.text_output_tokens_sum),\n reasoningOutputTokens: meterFragment(\n row.reasoning_output_tokens_count,\n row.reasoning_output_tokens_sum\n ),\n audioDurationMs: meterFragment(row.audio_duration_ms_count, row.audio_duration_ms_sum),\n },\n costs: {\n ...(row.amount_currency === null ||\n row.amount_high === null ||\n row.amount_middle === null ||\n row.amount_low === null\n ? {}\n : {\n amount: {\n currency: row.amount_currency,\n amountNanos: sqliteAggregateAmount(row),\n },\n }),\n ratedCallCount: row.rated_call_count,\n unpriceableCallCount: row.unpriceable_call_count,\n unvaluedCallCount: row.unvalued_call_count,\n },\n }\n}\n\nfunction meterFragment(presentCallCount: string, total: string | null) {\n return { presentCallCount, total }\n}\n\nfunction sqliteAggregateAmount(\n row: Pick<AggregateRow, \"amount_high\" | \"amount_middle\" | \"amount_low\">\n): string {\n return (\n BigInt(required(row.amount_high)) * 1_000_000_000_000n +\n BigInt(required(row.amount_middle)) * 1_000_000n +\n BigInt(required(row.amount_low))\n ).toString()\n}\n\nfunction accountingItemFromRow(row: JoinedRow): AiAccountingRecordSetItem {\n const usage = usageFromRow(row, parseStringArray(row.requester_group_ids))\n const cost = row.cost_status === null ? undefined : costFromJoinedRow(row)\n const attribution =\n row.attribution_kind === null\n ? directModelCallAttribution(row.executor_kind, row.executor_id, row.primitive_id)\n : row.attribution_kind === \"agent\"\n ? {\n kind: \"agent\" as const,\n agentRunId: required(row.attribution_agent_run_id),\n threadId: required(row.attribution_thread_id),\n }\n : row.attribution_kind === \"subagent\"\n ? {\n kind: \"subagent\" as const,\n subagentRunId: required(row.attribution_agent_run_id),\n parentRunId: required(row.attribution_parent_run_id),\n }\n : {\n kind: \"workflowAgent\" as const,\n agentStepId: required(row.attribution_agent_step_id),\n nodeRunId: required(row.attribution_node_run_id),\n workflowId: required(row.attribution_workflow_id),\n workflowRunId: required(row.attribution_workflow_run_id),\n }\n return {\n usage,\n ...(attribution ? { attribution } : {}),\n ...(cost ? { cost } : {}),\n }\n}\n\nfunction usageFromRow(row: UsageRow, requesterGroupIds: readonly string[]): AiModelCallUsageRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n executionId: row.execution_id,\n attempt: row.attempt,\n callId: row.call_id,\n requesterGroupIds,\n providerId: row.provider_id,\n ...(row.provider_ids === null\n ? {}\n : { providerIds: normalizeModelProviderIds(JSON.parse(row.provider_ids)) }),\n requestedModelId: row.requested_model_id,\n ...(row.model_kind === null ? {} : { modelKind: row.model_kind }),\n ...(row.requested_reasoning === null\n ? {}\n : { requestedReasoning: requestedReasoningFromRow(row.requested_reasoning) }),\n ...(row.response_model_id === null ? {} : { responseModelId: row.response_model_id }),\n responseId: row.response_id,\n usage: {\n ...(row.input_tokens === null ? {} : { inputTokens: row.input_tokens }),\n ...(row.output_tokens === null ? {} : { outputTokens: row.output_tokens }),\n ...(row.total_tokens === null ? {} : { totalTokens: row.total_tokens }),\n ...(row.uncached_input_tokens === null\n ? {}\n : { uncachedInputTokens: row.uncached_input_tokens }),\n ...(row.cache_read_input_tokens === null\n ? {}\n : { cacheReadInputTokens: row.cache_read_input_tokens }),\n ...(row.cache_write_input_tokens === null\n ? {}\n : { cacheWriteInputTokens: row.cache_write_input_tokens }),\n ...(row.text_output_tokens === null ? {} : { textOutputTokens: row.text_output_tokens }),\n ...(row.reasoning_output_tokens === null\n ? {}\n : { reasoningOutputTokens: row.reasoning_output_tokens }),\n ...(row.audio_duration_ms === null ? {} : { audioDurationMs: row.audio_duration_ms }),\n reportingStatus: row.reporting_status,\n },\n ...(row.raw_usage === null\n ? {}\n : { rawUsage: JSON.parse(row.raw_usage) as ReadonlyJsonObject }),\n occurredAt: new Date(row.occurred_at),\n recordedAt: new Date(row.recorded_at),\n }\n}\n\nfunction rowToCost(row: ValuationRow): AiModelCallCostRecord {\n return costRecord({\n projectId: row.project_id,\n usageId: row.usage_record_id,\n status: row.status,\n providerId: row.provider_id,\n modelId: row.model_id,\n currency: row.currency,\n amountNanos: row.amount_nanos,\n reason: row.reason,\n details: row.details,\n ratedAt: row.rated_at,\n })\n}\n\nfunction costFromJoinedRow(row: JoinedRow): AiModelCallCostRecord {\n return costRecord({\n projectId: row.project_id,\n usageId: row.id,\n status: required(row.cost_status),\n providerId: row.cost_provider_id,\n modelId: row.cost_model_id,\n currency: row.cost_currency,\n amountNanos: row.cost_amount_nanos,\n reason: row.cost_reason,\n details: required(row.cost_details),\n ratedAt: required(row.cost_rated_at),\n })\n}\n\nfunction costRecord(input: {\n projectId: string\n usageId: string\n status: ValuationRow[\"status\"]\n providerId: string | null\n modelId: string | null\n currency: string | null\n amountNanos: string | null\n reason: string | null\n details: string\n ratedAt: string\n}): AiModelCallCostRecord {\n const details = parseAiModelCallCostDetails(input.details)\n const priceSource =\n details.priceSource === undefined\n ? undefined\n : { ...details.priceSource, observedAt: new Date(details.priceSource.observedAt) }\n const base = {\n ...(details.estimate === undefined ? {} : { estimate: details.estimate }),\n projectId: input.projectId,\n usageRecordId: input.usageId,\n pricingContext: details.pricingContext,\n ratedAt: new Date(input.ratedAt),\n }\n if (input.status === \"rated\") {\n return normalizeAiModelCallCostRecord({\n ...base,\n status: \"rated\",\n billingIdentity: { providerId: required(input.providerId), modelId: required(input.modelId) },\n priceSource: required(priceSource),\n money: { currency: required(input.currency), amountNanos: required(input.amountNanos) },\n components: required(details.components),\n })\n }\n return normalizeAiModelCallCostRecord({\n ...base,\n status: \"unpriceable\",\n ...(input.providerId && input.modelId\n ? { billingIdentity: { providerId: input.providerId, modelId: input.modelId } }\n : {}),\n ...(priceSource === undefined ? {} : { priceSource }),\n reason: required(input.reason) as Extract<\n AiModelCallCostRecord,\n { status: \"unpriceable\" }\n >[\"reason\"],\n ...(details.missingMeters ? { missingMeters: details.missingMeters } : {}),\n })\n}\n\nfunction aggregateSummaryRows(\n ids: readonly string[],\n rows: readonly SummaryRow[]\n): AiCostSummary[] {\n const map = new Map(ids.map((id) => [id, accumulator()]))\n for (const row of rows) {\n const value = map.get(row.execution_id)\n if (!value) continue\n if (row.status === null) value.unvaluedCallCount += 1\n else if (row.status === \"unpriceable\") value.unpriceableCallCount += 1\n else {\n value.ratedCallCount += 1\n add(value.amounts, required(row.currency), required(row.amount_nanos))\n }\n }\n return ids.map((id) => finish(map.get(id)!))\n}\n\ninterface Accumulator {\n amounts: Map<string, bigint>\n ratedCallCount: number\n unpriceableCallCount: number\n unvaluedCallCount: number\n}\n\nfunction accumulator(): Accumulator {\n return {\n amounts: new Map(),\n ratedCallCount: 0,\n unpriceableCallCount: 0,\n unvaluedCallCount: 0,\n }\n}\n\nfunction finish(value: Accumulator): AiCostSummary {\n return {\n amounts: [...value.amounts]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([currency, amount]) => ({ currency, amountNanos: amount.toString() })),\n ratedCallCount: value.ratedCallCount,\n unpriceableCallCount: value.unpriceableCallCount,\n unvaluedCallCount: value.unvaluedCallCount,\n }\n}\n\nfunction add(amounts: Map<string, bigint>, currency: string, amount: string): void {\n amounts.set(currency, (amounts.get(currency) ?? 0n) + BigInt(amount))\n}\n\nfunction assertCostMatchesUsage(\n record: AiModelCallCostRecord,\n usage: AiModelCallUsageRecord\n): void {\n if (!aiModelCallCostMatchesUsage(record, usage)) {\n throw new AiCostStorageError(\n \"cost_mismatch\",\n `[SixbSqlite] AI valuation for usage '${record.usageRecordId}' does not match its usage record.`\n )\n }\n}\n\nfunction missingUsage(record: { projectId: string; usageRecordId: string }) {\n return new AiCostStorageError(\n \"missing_usage\",\n `[SixbSqlite] AI usage '${record.usageRecordId}' does not exist.`\n )\n}\n\nfunction parseStringArray(value: string): string[] {\n const parsed: unknown = JSON.parse(value)\n if (!Array.isArray(parsed) || parsed.some((item) => typeof item !== \"string\")) {\n throw new Error(\"[SixbSqlite] AI requester group ids are invalid.\")\n }\n return parsed\n}\n\nfunction assertNonBlank(value: string, field: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`[Sixb] AI ${field} must be nonblank.`)\n }\n}\n\nfunction safeSqlCount(value: string, field: string): number {\n if (!/^(0|[1-9]\\d*)$/.test(value)) {\n throw new Error(`[SixbSqlite] AI accounting ${field} is invalid.`)\n }\n const count = Number(value)\n if (!Number.isSafeInteger(count)) {\n throw new TypeError(`[Sixb] AI accounting ${field} exceeds the safe integer range.`)\n }\n return count\n}\n\nfunction required<T>(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error(\"[SixbSqlite] AI valuation column is unexpectedly null.\")\n }\n return value\n}\n",
19
- "import {\n type AiModelCallGroupRow,\n aiModelCallGroupFragmentFromRow,\n buildAiModelCallGroupsFromFragments,\n normalizeAiModelCallAccountingQuery,\n} from \"@sixb/core/internal/ai-cost-storage-provider\"\nimport type { ListAiModelCallGroupsInput, ListAiModelCallGroupsResult } from \"@sixb/core/storage\"\nimport type { SqliteStoreConnection } from \"./transactions\"\n\n/** Paginate initiating executions, then aggregate their matching calls without loading usage payloads. */\nexport async function listAiModelCallGroups(\n connection: SqliteStoreConnection,\n input: ListAiModelCallGroupsInput\n): Promise<ListAiModelCallGroupsResult> {\n const query = normalizeAiModelCallAccountingQuery(input)\n const parameters = [\n query.projectId,\n query.from.toISOString(),\n query.to.toISOString(),\n query.providerId ?? null,\n query.modelId ?? null,\n query.valuationStatus ?? null,\n ]\n const count = connection.db.query(COUNT_SQL).get(...parameters) as { total: string }\n const rows = connection.db\n .query(PAGE_SQL)\n .all(...parameters, query.limit, query.offset) as AiModelCallGroupRow[]\n const total = Number(count?.total)\n if (!Number.isSafeInteger(total) || total < 0)\n throw new RangeError(\"[Sixb] Invalid model-call group count.\")\n const items = buildAiModelCallGroupsFromFragments(rows.map(aiModelCallGroupFragmentFromRow))\n return { items, total, hasMore: query.offset + items.length < total }\n}\n\nconst FILTERED_SQL = `\nWITH filtered AS (\n SELECT COALESCE(root_agent.execution_id, usage.execution_id) AS root_execution_id,\n usage.execution_id, usage.provider_id, usage.requested_model_id, usage.occurred_at,\n usage.total_tokens,\n execution.executor_kind, execution.executor_id, execution.authority_primitive_id AS primitive_id,\n COALESCE(cost.status, 'unvalued') AS valuation_status,\n cost.currency AS amount_currency, cost.amount_nanos,\n root_agent.id AS root_agent_run_id,\n root_agent.thread_id AS root_thread_id,\n direct_agent.kind AS direct_kind,\n direct_agent.id AS direct_run_id,\n direct_agent.parent_run_id AS parent_run_id,\n workflow_node.node_id AS workflow_agent_step_id,\n workflow_agent.node_run_id AS workflow_node_run_id,\n workflow_node.workflow_id AS workflow_id,\n workflow_node.workflow_run_id AS workflow_run_id\n FROM ai_model_call_usage AS usage\n JOIN executions AS execution ON execution.project_id = usage.project_id AND execution.id = usage.execution_id\n LEFT JOIN agent_runs AS direct_agent\n ON direct_agent.project_id = usage.project_id AND direct_agent.execution_id = usage.execution_id\n LEFT JOIN agent_runs AS root_agent\n ON root_agent.project_id = usage.project_id\n AND root_agent.id = COALESCE(direct_agent.parent_run_id, direct_agent.id)\n LEFT JOIN workflow_agent_node_runs AS workflow_agent\n ON workflow_agent.project_id = usage.project_id AND workflow_agent.execution_id = usage.execution_id\n LEFT JOIN workflow_node_runs AS workflow_node\n ON workflow_node.project_id = workflow_agent.project_id AND workflow_node.id = workflow_agent.node_run_id\n LEFT JOIN ai_model_call_valuations AS cost\n ON cost.project_id = usage.project_id AND cost.usage_record_id = usage.id\n WHERE usage.project_id = ?1\n AND usage.occurred_at >= ?2\n AND usage.occurred_at < ?3\n AND (?4 IS NULL OR usage.provider_id = ?4)\n AND (?5 IS NULL OR usage.requested_model_id = ?5)\n AND (?6 IS NULL OR COALESCE(cost.status, 'unvalued') = ?6)\n), roots AS (\n SELECT root_execution_id, MAX(occurred_at) AS last_call_at\n FROM filtered GROUP BY root_execution_id\n)\n`\nconst COUNT_SQL = `${FILTERED_SQL} SELECT CAST(COUNT(*) AS TEXT) AS total FROM roots`\nconst PAGE_SQL = `${FILTERED_SQL}, page AS (\n SELECT root_execution_id FROM roots\n ORDER BY last_call_at DESC, root_execution_id ASC LIMIT ?7 OFFSET ?8\n)\nSELECT filtered.root_execution_id, execution_id, provider_id, requested_model_id,\n MIN(occurred_at) AS first_call_at, MAX(occurred_at) AS last_call_at,\n CAST(COUNT(*) AS TEXT) AS call_count,\n CAST(COUNT(total_tokens) AS TEXT) AS token_count,\n CAST(SUM(total_tokens) AS TEXT) AS total_tokens,\n valuation_status, amount_currency,\n CAST(SUM(amount_nanos / 1000000000000) AS TEXT) AS amount_high,\n CAST(SUM((amount_nanos / 1000000) % 1000000) AS TEXT) AS amount_middle,\n CAST(SUM(amount_nanos % 1000000) AS TEXT) AS amount_low,\n MAX(root_agent_run_id) AS root_agent_run_id,\n MAX(executor_kind) AS executor_kind, MAX(executor_id) AS executor_id, MAX(primitive_id) AS primitive_id,\n MAX(root_thread_id) AS root_thread_id,\n MAX(direct_kind) AS direct_kind,\n MAX(direct_run_id) AS direct_run_id,\n MAX(parent_run_id) AS parent_run_id,\n MAX(workflow_agent_step_id) AS workflow_agent_step_id,\n MAX(workflow_node_run_id) AS workflow_node_run_id,\n MAX(workflow_id) AS workflow_id,\n MAX(workflow_run_id) AS workflow_run_id\nFROM filtered JOIN page ON page.root_execution_id = filtered.root_execution_id\nGROUP BY filtered.root_execution_id, execution_id, provider_id, requested_model_id,\n valuation_status, amount_currency\n`\n",
20
- "import { assertAiUsageExecutionId, normalizeAiModelCallRecord } from \"@sixb/core/internal/storage\"\nimport { isModelReasoning, normalizeModelProviderIds } from \"@sixb/core/models\"\nimport type { ReadonlyJsonObject } from \"@sixb/core/storage\"\nimport {\n type AiModelCallUsageInput,\n type AiModelCallUsageRecord,\n type AiUsageExecutionSummary,\n type AiUsageStorage,\n AiUsageStorageError,\n aggregateAiModelCallUsage,\n type GetLatestAiModelCallForExecutionInput,\n type RecordAiModelCallInput,\n type RecordAiModelCallResult,\n type SummarizeAiUsageExecutionInput,\n type SummarizeAiUsageExecutionsInput,\n} from \"@sixb/core/storage\"\nimport { isUniqueConstraintError } from \"./storage-errors\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n runImmediateTransaction,\n type SqliteStoreConnection,\n} from \"./transactions\"\n\nexport interface SqliteAiUsageStorageOptions {\n readonly path?: string\n readonly connection?: SqliteStoreConnection\n}\n\n/** SQLite-backed append-only model-call usage ledger. */\nexport class SqliteAiUsageStorage implements AiUsageStorage {\n private readonly connection: SqliteStoreConnection\n\n constructor(options: SqliteAiUsageStorageOptions = {}) {\n this.connection = openSqliteStoreConnection(options)\n }\n\n async recordModelCall(input: RecordAiModelCallInput): Promise<RecordAiModelCallResult> {\n const record = normalizeAiModelCallRecord(input)\n return runImmediateTransaction(this.connection.db, () => {\n const existing = this.findByIdempotencyKey(record)\n if (existing) return { record: existing, created: false }\n this.assertExecutionExists(record.projectId, record.executionId)\n\n try {\n this.insertRecord(record)\n } catch (error) {\n if (!isUniqueConstraintError(error)) throw error\n\n const concurrent = this.findByIdempotencyKey(record)\n if (concurrent) return { record: concurrent, created: false }\n throw new AiUsageStorageError(\n \"duplicate_id\",\n `[SixbSqlite] AI usage record '${record.id}' already exists for project '${record.projectId}'.`\n )\n }\n\n for (const groupId of record.requesterGroupIds) {\n this.connection.db\n .query(\n `\n INSERT INTO ai_model_call_usage_groups (\n project_id, usage_record_id, group_id, occurred_at\n ) VALUES (?, ?, ?, ?)\n `\n )\n .run(record.projectId, record.id, groupId, record.occurredAt.toISOString())\n }\n\n return { record: this.requireById(record.projectId, record.id), created: true }\n })\n }\n\n async summarizeExecution(\n input: SummarizeAiUsageExecutionInput\n ): Promise<AiUsageExecutionSummary> {\n const [summary] = await this.summarizeExecutions({\n projectId: input.projectId,\n executionIds: [input.executionId],\n })\n return summary!\n }\n\n async getLatestForExecution(\n input: GetLatestAiModelCallForExecutionInput\n ): Promise<AiModelCallUsageRecord | null> {\n assertNonBlankProjectId(input.projectId)\n assertAiUsageExecutionId(input.executionId)\n const row = this.connection.db\n .query(\n `\n SELECT * FROM ai_model_call_usage\n WHERE project_id = ? AND execution_id = ?\n ORDER BY occurred_at DESC, id DESC\n LIMIT 1\n `\n )\n .get(input.projectId, input.executionId) as AiUsageRow | null\n return row ? this.rowToRecord(row) : null\n }\n\n async summarizeExecutions(\n input: SummarizeAiUsageExecutionsInput\n ): Promise<readonly AiUsageExecutionSummary[]> {\n assertNonBlankProjectId(input.projectId)\n for (const executionId of input.executionIds) assertAiUsageExecutionId(executionId)\n if (input.executionIds.length === 0) return []\n\n const rows = this.executionRows(input)\n return aggregateExecutionRows(input.executionIds, rows)\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n\n private insertRecord(record: AiModelCallUsageRecord): void {\n this.connection.db\n .query(\n `\n INSERT INTO ai_model_call_usage (\n project_id,\n id,\n execution_id,\n attempt,\n call_id,\n provider_id,\n provider_ids,\n requested_model_id,\n model_kind,\n requested_reasoning,\n response_model_id,\n response_id,\n input_tokens,\n output_tokens,\n total_tokens,\n uncached_input_tokens,\n cache_read_input_tokens,\n cache_write_input_tokens,\n text_output_tokens,\n reasoning_output_tokens,\n audio_duration_ms,\n reporting_status,\n raw_usage,\n occurred_at,\n recorded_at\n ) VALUES (\n ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?\n )\n `\n )\n .run(\n record.projectId,\n record.id,\n record.executionId,\n record.attempt,\n record.callId,\n record.providerId,\n record.providerIds === undefined ? null : JSON.stringify(record.providerIds),\n record.requestedModelId,\n record.modelKind ?? null,\n record.requestedReasoning === undefined ? null : JSON.stringify(record.requestedReasoning),\n record.responseModelId ?? null,\n record.responseId,\n record.usage.inputTokens ?? null,\n record.usage.outputTokens ?? null,\n record.usage.totalTokens ?? null,\n record.usage.uncachedInputTokens ?? null,\n record.usage.cacheReadInputTokens ?? null,\n record.usage.cacheWriteInputTokens ?? null,\n record.usage.textOutputTokens ?? null,\n record.usage.reasoningOutputTokens ?? null,\n record.usage.audioDurationMs ?? null,\n record.usage.reportingStatus,\n record.rawUsage === undefined ? null : JSON.stringify(record.rawUsage),\n record.occurredAt.toISOString(),\n record.recordedAt.toISOString()\n )\n }\n\n private findByIdempotencyKey(\n record: Pick<\n AiModelCallUsageRecord,\n \"projectId\" | \"executionId\" | \"attempt\" | \"callId\" | \"responseId\"\n >\n ): AiModelCallUsageRecord | null {\n const row = this.connection.db\n .query(\n `\n SELECT * FROM ai_model_call_usage\n WHERE project_id = ?\n AND execution_id = ?\n AND attempt = ?\n AND call_id = ?\n AND response_id = ?\n `\n )\n .get(\n record.projectId,\n record.executionId,\n record.attempt,\n record.callId,\n record.responseId\n ) as AiUsageRow | null\n return row ? this.rowToRecord(row) : null\n }\n\n private requireById(projectId: string, id: string): AiModelCallUsageRecord {\n const row = this.connection.db\n .query(\"SELECT * FROM ai_model_call_usage WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AiUsageRow | null\n if (!row) throw new Error(`[SixbSqlite] AI usage record '${id}' disappeared after insert.`)\n return this.rowToRecord(row)\n }\n\n private rowToRecord(row: AiUsageRow): AiModelCallUsageRecord {\n const groupRows = this.connection.db\n .query(\n `\n SELECT group_id FROM ai_model_call_usage_groups\n WHERE project_id = ? AND usage_record_id = ?\n ORDER BY group_id\n `\n )\n .all(row.project_id, row.id) as Array<{ group_id: string }>\n\n return {\n id: row.id,\n projectId: row.project_id,\n executionId: row.execution_id,\n attempt: row.attempt,\n callId: row.call_id,\n requesterGroupIds: groupRows.map((group) => group.group_id),\n providerId: row.provider_id,\n ...(row.provider_ids === null\n ? {}\n : { providerIds: normalizeModelProviderIds(JSON.parse(row.provider_ids)) }),\n requestedModelId: row.requested_model_id,\n ...(row.model_kind === null ? {} : { modelKind: row.model_kind }),\n ...(row.requested_reasoning === null\n ? {}\n : { requestedReasoning: requestedReasoningFromRow(row.requested_reasoning) }),\n ...(row.response_model_id === null ? {} : { responseModelId: row.response_model_id }),\n responseId: row.response_id,\n usage: {\n ...usageFromRow(row),\n ...(row.total_tokens === null ? {} : { totalTokens: row.total_tokens }),\n reportingStatus: row.reporting_status,\n },\n ...(row.raw_usage === null\n ? {}\n : { rawUsage: JSON.parse(row.raw_usage) as ReadonlyJsonObject }),\n occurredAt: new Date(row.occurred_at),\n recordedAt: new Date(row.recorded_at),\n }\n }\n\n private executionRows(input: SummarizeAiUsageExecutionsInput): AiUsageRow[] {\n const requested = JSON.stringify([...new Set(input.executionIds)])\n return this.connection.db\n .query(\n `\n WITH requested AS (\n SELECT DISTINCT value AS execution_id\n FROM json_each(?)\n )\n SELECT usage.* FROM requested\n JOIN ai_model_call_usage AS usage\n ON usage.project_id = ?\n AND usage.execution_id = requested.execution_id\n `\n )\n .all(requested, input.projectId) as AiUsageRow[]\n }\n\n private assertExecutionExists(projectId: string, executionId: string): void {\n const execution = this.connection.db\n .query(\"SELECT 1 FROM executions WHERE project_id = ? AND id = ?\")\n .get(projectId, executionId)\n if (execution) return\n throw new AiUsageStorageError(\n \"missing_execution\",\n `[SixbSqlite] AI usage execution '${executionId}' does not exist in project '${projectId}'.`\n )\n }\n}\n\ninterface AiUsageRow {\n readonly project_id: string\n readonly id: string\n readonly execution_id: string\n readonly attempt: number\n readonly call_id: string\n readonly provider_id: string\n readonly provider_ids: string | null\n readonly requested_model_id: string\n readonly model_kind: AiModelCallUsageRecord[\"modelKind\"] | null\n readonly requested_reasoning: string | null\n readonly response_model_id: string | null\n readonly response_id: string\n readonly input_tokens: number | null\n readonly output_tokens: number | null\n readonly total_tokens: number | null\n readonly uncached_input_tokens: number | null\n readonly cache_read_input_tokens: number | null\n readonly cache_write_input_tokens: number | null\n readonly text_output_tokens: number | null\n readonly reasoning_output_tokens: number | null\n readonly audio_duration_ms: number | null\n readonly reporting_status: AiModelCallUsageRecord[\"usage\"][\"reportingStatus\"]\n readonly raw_usage: string | null\n readonly occurred_at: string\n readonly recorded_at: string\n}\n\nfunction aggregateExecutionRows(\n executionIds: readonly string[],\n rows: readonly AiUsageRow[]\n): readonly AiUsageExecutionSummary[] {\n const usageByExecutionId = new Map<string, AiModelCallUsageInput[]>()\n for (const executionId of executionIds) usageByExecutionId.set(executionId, [])\n for (const row of rows) {\n usageByExecutionId.get(row.execution_id)?.push(usageFromRow(row))\n }\n return executionIds.map((executionId) => {\n const usages = usageByExecutionId.get(executionId) ?? []\n return {\n modelCallCount: usages.length,\n usage: aggregateAiModelCallUsage(usages),\n }\n })\n}\n\nfunction usageFromRow(row: AiUsageRow): AiModelCallUsageInput {\n return {\n ...(row.input_tokens === null ? {} : { inputTokens: row.input_tokens }),\n ...(row.output_tokens === null ? {} : { outputTokens: row.output_tokens }),\n ...(row.uncached_input_tokens === null\n ? {}\n : { uncachedInputTokens: row.uncached_input_tokens }),\n ...(row.cache_read_input_tokens === null\n ? {}\n : { cacheReadInputTokens: row.cache_read_input_tokens }),\n ...(row.cache_write_input_tokens === null\n ? {}\n : { cacheWriteInputTokens: row.cache_write_input_tokens }),\n ...(row.text_output_tokens === null ? {} : { textOutputTokens: row.text_output_tokens }),\n ...(row.reasoning_output_tokens === null\n ? {}\n : { reasoningOutputTokens: row.reasoning_output_tokens }),\n ...(row.audio_duration_ms === null ? {} : { audioDurationMs: row.audio_duration_ms }),\n }\n}\n\nexport function requestedReasoningFromRow(\n value: string\n): AiModelCallUsageRecord[\"requestedReasoning\"] {\n const parsed: unknown = JSON.parse(value)\n if (!isModelReasoning(parsed)) {\n throw new Error(\"[SixbSqlite] Stored AI usage requested reasoning is invalid.\")\n }\n return parsed\n}\n\nfunction assertNonBlankProjectId(projectId: string): void {\n if (typeof projectId !== \"string\" || projectId.trim().length === 0) {\n throw new TypeError(\"[Sixb] AI usage projectId must be nonblank.\")\n }\n}\n",
18
+ "import type { Database } from \"bun:sqlite\"\nimport { assertAgentApprovalModeInput } from \"@sixb/core/internal/agent-run-storage-provider\"\nimport {\n type AgentApprovalMode,\n type AgentApprovalModeStore,\n AgentStorageError,\n type Principal,\n} from \"@sixb/core/storage\"\n\nexport class SqliteAgentApprovalModeStore implements AgentApprovalModeStore {\n constructor(private readonly db: Database) {}\n\n async getDefault(input: {\n readonly projectId: string\n readonly principal: Principal\n }): Promise<AgentApprovalMode | null> {\n const row = this.db\n .query(\n `SELECT approval_mode FROM agent_user_settings\n WHERE project_id = ? AND principal_type = ? AND principal_id = ?`\n )\n .get(input.projectId, input.principal.type, input.principal.id) as {\n approval_mode: AgentApprovalMode\n } | null\n return row?.approval_mode ?? null\n }\n\n async setDefault(input: {\n readonly projectId: string\n readonly principal: Principal\n readonly mode: AgentApprovalMode\n readonly updatedAt?: Date\n }): Promise<void> {\n assertAgentApprovalModeInput(input.mode, \"SixbSqlite\")\n this.db\n .query(\n `INSERT INTO agent_user_settings (\n project_id, principal_type, principal_id, approval_mode, updated_at\n ) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT (project_id, principal_type, principal_id)\n DO UPDATE SET approval_mode = excluded.approval_mode, updated_at = excluded.updated_at`\n )\n .run(\n input.projectId,\n input.principal.type,\n input.principal.id,\n input.mode,\n (input.updatedAt ?? new Date()).toISOString()\n )\n }\n\n async getForThread(input: {\n readonly projectId: string\n readonly threadId: string\n readonly principal: Principal\n }): Promise<AgentApprovalMode | null> {\n const row = this.db\n .query(\n `SELECT approval_mode FROM agent_thread_user_settings\n WHERE project_id = ? AND thread_id = ? AND principal_type = ? AND principal_id = ?`\n )\n .get(input.projectId, input.threadId, input.principal.type, input.principal.id) as {\n approval_mode: AgentApprovalMode\n } | null\n return row?.approval_mode ?? null\n }\n\n async setForThread(input: {\n readonly projectId: string\n readonly threadId: string\n readonly principal: Principal\n readonly mode: AgentApprovalMode | null\n readonly updatedAt?: Date\n }): Promise<void> {\n if (input.mode !== null) assertAgentApprovalModeInput(input.mode, \"SixbSqlite\")\n const thread = this.db\n .query(\"SELECT id FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.threadId)\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[SixbSqlite] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n\n if (input.mode === null) {\n this.db\n .query(\n `DELETE FROM agent_thread_user_settings\n WHERE project_id = ? AND thread_id = ? AND principal_type = ? AND principal_id = ?`\n )\n .run(input.projectId, input.threadId, input.principal.type, input.principal.id)\n return\n }\n this.db\n .query(\n `INSERT INTO agent_thread_user_settings (\n project_id, thread_id, principal_type, principal_id, approval_mode, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (project_id, thread_id, principal_type, principal_id)\n DO UPDATE SET approval_mode = excluded.approval_mode, updated_at = excluded.updated_at`\n )\n .run(\n input.projectId,\n input.threadId,\n input.principal.type,\n input.principal.id,\n input.mode,\n (input.updatedAt ?? new Date()).toISOString()\n )\n }\n}\n",
19
+ "import type { Database } from \"bun:sqlite\"\nimport {\n assertConversationThreadRow,\n participantsToAdd,\n planAgentThreadFork,\n remapArtifactIds,\n snapshotAgentThreadSandboxParams,\n transitionAgentThreadSandbox,\n} from \"@sixb/core/internal/agent-run-storage-provider\"\nimport {\n type AddAgentThreadParticipantsInput,\n type AgentContextCheckpointRecord,\n AgentStorageError,\n type AgentThreadParticipantRecord,\n type AgentThreadRecord,\n type AgentThreadSandboxState,\n type AgentThreadStore,\n type CreateAgentThreadInput,\n type ForkAgentThreadInput,\n type ListAgentThreadChildrenInput,\n type ListAgentThreadParticipantsInput,\n type ListAgentThreadsInput,\n type ListAgentThreadsResult,\n type RemoveAgentThreadParticipantInput,\n type TransitionAgentThreadSandboxInput,\n} from \"@sixb/core/storage\"\nimport type { SqliteValue } from \"../run-list-query\"\nimport { isUniqueConstraintError } from \"../storage-errors\"\nimport {\n type AgentContextCheckpointRow,\n type AgentMessageRow,\n type AgentRunRow,\n type AgentThreadParticipantRow,\n type AgentThreadRow,\n queryAgentList,\n rowToContextCheckpointRecord,\n rowToParticipantRecord,\n rowToRunRecord,\n rowToThreadRecord,\n} from \"./rows\"\n\nexport class SqliteAgentThreadStore implements AgentThreadStore {\n constructor(private readonly db: Database) {}\n\n async transitionSandbox(\n input: TransitionAgentThreadSandboxInput\n ): Promise<AgentThreadSandboxState> {\n return this.db\n .transaction(() => {\n const run =\n input.action === \"recreate\"\n ? null\n : (this.db\n .query(\"SELECT * FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.runId) as AgentRunRow | null)\n const thread = this.requireThread(input.projectId, input.id)\n const state = transitionAgentThreadSandbox(thread, run ? rowToRunRecord(run) : null, input)\n this.db\n .query(\"UPDATE agent_threads SET sandbox_state = ? WHERE project_id = ? AND id = ?\")\n .run(JSON.stringify(state), input.projectId, input.id)\n return state\n })\n .immediate()\n }\n\n async create(input: CreateAgentThreadInput): Promise<AgentThreadRecord> {\n const sandboxParams =\n input.sandboxParams === undefined\n ? null\n : JSON.stringify(snapshotAgentThreadSandboxParams(input.sandboxParams))\n const createdAt = input.createdAt ?? new Date()\n const updatedAt = input.updatedAt ?? createdAt\n\n try {\n this.db\n .query(\n `\n INSERT INTO agent_threads (\n project_id,\n id,\n owner_principal_type,\n owner_principal_id,\n title,\n sandbox_params,\n status,\n active_run_id,\n last_message_at,\n message_count,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL, 0, ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.ownerPrincipal.type,\n input.ownerPrincipal.id,\n input.title ?? null,\n sandboxParams,\n input.status ?? \"active\",\n createdAt.toISOString(),\n updatedAt.toISOString()\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Agent thread '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n throw error\n }\n\n return this.requireThread(input.projectId, input.id)\n }\n\n async fork(input: ForkAgentThreadInput): Promise<AgentThreadRecord> {\n return this.db\n .transaction(() => {\n const source = this.db\n .query(\n \"SELECT id, kind, active_run_id FROM agent_threads WHERE project_id = ? AND id = ?\"\n )\n .get(input.projectId, input.sourceThreadId) as Pick<\n AgentThreadRow,\n \"id\" | \"kind\" | \"active_run_id\"\n > | null\n\n if (!source) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[SixbSqlite] Agent thread '${input.sourceThreadId}' not found for project '${input.projectId}'.`\n )\n }\n assertConversationThreadRow(source, \"can be forked\", \"SixbSqlite\")\n\n const activeRun = source.active_run_id === null ? null : this.findActiveRun(input, source)\n\n // Only what the plan needs: the parts are copied by the database, not through here. A\n // message of approval outcomes only is not counted (`countsAsThreadMessage`).\n const messages = (\n this.db\n .query(\n `\n SELECT id, seq,\n NOT (\n json_array_length(parts) > 0 AND NOT EXISTS (\n SELECT 1 FROM json_each(agent_messages.parts)\n WHERE json_extract(value, '$.type') <> 'approval-outcome'\n )\n ) AS counted\n FROM agent_messages WHERE project_id = ? AND thread_id = ? ORDER BY seq ASC\n `\n )\n .all(input.projectId, source.id) as (Pick<AgentMessageRow, \"id\" | \"seq\"> & {\n counted: number\n })[]\n ).map((row) => ({ id: row.id, seq: row.seq, counted: row.counted === 1 }))\n\n const checkpoints = this.db\n .query(\n `\n SELECT * FROM agent_context_checkpoints\n WHERE project_id = ? AND thread_id = ?\n ORDER BY summarized_through_seq DESC, created_at DESC, id DESC\n `\n )\n .all(input.projectId, source.id) as AgentContextCheckpointRow[]\n\n const plan = planAgentThreadFork(\n input,\n {\n ...(activeRun?.trigger_message_id\n ? { triggerMessageId: activeRun.trigger_message_id }\n : {}),\n messages,\n checkpoints: checkpoints.map(rowToContextCheckpointRecord),\n },\n \"SixbSqlite\"\n )\n\n this.insertForkedThread(plan.thread)\n\n this.db\n .query(\n `\n INSERT INTO agent_messages (\n project_id,\n id,\n thread_id,\n run_id,\n role,\n author_principal_type,\n author_principal_id,\n seq,\n parts,\n metadata,\n content_version,\n created_at,\n completed_at\n )\n SELECT\n message.project_id,\n json_extract(copy.value, '$[1]'),\n ?,\n message.run_id,\n message.role,\n message.author_principal_type,\n message.author_principal_id,\n message.seq,\n message.parts,\n message.metadata,\n message.content_version,\n message.created_at,\n message.completed_at\n FROM json_each(?) AS copy\n JOIN agent_messages AS message\n ON message.project_id = ? AND message.id = json_extract(copy.value, '$[0]')\n `\n )\n .run(\n plan.thread.id,\n JSON.stringify(plan.messages.map((copy) => [copy.sourceId, copy.id])),\n input.projectId\n )\n this.remapCopiedParts(\n input.projectId,\n plan.messages.map((copy) => copy.id),\n input.artifactCopies\n )\n\n if (plan.checkpoint) {\n this.insertCopiedCheckpoint(plan.checkpoint)\n }\n\n return this.requireThread(input.projectId, input.id)\n })\n .immediate()\n }\n\n async getById(params: { projectId: string; id: string }): Promise<AgentThreadRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as AgentThreadRow | null\n\n return row ? rowToThreadRecord(row) : null\n }\n\n async getByIds(params: {\n readonly projectId: string\n readonly ids: readonly string[]\n }): Promise<readonly AgentThreadRecord[]> {\n const ids = [...new Set(params.ids)]\n if (ids.length === 0) {\n return []\n }\n\n const rows = this.db\n .query(\n `\n SELECT *\n FROM agent_threads\n WHERE project_id = ?\n AND id IN (SELECT value FROM json_each(?))\n `\n )\n .all(params.projectId, JSON.stringify(ids)) as AgentThreadRow[]\n\n const byId = new Map(rows.map((row) => [row.id, row]))\n return ids.flatMap((id) => {\n const row = byId.get(id)\n return row ? [rowToThreadRecord(row)] : []\n })\n }\n\n async listChildren(input: ListAgentThreadChildrenInput): Promise<readonly AgentThreadRecord[]> {\n // By `idx_agent_threads_children`, which holds sub-agents' threads only.\n const turn = input.parentRunId === undefined ? \"\" : \"AND parent_run_id = ?\"\n const rows = this.db\n .query(\n `\n SELECT *\n FROM agent_threads\n WHERE project_id = ? AND parent_thread_id = ? AND kind = 'subagent' ${turn}\n ORDER BY created_at ASC, id ASC\n LIMIT ? OFFSET ?\n `\n )\n .all(\n input.projectId,\n input.parentThreadId,\n ...(input.parentRunId === undefined ? [] : [input.parentRunId]),\n input.limit ?? 100,\n input.offset ?? 0\n ) as AgentThreadRow[]\n return rows.map(rowToThreadRecord)\n }\n\n async list(input: ListAgentThreadsInput): Promise<ListAgentThreadsResult> {\n if (input.statuses !== undefined && input.statuses.length === 0) {\n return { threads: [], hasMore: false, total: 0 }\n }\n\n // A sub-agent's thread is read through its conversation; the list indexes leave it out too.\n const whereClauses = [\"project_id = ?\", \"kind = 'conversation'\"]\n const args: SqliteValue[] = [input.projectId]\n\n if (input.statuses) {\n whereClauses.push(`status IN (${input.statuses.map(() => \"?\").join(\", \")})`)\n args.push(...input.statuses)\n }\n\n if (input.ownerPrincipal) {\n whereClauses.push(\"owner_principal_type = ? AND owner_principal_id = ?\")\n args.push(input.ownerPrincipal.type, input.ownerPrincipal.id)\n }\n\n if (input.participantPrincipal) {\n whereClauses.push(`EXISTS (\n SELECT 1 FROM agent_thread_participants participant\n WHERE participant.project_id = agent_threads.project_id\n AND participant.thread_id = agent_threads.id\n AND participant.principal_type = ?\n AND participant.principal_id = ?\n )`)\n args.push(input.participantPrincipal.type, input.participantPrincipal.id)\n }\n\n const dir = input.order === \"asc\" ? \"ASC\" : \"DESC\"\n const { rows, total, hasMore } = queryAgentList<AgentThreadRow>({\n db: this.db,\n table: \"agent_threads\",\n whereClauses,\n args,\n orderBy: `COALESCE(last_message_at, created_at) ${dir}, id ${dir}`,\n limit: input.limit,\n offset: input.offset,\n })\n\n return { threads: rows.map(rowToThreadRecord), hasMore, total }\n }\n\n async addParticipants(\n input: AddAgentThreadParticipantsInput\n ): Promise<readonly AgentThreadParticipantRecord[]> {\n return this.db\n .transaction(() => {\n const thread = this.db\n .query(\"SELECT id, kind FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.threadId) as Pick<AgentThreadRow, \"id\" | \"kind\"> | null\n if (!thread) {\n throw new AgentStorageError(\n \"thread_not_found\",\n `[SixbSqlite] Agent thread '${input.threadId}' not found for project '${input.projectId}'.`\n )\n }\n assertConversationThreadRow(thread, \"has participants\", \"SixbSqlite\")\n\n const existing = this.selectParticipants(input.projectId, [input.threadId])\n const added = participantsToAdd(input, existing, \"SixbSqlite\")\n const addedAt = (input.addedAt ?? new Date()).toISOString()\n\n const insert = this.db.query(`\n INSERT INTO agent_thread_participants (\n project_id,\n thread_id,\n principal_type,\n principal_id,\n added_at,\n added_by_type,\n added_by_id\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n `)\n for (const principal of added) {\n insert.run(\n input.projectId,\n input.threadId,\n principal.type,\n principal.id,\n addedAt,\n input.addedBy.type,\n input.addedBy.id\n )\n }\n\n return added.length === 0\n ? existing\n : this.selectParticipants(input.projectId, [input.threadId])\n })\n .immediate()\n }\n\n async removeParticipant(input: RemoveAgentThreadParticipantInput): Promise<boolean> {\n const result = this.db\n .query(`\n DELETE FROM agent_thread_participants\n WHERE project_id = ? AND thread_id = ? AND principal_type = ? AND principal_id = ?\n `)\n .run(input.projectId, input.threadId, input.principal.type, input.principal.id)\n\n return result.changes > 0\n }\n\n async listParticipants(\n input: ListAgentThreadParticipantsInput\n ): Promise<readonly AgentThreadParticipantRecord[]> {\n return this.selectParticipants(input.projectId, [...new Set(input.threadIds)])\n }\n\n private selectParticipants(\n projectId: string,\n threadIds: readonly string[]\n ): AgentThreadParticipantRecord[] {\n if (threadIds.length === 0) {\n return []\n }\n\n const rows = this.db\n .query(`\n SELECT *\n FROM agent_thread_participants\n WHERE project_id = ?\n AND thread_id IN (SELECT value FROM json_each(?))\n ORDER BY added_at, principal_id, thread_id\n `)\n .all(projectId, JSON.stringify(threadIds)) as AgentThreadParticipantRow[]\n\n return rows.map(rowToParticipantRecord)\n }\n\n private findActiveRun(\n input: ForkAgentThreadInput,\n source: Pick<AgentThreadRow, \"active_run_id\">\n ): Pick<AgentRunRow, \"trigger_message_id\"> | null {\n return this.db\n .query(\"SELECT trigger_message_id FROM agent_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, source.active_run_id) as Pick<AgentRunRow, \"trigger_message_id\"> | null\n }\n\n private insertForkedThread(thread: AgentThreadRecord): void {\n try {\n this.db\n .query(\n `\n INSERT INTO agent_threads (\n project_id,\n id,\n owner_principal_type,\n owner_principal_id,\n title,\n sandbox_params,\n sandbox_state,\n status,\n active_run_id,\n last_message_at,\n message_count,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?)\n `\n )\n .run(\n thread.projectId,\n thread.id,\n thread.ownerPrincipal.type,\n thread.ownerPrincipal.id,\n thread.title ?? null,\n thread.sandboxParams === undefined ? null : JSON.stringify(thread.sandboxParams),\n thread.sandboxState === undefined ? null : JSON.stringify(thread.sandboxState),\n thread.status,\n thread.lastMessageAt?.toISOString() ?? null,\n thread.messageCount,\n thread.createdAt.toISOString(),\n thread.updatedAt.toISOString()\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new AgentStorageError(\n \"duplicate_id\",\n `[SixbSqlite] Agent thread '${thread.id}' already exists for project '${thread.projectId}'.`\n )\n }\n\n throw error\n }\n }\n\n private insertCopiedCheckpoint(checkpoint: AgentContextCheckpointRecord): void {\n this.db\n .query(\n `\n INSERT INTO agent_context_checkpoints (\n project_id,\n id,\n thread_id,\n created_by_run_id,\n reason,\n summary,\n summary_format_version,\n summarized_through_seq,\n observed_head_seq,\n estimated_input_tokens_before,\n estimated_input_tokens_after,\n summary_model_id,\n created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n checkpoint.projectId,\n checkpoint.id,\n checkpoint.threadId,\n checkpoint.createdByRunId,\n checkpoint.reason,\n checkpoint.summary,\n checkpoint.summaryFormatVersion,\n checkpoint.summarizedThroughSeq,\n checkpoint.observedHeadSeq,\n checkpoint.estimatedInputTokensBefore,\n checkpoint.estimatedInputTokensAfter,\n checkpoint.summaryModelId,\n checkpoint.createdAt.toISOString()\n )\n }\n\n /** The copied messages name the fork's copies of the source's artifacts. */\n private remapCopiedParts(\n projectId: string,\n messageIds: readonly string[],\n copies: Readonly<Record<string, string>> | undefined\n ): void {\n if (!copies || Object.keys(copies).length === 0 || messageIds.length === 0) return\n\n const rows = this.db\n .query(\n `SELECT id, parts FROM agent_messages\n WHERE project_id = ? AND id IN (SELECT value FROM json_each(?))`\n )\n .all(projectId, JSON.stringify(messageIds)) as {\n readonly id: string\n readonly parts: string\n }[]\n const update = this.db.query(\n \"UPDATE agent_messages SET parts = ? WHERE project_id = ? AND id = ?\"\n )\n for (const row of rows) {\n const parts = remapArtifactIds(row.parts, copies)\n if (parts !== row.parts) update.run(parts, projectId, row.id)\n }\n }\n\n private requireThread(projectId: string, id: string): AgentThreadRecord {\n const row = this.db\n .query(\"SELECT * FROM agent_threads WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AgentThreadRow | null\n\n if (!row) {\n throw new AgentStorageError(\n \"invalid_state\",\n `[SixbSqlite] Failed to load agent thread '${id}' for project '${projectId}'.`\n )\n }\n\n return rowToThreadRecord(row)\n }\n}\n",
20
+ "import type { AgentStorage, ExecutionStorage } from \"@sixb/core/storage\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n type SqliteStoreConnection,\n} from \"../transactions\"\nimport { SqliteAgentApprovalStore } from \"./approvals\"\nimport { SqliteAgentContextCheckpointStore } from \"./checkpoints\"\nimport { SqliteAgentMemoryStore } from \"./memory\"\nimport { SqliteAgentMessageStore } from \"./messages\"\nimport { SqliteAgentRunStore } from \"./runs\"\nimport { SqliteAgentApprovalModeStore } from \"./settings\"\nimport { SqliteAgentThreadStore } from \"./threads\"\n\nexport interface SqliteAgentStorageOptions {\n /** Path to SQLite database file. Defaults to ':memory:' for in-memory database. */\n path?: string\n /** Internal shared connection used by bundled SqliteStorage. */\n connection?: SqliteStoreConnection\n /** Execution ledger used to validate immutable run ownership. */\n executions: ExecutionStorage\n}\n\n/**\n * SQLite-backed agent persistence: thread, run, message, context-checkpoint, memory, approval and\n * approval-mode sub-stores sharing one connection. Cross-table writes run in SQLite transactions; the bundled {@link SqliteStorage}\n * serializes them for single-flight and checkpoint compare-and-swap safety.\n */\nexport class SqliteAgentStorage implements AgentStorage {\n readonly threads: SqliteAgentThreadStore\n readonly runs: SqliteAgentRunStore\n readonly messages: SqliteAgentMessageStore\n readonly checkpoints: SqliteAgentContextCheckpointStore\n readonly memory: SqliteAgentMemoryStore\n readonly approvals: SqliteAgentApprovalStore\n readonly approvalModes: SqliteAgentApprovalModeStore\n\n private readonly connection: SqliteStoreConnection\n\n constructor(options: SqliteAgentStorageOptions) {\n this.connection = openSqliteStoreConnection(options)\n\n this.threads = new SqliteAgentThreadStore(this.connection.db)\n this.runs = new SqliteAgentRunStore(this.connection.db, options.executions)\n this.messages = new SqliteAgentMessageStore(this.connection.db)\n this.checkpoints = new SqliteAgentContextCheckpointStore(this.connection.db)\n this.memory = new SqliteAgentMemoryStore(this.connection.db)\n this.approvals = new SqliteAgentApprovalStore(this.connection.db)\n this.approvalModes = new SqliteAgentApprovalModeStore(this.connection.db)\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n}\n",
21
+ "import {\n type AiAccountingAggregateFragment,\n type AiAccountingRecordSetItem,\n aiAccountingModelKind,\n aiModelCallCostDetails,\n aiModelCallCostMatchesUsage,\n buildAiAccountingOverviewFromFragments,\n directModelCallAttribution,\n normalizeAiAccountingQuery,\n normalizeAiModelCallAccountingQuery,\n normalizeAiModelCallCostRecord,\n parseAiModelCallCostDetails,\n toAccountingItem,\n} from \"@sixb/core/internal/ai-cost-storage-provider\"\nimport { normalizeModelProviderIds } from \"@sixb/core/models\"\nimport type { ReadonlyJsonObject } from \"@sixb/core/storage\"\nimport {\n type AiAccountingOverview,\n type AiCostStorage,\n AiCostStorageError,\n type AiCostSummary,\n type AiModelCallCostRecord,\n type AiModelCallUsageRecord,\n type ListAiModelCallAccountingInput,\n type ListAiModelCallAccountingResult,\n type ListAiModelCallGroupsInput,\n type ListAiModelCallGroupsResult,\n type QueryAiAccountingOverviewInput,\n type SummarizeAiCostExecutionsInput,\n} from \"@sixb/core/storage\"\nimport { listAiModelCallGroups } from \"./ai-cost-groups\"\nimport { requestedReasoningFromRow } from \"./ai-usage-storage\"\nimport { isUniqueConstraintError } from \"./storage-errors\"\nimport { runImmediateTransaction, type SqliteStoreConnection } from \"./transactions\"\n\n/** SQLite-backed immutable valuations stored in one append-only table. */\nexport class SqliteAiCostStorage implements AiCostStorage {\n constructor(private readonly connection: SqliteStoreConnection) {}\n\n async listModelCallGroups(\n input: ListAiModelCallGroupsInput\n ): Promise<ListAiModelCallGroupsResult> {\n return listAiModelCallGroups(this.connection, input)\n }\n\n async recordModelCallCost(input: AiModelCallCostRecord): Promise<void> {\n const record = normalizeAiModelCallCostRecord(input)\n runImmediateTransaction(this.connection.db, () => {\n const usage = this.findUsage(record.projectId, record.usageRecordId)\n if (!usage) throw missingUsage(record)\n assertCostMatchesUsage(record, usage)\n if (this.findCost(record.projectId, record.usageRecordId)) return\n try {\n this.insertCost(record)\n } catch (error) {\n if (!isUniqueConstraintError(error)) throw error\n if (!this.findCost(record.projectId, record.usageRecordId)) throw error\n }\n })\n }\n\n async summarizeExecutions(\n input: SummarizeAiCostExecutionsInput\n ): Promise<readonly AiCostSummary[]> {\n assertNonBlank(input.projectId, \"cost summary projectId\")\n for (const id of input.executionIds) assertNonBlank(id, \"cost summary executionId\")\n if (input.executionIds.length === 0) return []\n const rows = this.connection.db\n .query(\n `\n WITH requested AS (SELECT DISTINCT value AS execution_id FROM json_each(?))\n SELECT usage.execution_id,\n cost.status,\n cost.currency,\n CAST(cost.amount_nanos AS TEXT) AS amount_nanos\n FROM requested\n JOIN ai_model_call_usage AS usage\n ON usage.project_id = ? AND usage.execution_id = requested.execution_id\n LEFT JOIN ai_model_call_valuations AS cost\n ON cost.project_id = usage.project_id AND cost.usage_record_id = usage.id\n `\n )\n .all(JSON.stringify([...new Set(input.executionIds)]), input.projectId) as SummaryRow[]\n return aggregateSummaryRows(input.executionIds, rows)\n }\n\n async queryProjectOverview(input: QueryAiAccountingOverviewInput): Promise<AiAccountingOverview> {\n const query = normalizeAiAccountingQuery(input)\n const rows = this.connection.db\n .query(SQLITE_ACCOUNTING_OVERVIEW_SQL)\n .all(\n query.projectId,\n query.from.toISOString(),\n query.to.toISOString(),\n query.providerId ?? null,\n query.providerId ?? null,\n query.modelId ?? null,\n query.modelId ?? null,\n input.bucket\n ) as AggregateRow[]\n return buildAiAccountingOverviewFromFragments(input, rows.map(aggregateFragmentFromRow))\n }\n\n async listModelCalls(\n input: ListAiModelCallAccountingInput\n ): Promise<ListAiModelCallAccountingResult> {\n const query = normalizeAiModelCallAccountingQuery(input)\n const parameters = accountingListFilterParameters(query)\n const count = this.connection.db\n .query(SQLITE_ACCOUNTING_LIST_COUNT_SQL)\n .get(...parameters) as CountRow\n const rows = this.connection.db\n .query(SQLITE_ACCOUNTING_LIST_PAGE_SQL)\n .all(...parameters, query.limit, query.offset) as JoinedRow[]\n const items = rows.map((row) => toAccountingItem(accountingItemFromRow(row)))\n const total = safeSqlCount(count.total, \"model-call list total\")\n return structuredClone({\n items,\n total,\n hasMore: query.offset + items.length < total,\n })\n }\n\n private insertCost(record: AiModelCallCostRecord): void {\n const rated = record.status === \"rated\" ? record : undefined\n const details = aiModelCallCostDetails(record)\n this.connection.db\n .query(\n `INSERT INTO ai_model_call_valuations (\n project_id, usage_record_id, status, provider_id, model_id,\n currency, amount_nanos, reason, details, rated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`\n )\n .run(\n record.projectId,\n record.usageRecordId,\n record.status,\n record.billingIdentity?.providerId ?? null,\n record.billingIdentity?.modelId ?? null,\n rated?.money.currency ?? null,\n rated ? BigInt(rated.money.amountNanos) : null,\n record.status === \"unpriceable\" ? record.reason : null,\n JSON.stringify(details),\n record.ratedAt.toISOString()\n )\n }\n\n private findCost(projectId: string, usageId: string): AiModelCallCostRecord | null {\n const row = this.connection.db\n .query(\n `SELECT *, CAST(amount_nanos AS TEXT) AS amount_nanos\n FROM ai_model_call_valuations\n WHERE project_id = ? AND usage_record_id = ?`\n )\n .get(projectId, usageId) as ValuationRow | null\n return row ? rowToCost(row) : null\n }\n\n private findUsage(projectId: string, id: string): AiModelCallUsageRecord | null {\n const row = this.connection.db\n .query(\"SELECT * FROM ai_model_call_usage WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as UsageRow | null\n return row ? usageFromRow(row, []) : null\n }\n}\n\nconst SQLITE_ACCOUNTING_LIST_FILTER = `\n usage.project_id = ? AND usage.occurred_at >= ? AND usage.occurred_at < ?\n AND (? IS NULL OR usage.provider_id = ?)\n AND (? IS NULL OR usage.requested_model_id = ?)\n AND (? IS NULL OR usage.execution_id = ?)\n AND (\n ? IS NULL OR ? = CASE\n WHEN cost.status = 'rated' THEN 'rated'\n WHEN cost.status = 'unpriceable' THEN 'unpriceable'\n ELSE 'unvalued'\n END\n )\n`\n\nconst SQLITE_ACCOUNTING_LIST_COUNT_SQL = `\n SELECT CAST(COUNT(*) AS TEXT) AS total\n FROM ai_model_call_usage AS usage\n LEFT JOIN ai_model_call_valuations AS cost\n ON cost.project_id = usage.project_id AND cost.usage_record_id = usage.id\n WHERE ${SQLITE_ACCOUNTING_LIST_FILTER}\n`\n\nconst SQLITE_ACCOUNTING_LIST_PAGE_SQL = `\n SELECT usage.*,\n CASE\n WHEN direct_agent.kind = 'conversation' THEN 'agent'\n WHEN direct_agent.kind = 'subagent' THEN 'subagent'\n WHEN workflow_agent.node_run_id IS NOT NULL THEN 'workflowAgent'\n ELSE NULL\n END AS attribution_kind,\n workflow_node.node_id AS attribution_agent_step_id,\n direct_agent.id AS attribution_agent_run_id,\n direct_agent.thread_id AS attribution_thread_id,\n direct_agent.parent_run_id AS attribution_parent_run_id,\n workflow_agent.node_run_id AS attribution_node_run_id,\n workflow_node.workflow_id AS attribution_workflow_id,\n workflow_node.workflow_run_id AS attribution_workflow_run_id,\n execution.executor_kind, execution.executor_id, execution.authority_primitive_id AS primitive_id,\n COALESCE((\n SELECT json_group_array(group_id) FROM (\n SELECT group_id FROM ai_model_call_usage_groups\n WHERE project_id = usage.project_id AND usage_record_id = usage.id\n ORDER BY group_id\n )\n ), '[]') AS requester_group_ids,\n cost.status AS cost_status,\n cost.provider_id AS cost_provider_id,\n cost.model_id AS cost_model_id,\n cost.currency AS cost_currency,\n CAST(cost.amount_nanos AS TEXT) AS cost_amount_nanos,\n cost.reason AS cost_reason,\n cost.details AS cost_details,\n cost.rated_at AS cost_rated_at\n FROM ai_model_call_usage AS usage\n JOIN executions AS execution ON execution.project_id = usage.project_id AND execution.id = usage.execution_id\n LEFT JOIN agent_runs AS direct_agent\n ON direct_agent.project_id = usage.project_id\n AND direct_agent.execution_id = usage.execution_id\n LEFT JOIN workflow_agent_node_runs AS workflow_agent\n ON workflow_agent.project_id = usage.project_id\n AND workflow_agent.execution_id = usage.execution_id\n LEFT JOIN workflow_node_runs AS workflow_node\n ON workflow_node.project_id = workflow_agent.project_id\n AND workflow_node.id = workflow_agent.node_run_id\n LEFT JOIN ai_model_call_valuations AS cost\n ON cost.project_id = usage.project_id AND cost.usage_record_id = usage.id\n WHERE ${SQLITE_ACCOUNTING_LIST_FILTER}\n ORDER BY usage.occurred_at DESC, usage.id ASC\n LIMIT ? OFFSET ?\n`\n\nconst SQLITE_ACCOUNTING_OVERVIEW_SQL = `\n WITH classified AS (\n SELECT usage.provider_id,\n usage.requested_model_id,\n usage.model_kind,\n usage.occurred_at,\n usage.input_tokens,\n usage.output_tokens,\n usage.uncached_input_tokens,\n usage.cache_read_input_tokens,\n usage.cache_write_input_tokens,\n usage.text_output_tokens,\n usage.reasoning_output_tokens,\n usage.audio_duration_ms,\n usage.image_output_tokens,\n usage.audio_output_tokens,\n usage.output_images,\n usage.input_characters,\n usage.reporting_status,\n CASE\n WHEN direct_agent.kind = 'conversation' THEN 'agent'\n WHEN workflow_agent.node_run_id IS NOT NULL THEN 'workflowAgent'\n ELSE NULL\n END AS attribution_agent_kind,\n workflow_node.node_id AS attribution_agent_step_id,\n COALESCE(workflow_node.workflow_id,\n CASE WHEN execution.executor_kind = 'workflow' THEN execution.authority_primitive_id END\n ) AS attribution_workflow_id,\n CASE\n WHEN cost.status = 'rated' THEN 'rated'\n WHEN cost.status = 'unpriceable' THEN 'unpriceable'\n ELSE 'unvalued'\n END AS valuation_status,\n CASE WHEN cost.status = 'rated' THEN cost.currency ELSE NULL END AS amount_currency,\n CASE WHEN cost.status = 'rated' THEN cost.amount_nanos ELSE NULL END AS amount_nanos\n FROM ai_model_call_usage AS usage\n JOIN executions AS execution ON execution.project_id = usage.project_id AND execution.id = usage.execution_id\n LEFT JOIN agent_runs AS direct_agent\n ON direct_agent.project_id = usage.project_id\n AND direct_agent.execution_id = usage.execution_id\n LEFT JOIN workflow_agent_node_runs AS workflow_agent\n ON workflow_agent.project_id = usage.project_id\n AND workflow_agent.execution_id = usage.execution_id\n LEFT JOIN workflow_node_runs AS workflow_node\n ON workflow_node.project_id = workflow_agent.project_id\n AND workflow_node.id = workflow_agent.node_run_id\n LEFT JOIN ai_model_call_valuations AS cost\n ON cost.project_id = usage.project_id AND cost.usage_record_id = usage.id\n WHERE usage.project_id = ? AND usage.occurred_at >= ? AND usage.occurred_at < ?\n AND (? IS NULL OR usage.provider_id = ?)\n AND (? IS NULL OR usage.requested_model_id = ?)\n ), expanded AS (\n SELECT 'totals' AS dimension, NULL AS key_1, NULL AS key_2, NULL AS key_3, NULL AS bucket_start,\n classified.*\n FROM classified\n UNION ALL\n SELECT 'series', NULL, NULL, NULL,\n CASE ?\n WHEN 'hour' THEN strftime('%Y-%m-%dT%H:00:00.000Z', occurred_at)\n WHEN 'day' THEN strftime('%Y-%m-%dT00:00:00.000Z', occurred_at)\n ELSE strftime(\n '%Y-%m-%dT00:00:00.000Z',\n occurred_at,\n printf('-%d days', (CAST(strftime('%w', occurred_at) AS INTEGER) + 6) % 7)\n )\n END,\n classified.*\n FROM classified\n UNION ALL\n SELECT 'model', provider_id, requested_model_id, NULL, NULL, classified.* FROM classified\n UNION ALL\n SELECT 'kind', model_kind, NULL, NULL, NULL, classified.* FROM classified\n UNION ALL\n SELECT 'agent', attribution_agent_kind, attribution_workflow_id, attribution_agent_step_id, NULL, classified.*\n FROM classified WHERE attribution_agent_kind IS NOT NULL\n UNION ALL\n SELECT 'workflow', attribution_workflow_id, NULL, NULL, NULL, classified.*\n FROM classified WHERE attribution_workflow_id IS NOT NULL\n )\n SELECT dimension,\n key_1,\n key_2,\n key_3,\n bucket_start,\n amount_currency,\n CAST(COUNT(*) AS TEXT) AS model_call_count,\n CAST(SUM(CASE WHEN reporting_status <> 'unavailable' THEN 1 ELSE 0 END) AS TEXT)\n AS reported_usage_call_count,\n CAST(SUM(CASE WHEN input_tokens IS NOT NULL AND output_tokens IS NOT NULL THEN 1 ELSE 0 END) AS TEXT)\n AS complete_usage_call_count,\n CAST(COUNT(input_tokens) AS TEXT) AS input_tokens_count,\n CAST(SUM(input_tokens) AS TEXT) AS input_tokens_sum,\n CAST(COUNT(output_tokens) AS TEXT) AS output_tokens_count,\n CAST(SUM(output_tokens) AS TEXT) AS output_tokens_sum,\n CAST(COUNT(uncached_input_tokens) AS TEXT) AS uncached_input_tokens_count,\n CAST(SUM(uncached_input_tokens) AS TEXT) AS uncached_input_tokens_sum,\n CAST(COUNT(cache_read_input_tokens) AS TEXT) AS cache_read_input_tokens_count,\n CAST(SUM(cache_read_input_tokens) AS TEXT) AS cache_read_input_tokens_sum,\n CAST(COUNT(cache_write_input_tokens) AS TEXT) AS cache_write_input_tokens_count,\n CAST(SUM(cache_write_input_tokens) AS TEXT) AS cache_write_input_tokens_sum,\n CAST(COUNT(text_output_tokens) AS TEXT) AS text_output_tokens_count,\n CAST(SUM(text_output_tokens) AS TEXT) AS text_output_tokens_sum,\n CAST(COUNT(reasoning_output_tokens) AS TEXT) AS reasoning_output_tokens_count,\n CAST(SUM(reasoning_output_tokens) AS TEXT) AS reasoning_output_tokens_sum,\n CAST(COUNT(audio_duration_ms) AS TEXT) AS audio_duration_ms_count,\n CAST(COUNT(image_output_tokens) AS TEXT) AS image_output_tokens_count,\n CAST(COUNT(audio_output_tokens) AS TEXT) AS audio_output_tokens_count,\n CAST(COUNT(output_images) AS TEXT) AS output_images_count,\n CAST(COUNT(input_characters) AS TEXT) AS input_characters_count,\n CAST(SUM(audio_duration_ms) AS TEXT) AS audio_duration_ms_sum,\n CAST(SUM(image_output_tokens) AS TEXT) AS image_output_tokens_sum,\n CAST(SUM(audio_output_tokens) AS TEXT) AS audio_output_tokens_sum,\n CAST(SUM(output_images) AS TEXT) AS output_images_sum,\n CAST(SUM(input_characters) AS TEXT) AS input_characters_sum,\n CAST(SUM(CASE WHEN valuation_status = 'rated' THEN 1 ELSE 0 END) AS TEXT)\n AS rated_call_count,\n CAST(SUM(CASE WHEN valuation_status = 'unpriceable' THEN 1 ELSE 0 END) AS TEXT)\n AS unpriceable_call_count,\n CAST(SUM(CASE WHEN valuation_status = 'unvalued' THEN 1 ELSE 0 END) AS TEXT)\n AS unvalued_call_count,\n CAST(SUM(amount_nanos / 1000000000000) AS TEXT) AS amount_high,\n CAST(SUM((amount_nanos / 1000000) % 1000000) AS TEXT) AS amount_middle,\n CAST(SUM(amount_nanos % 1000000) AS TEXT) AS amount_low\n FROM expanded\n GROUP BY dimension, key_1, key_2, key_3, bucket_start, amount_currency\n`\n\nfunction accountingListFilterParameters(\n query: ReturnType<typeof normalizeAiModelCallAccountingQuery>\n): readonly (string | null)[] {\n return [\n query.projectId,\n query.from.toISOString(),\n query.to.toISOString(),\n query.providerId ?? null,\n query.providerId ?? null,\n query.modelId ?? null,\n query.modelId ?? null,\n query.executionId ?? null,\n query.executionId ?? null,\n query.valuationStatus ?? null,\n query.valuationStatus ?? null,\n ]\n}\n\ninterface ValuationRow {\n readonly project_id: string\n readonly usage_record_id: string\n readonly status: \"rated\" | \"unpriceable\"\n readonly provider_id: string | null\n readonly model_id: string | null\n readonly currency: string | null\n readonly amount_nanos: string | null\n readonly reason: string | null\n readonly details: string\n readonly rated_at: string\n}\n\ninterface UsageRow {\n readonly project_id: string\n readonly id: string\n readonly execution_id: string\n readonly attempt: number\n readonly call_id: string\n readonly provider_id: string\n readonly requested_model_id: string\n readonly model_kind: AiModelCallUsageRecord[\"modelKind\"] | null\n readonly requested_reasoning: string | null\n readonly response_model_id: string | null\n readonly response_id: string\n readonly input_tokens: number | null\n readonly output_tokens: number | null\n readonly total_tokens: number | null\n readonly uncached_input_tokens: number | null\n readonly cache_read_input_tokens: number | null\n readonly cache_write_input_tokens: number | null\n readonly text_output_tokens: number | null\n readonly reasoning_output_tokens: number | null\n readonly audio_duration_ms: number | null\n readonly image_output_tokens: number | null\n readonly audio_output_tokens: number | null\n readonly output_images: number | null\n readonly input_characters: number | null\n readonly reporting_status: AiModelCallUsageRecord[\"usage\"][\"reportingStatus\"]\n readonly raw_usage: string | null\n readonly provider_ids: string | null\n readonly occurred_at: string\n readonly recorded_at: string\n}\n\ninterface JoinedRow extends UsageRow {\n readonly executor_kind: string | null\n readonly executor_id: string | null\n readonly primitive_id: string | null\n readonly attribution_kind: \"agent\" | \"subagent\" | \"workflowAgent\" | null\n readonly attribution_agent_step_id: string | null\n readonly attribution_agent_run_id: string | null\n readonly attribution_thread_id: string | null\n readonly attribution_parent_run_id: string | null\n readonly attribution_node_run_id: string | null\n readonly attribution_workflow_id: string | null\n readonly attribution_workflow_run_id: string | null\n readonly requester_group_ids: string\n readonly cost_status: ValuationRow[\"status\"] | null\n readonly cost_provider_id: string | null\n readonly cost_model_id: string | null\n readonly cost_currency: string | null\n readonly cost_amount_nanos: string | null\n readonly cost_reason: string | null\n readonly cost_details: string | null\n readonly cost_rated_at: string | null\n}\n\ninterface AggregateRow {\n readonly dimension: AiAccountingAggregateFragment[\"dimension\"]\n readonly key_1: string | null\n readonly key_2: string | null\n readonly key_3: string | null\n readonly bucket_start: string | null\n readonly amount_currency: string | null\n readonly model_call_count: string\n readonly reported_usage_call_count: string\n readonly complete_usage_call_count: string\n readonly input_tokens_count: string\n readonly input_tokens_sum: string | null\n readonly output_tokens_count: string\n readonly output_tokens_sum: string | null\n readonly uncached_input_tokens_count: string\n readonly uncached_input_tokens_sum: string | null\n readonly cache_read_input_tokens_count: string\n readonly cache_read_input_tokens_sum: string | null\n readonly cache_write_input_tokens_count: string\n readonly cache_write_input_tokens_sum: string | null\n readonly text_output_tokens_count: string\n readonly text_output_tokens_sum: string | null\n readonly reasoning_output_tokens_count: string\n readonly reasoning_output_tokens_sum: string | null\n readonly audio_duration_ms_count: string\n readonly image_output_tokens_count: string\n readonly audio_output_tokens_count: string\n readonly output_images_count: string\n readonly input_characters_count: string\n readonly audio_duration_ms_sum: string | null\n readonly image_output_tokens_sum: string | null\n readonly audio_output_tokens_sum: string | null\n readonly output_images_sum: string | null\n readonly input_characters_sum: string | null\n readonly rated_call_count: string\n readonly unpriceable_call_count: string\n readonly unvalued_call_count: string\n readonly amount_high: string | null\n readonly amount_middle: string | null\n readonly amount_low: string | null\n}\n\ninterface CountRow {\n readonly total: string\n}\n\ninterface SummaryRow {\n readonly execution_id: string\n readonly status: ValuationRow[\"status\"] | null\n readonly currency: string | null\n readonly amount_nanos: string | null\n}\n\nfunction aggregateFragmentFromRow(row: AggregateRow): AiAccountingAggregateFragment {\n const dimensionKeys =\n row.dimension === \"model\"\n ? { providerId: required(row.key_1), modelId: required(row.key_2) }\n : row.dimension === \"kind\"\n ? withModelKind(aiAccountingModelKind(row.key_1))\n : row.dimension === \"agent\"\n ? {\n agentKind: required(row.key_1) as \"agent\" | \"workflowAgent\",\n ...(row.key_1 === \"workflowAgent\"\n ? { workflowId: required(row.key_2), agentStepId: required(row.key_3) }\n : {}),\n }\n : row.dimension === \"workflow\"\n ? { workflowId: required(row.key_1) }\n : row.dimension === \"series\"\n ? { start: new Date(required(row.bucket_start)) }\n : {}\n return {\n dimension: row.dimension,\n ...dimensionKeys,\n modelCallCount: row.model_call_count,\n usage: {\n reportedCallCount: row.reported_usage_call_count,\n completeCallCount: row.complete_usage_call_count,\n inputTokens: meterFragment(row.input_tokens_count, row.input_tokens_sum),\n outputTokens: meterFragment(row.output_tokens_count, row.output_tokens_sum),\n uncachedInputTokens: meterFragment(\n row.uncached_input_tokens_count,\n row.uncached_input_tokens_sum\n ),\n cacheReadInputTokens: meterFragment(\n row.cache_read_input_tokens_count,\n row.cache_read_input_tokens_sum\n ),\n cacheWriteInputTokens: meterFragment(\n row.cache_write_input_tokens_count,\n row.cache_write_input_tokens_sum\n ),\n textOutputTokens: meterFragment(row.text_output_tokens_count, row.text_output_tokens_sum),\n reasoningOutputTokens: meterFragment(\n row.reasoning_output_tokens_count,\n row.reasoning_output_tokens_sum\n ),\n audioDurationMs: meterFragment(row.audio_duration_ms_count, row.audio_duration_ms_sum),\n imageOutputTokens: meterFragment(row.image_output_tokens_count, row.image_output_tokens_sum),\n audioOutputTokens: meterFragment(row.audio_output_tokens_count, row.audio_output_tokens_sum),\n outputImages: meterFragment(row.output_images_count, row.output_images_sum),\n inputCharacters: meterFragment(row.input_characters_count, row.input_characters_sum),\n },\n costs: {\n ...(row.amount_currency === null ||\n row.amount_high === null ||\n row.amount_middle === null ||\n row.amount_low === null\n ? {}\n : {\n amount: {\n currency: row.amount_currency,\n amountNanos: sqliteAggregateAmount(row),\n },\n }),\n ratedCallCount: row.rated_call_count,\n unpriceableCallCount: row.unpriceable_call_count,\n unvaluedCallCount: row.unvalued_call_count,\n },\n }\n}\n\nfunction meterFragment(presentCallCount: string, total: string | null) {\n return { presentCallCount, total }\n}\n\nfunction sqliteAggregateAmount(\n row: Pick<AggregateRow, \"amount_high\" | \"amount_middle\" | \"amount_low\">\n): string {\n return (\n BigInt(required(row.amount_high)) * 1_000_000_000_000n +\n BigInt(required(row.amount_middle)) * 1_000_000n +\n BigInt(required(row.amount_low))\n ).toString()\n}\n\nfunction accountingItemFromRow(row: JoinedRow): AiAccountingRecordSetItem {\n const usage = usageFromRow(row, parseStringArray(row.requester_group_ids))\n const cost = row.cost_status === null ? undefined : costFromJoinedRow(row)\n const attribution =\n row.attribution_kind === null\n ? directModelCallAttribution(row.executor_kind, row.executor_id, row.primitive_id)\n : row.attribution_kind === \"agent\"\n ? {\n kind: \"agent\" as const,\n agentRunId: required(row.attribution_agent_run_id),\n threadId: required(row.attribution_thread_id),\n }\n : row.attribution_kind === \"subagent\"\n ? {\n kind: \"subagent\" as const,\n subagentRunId: required(row.attribution_agent_run_id),\n parentRunId: required(row.attribution_parent_run_id),\n }\n : {\n kind: \"workflowAgent\" as const,\n agentStepId: required(row.attribution_agent_step_id),\n nodeRunId: required(row.attribution_node_run_id),\n workflowId: required(row.attribution_workflow_id),\n workflowRunId: required(row.attribution_workflow_run_id),\n }\n return {\n usage,\n ...(attribution ? { attribution } : {}),\n ...(cost ? { cost } : {}),\n }\n}\n\nfunction usageFromRow(row: UsageRow, requesterGroupIds: readonly string[]): AiModelCallUsageRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n executionId: row.execution_id,\n attempt: row.attempt,\n callId: row.call_id,\n requesterGroupIds,\n providerId: row.provider_id,\n ...(row.provider_ids === null\n ? {}\n : { providerIds: normalizeModelProviderIds(JSON.parse(row.provider_ids)) }),\n requestedModelId: row.requested_model_id,\n ...(row.model_kind === null ? {} : { modelKind: row.model_kind }),\n ...(row.requested_reasoning === null\n ? {}\n : { requestedReasoning: requestedReasoningFromRow(row.requested_reasoning) }),\n ...(row.response_model_id === null ? {} : { responseModelId: row.response_model_id }),\n responseId: row.response_id,\n usage: {\n ...(row.input_tokens === null ? {} : { inputTokens: row.input_tokens }),\n ...(row.output_tokens === null ? {} : { outputTokens: row.output_tokens }),\n ...(row.total_tokens === null ? {} : { totalTokens: row.total_tokens }),\n ...(row.uncached_input_tokens === null\n ? {}\n : { uncachedInputTokens: row.uncached_input_tokens }),\n ...(row.cache_read_input_tokens === null\n ? {}\n : { cacheReadInputTokens: row.cache_read_input_tokens }),\n ...(row.cache_write_input_tokens === null\n ? {}\n : { cacheWriteInputTokens: row.cache_write_input_tokens }),\n ...(row.text_output_tokens === null ? {} : { textOutputTokens: row.text_output_tokens }),\n ...(row.reasoning_output_tokens === null\n ? {}\n : { reasoningOutputTokens: row.reasoning_output_tokens }),\n ...(row.audio_duration_ms === null ? {} : { audioDurationMs: row.audio_duration_ms }),\n ...(row.image_output_tokens === null ? {} : { imageOutputTokens: row.image_output_tokens }),\n ...(row.audio_output_tokens === null ? {} : { audioOutputTokens: row.audio_output_tokens }),\n ...(row.output_images === null ? {} : { outputImages: row.output_images }),\n ...(row.input_characters === null ? {} : { inputCharacters: row.input_characters }),\n reportingStatus: row.reporting_status,\n },\n ...(row.raw_usage === null\n ? {}\n : { rawUsage: JSON.parse(row.raw_usage) as ReadonlyJsonObject }),\n occurredAt: new Date(row.occurred_at),\n recordedAt: new Date(row.recorded_at),\n }\n}\n\nfunction rowToCost(row: ValuationRow): AiModelCallCostRecord {\n return costRecord({\n projectId: row.project_id,\n usageId: row.usage_record_id,\n status: row.status,\n providerId: row.provider_id,\n modelId: row.model_id,\n currency: row.currency,\n amountNanos: row.amount_nanos,\n reason: row.reason,\n details: row.details,\n ratedAt: row.rated_at,\n })\n}\n\nfunction costFromJoinedRow(row: JoinedRow): AiModelCallCostRecord {\n return costRecord({\n projectId: row.project_id,\n usageId: row.id,\n status: required(row.cost_status),\n providerId: row.cost_provider_id,\n modelId: row.cost_model_id,\n currency: row.cost_currency,\n amountNanos: row.cost_amount_nanos,\n reason: row.cost_reason,\n details: required(row.cost_details),\n ratedAt: required(row.cost_rated_at),\n })\n}\n\nfunction costRecord(input: {\n projectId: string\n usageId: string\n status: ValuationRow[\"status\"]\n providerId: string | null\n modelId: string | null\n currency: string | null\n amountNanos: string | null\n reason: string | null\n details: string\n ratedAt: string\n}): AiModelCallCostRecord {\n const details = parseAiModelCallCostDetails(input.details)\n const priceSource =\n details.priceSource === undefined\n ? undefined\n : { ...details.priceSource, observedAt: new Date(details.priceSource.observedAt) }\n const base = {\n ...(details.estimate === undefined ? {} : { estimate: details.estimate }),\n projectId: input.projectId,\n usageRecordId: input.usageId,\n pricingContext: details.pricingContext,\n ratedAt: new Date(input.ratedAt),\n }\n if (input.status === \"rated\") {\n return normalizeAiModelCallCostRecord({\n ...base,\n status: \"rated\",\n billingIdentity: { providerId: required(input.providerId), modelId: required(input.modelId) },\n priceSource: required(priceSource),\n money: { currency: required(input.currency), amountNanos: required(input.amountNanos) },\n components: required(details.components),\n })\n }\n return normalizeAiModelCallCostRecord({\n ...base,\n status: \"unpriceable\",\n ...(input.providerId && input.modelId\n ? { billingIdentity: { providerId: input.providerId, modelId: input.modelId } }\n : {}),\n ...(priceSource === undefined ? {} : { priceSource }),\n reason: required(input.reason) as Extract<\n AiModelCallCostRecord,\n { status: \"unpriceable\" }\n >[\"reason\"],\n ...(details.missingMeters ? { missingMeters: details.missingMeters } : {}),\n })\n}\n\nfunction aggregateSummaryRows(\n ids: readonly string[],\n rows: readonly SummaryRow[]\n): AiCostSummary[] {\n const map = new Map(ids.map((id) => [id, accumulator()]))\n for (const row of rows) {\n const value = map.get(row.execution_id)\n if (!value) continue\n if (row.status === null) value.unvaluedCallCount += 1\n else if (row.status === \"unpriceable\") value.unpriceableCallCount += 1\n else {\n value.ratedCallCount += 1\n add(value.amounts, required(row.currency), required(row.amount_nanos))\n }\n }\n return ids.map((id) => finish(map.get(id)!))\n}\n\ninterface Accumulator {\n amounts: Map<string, bigint>\n ratedCallCount: number\n unpriceableCallCount: number\n unvaluedCallCount: number\n}\n\nfunction accumulator(): Accumulator {\n return {\n amounts: new Map(),\n ratedCallCount: 0,\n unpriceableCallCount: 0,\n unvaluedCallCount: 0,\n }\n}\n\nfunction finish(value: Accumulator): AiCostSummary {\n return {\n amounts: [...value.amounts]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([currency, amount]) => ({ currency, amountNanos: amount.toString() })),\n ratedCallCount: value.ratedCallCount,\n unpriceableCallCount: value.unpriceableCallCount,\n unvaluedCallCount: value.unvaluedCallCount,\n }\n}\n\nfunction add(amounts: Map<string, bigint>, currency: string, amount: string): void {\n amounts.set(currency, (amounts.get(currency) ?? 0n) + BigInt(amount))\n}\n\nfunction assertCostMatchesUsage(\n record: AiModelCallCostRecord,\n usage: AiModelCallUsageRecord\n): void {\n if (!aiModelCallCostMatchesUsage(record, usage)) {\n throw new AiCostStorageError(\n \"cost_mismatch\",\n `[SixbSqlite] AI valuation for usage '${record.usageRecordId}' does not match its usage record.`\n )\n }\n}\n\nfunction missingUsage(record: { projectId: string; usageRecordId: string }) {\n return new AiCostStorageError(\n \"missing_usage\",\n `[SixbSqlite] AI usage '${record.usageRecordId}' does not exist.`\n )\n}\n\nfunction parseStringArray(value: string): string[] {\n const parsed: unknown = JSON.parse(value)\n if (!Array.isArray(parsed) || parsed.some((item) => typeof item !== \"string\")) {\n throw new Error(\"[SixbSqlite] AI requester group ids are invalid.\")\n }\n return parsed\n}\n\nfunction assertNonBlank(value: string, field: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new TypeError(`[Sixb] AI ${field} must be nonblank.`)\n }\n}\n\nfunction safeSqlCount(value: string, field: string): number {\n if (!/^(0|[1-9]\\d*)$/.test(value)) {\n throw new Error(`[SixbSqlite] AI accounting ${field} is invalid.`)\n }\n const count = Number(value)\n if (!Number.isSafeInteger(count)) {\n throw new TypeError(`[Sixb] AI accounting ${field} exceeds the safe integer range.`)\n }\n return count\n}\n\nfunction required<T>(value: T | null | undefined): T {\n if (value === null || value === undefined) {\n throw new Error(\"[SixbSqlite] AI valuation column is unexpectedly null.\")\n }\n return value\n}\n\nfunction withModelKind(modelKind: AiAccountingAggregateFragment[\"modelKind\"]) {\n return modelKind === undefined ? {} : { modelKind }\n}\n",
22
+ "import {\n type AiModelCallGroupRow,\n aiModelCallGroupFragmentFromRow,\n buildAiModelCallGroupsFromFragments,\n normalizeAiModelCallAccountingQuery,\n TOKENLESS_MODEL_KINDS,\n} from \"@sixb/core/internal/ai-cost-storage-provider\"\nimport type { ListAiModelCallGroupsInput, ListAiModelCallGroupsResult } from \"@sixb/core/storage\"\nimport type { SqliteStoreConnection } from \"./transactions\"\n\n/** Paginate initiating executions, then aggregate their matching calls without loading usage payloads. */\nexport async function listAiModelCallGroups(\n connection: SqliteStoreConnection,\n input: ListAiModelCallGroupsInput\n): Promise<ListAiModelCallGroupsResult> {\n const query = normalizeAiModelCallAccountingQuery(input)\n const parameters = [\n query.projectId,\n query.from.toISOString(),\n query.to.toISOString(),\n query.providerId ?? null,\n query.modelId ?? null,\n query.valuationStatus ?? null,\n ]\n const count = connection.db.query(COUNT_SQL).get(...parameters) as { total: string }\n const rows = connection.db\n .query(PAGE_SQL)\n .all(...parameters, query.limit, query.offset) as AiModelCallGroupRow[]\n const total = Number(count?.total)\n if (!Number.isSafeInteger(total) || total < 0)\n throw new RangeError(\"[Sixb] Invalid model-call group count.\")\n const items = buildAiModelCallGroupsFromFragments(rows.map(aiModelCallGroupFragmentFromRow))\n return { items, total, hasMore: query.offset + items.length < total }\n}\n\n// Fixed kind names, never user input.\nconst TOKENLESS_KINDS = TOKENLESS_MODEL_KINDS.map((kind) => `'${kind}'`).join(\", \")\n\nconst FILTERED_SQL = `\nWITH filtered AS (\n SELECT COALESCE(root_agent.execution_id, usage.execution_id) AS root_execution_id,\n usage.execution_id, usage.provider_id, usage.requested_model_id, usage.occurred_at,\n usage.total_tokens, usage.model_kind, usage.output_images, usage.input_characters,\n usage.audio_duration_ms,\n execution.executor_kind, execution.executor_id, execution.authority_primitive_id AS primitive_id,\n COALESCE(cost.status, 'unvalued') AS valuation_status,\n cost.currency AS amount_currency, cost.amount_nanos,\n root_agent.id AS root_agent_run_id,\n root_agent.thread_id AS root_thread_id,\n direct_agent.kind AS direct_kind,\n direct_agent.id AS direct_run_id,\n direct_agent.parent_run_id AS parent_run_id,\n workflow_node.node_id AS workflow_agent_step_id,\n workflow_agent.node_run_id AS workflow_node_run_id,\n workflow_node.workflow_id AS workflow_id,\n workflow_node.workflow_run_id AS workflow_run_id\n FROM ai_model_call_usage AS usage\n JOIN executions AS execution ON execution.project_id = usage.project_id AND execution.id = usage.execution_id\n LEFT JOIN agent_runs AS direct_agent\n ON direct_agent.project_id = usage.project_id AND direct_agent.execution_id = usage.execution_id\n LEFT JOIN agent_runs AS root_agent\n ON root_agent.project_id = usage.project_id\n AND root_agent.id = COALESCE(direct_agent.parent_run_id, direct_agent.id)\n LEFT JOIN workflow_agent_node_runs AS workflow_agent\n ON workflow_agent.project_id = usage.project_id AND workflow_agent.execution_id = usage.execution_id\n LEFT JOIN workflow_node_runs AS workflow_node\n ON workflow_node.project_id = workflow_agent.project_id AND workflow_node.id = workflow_agent.node_run_id\n LEFT JOIN ai_model_call_valuations AS cost\n ON cost.project_id = usage.project_id AND cost.usage_record_id = usage.id\n WHERE usage.project_id = ?1\n AND usage.occurred_at >= ?2\n AND usage.occurred_at < ?3\n AND (?4 IS NULL OR usage.provider_id = ?4)\n AND (?5 IS NULL OR usage.requested_model_id = ?5)\n AND (?6 IS NULL OR COALESCE(cost.status, 'unvalued') = ?6)\n), roots AS (\n SELECT root_execution_id, MAX(occurred_at) AS last_call_at\n FROM filtered GROUP BY root_execution_id\n)\n`\nconst COUNT_SQL = `${FILTERED_SQL} SELECT CAST(COUNT(*) AS TEXT) AS total FROM roots`\nconst PAGE_SQL = `${FILTERED_SQL}, page AS (\n SELECT root_execution_id FROM roots\n ORDER BY last_call_at DESC, root_execution_id ASC LIMIT ?7 OFFSET ?8\n)\nSELECT filtered.root_execution_id, execution_id, provider_id, requested_model_id,\n MIN(occurred_at) AS first_call_at, MAX(occurred_at) AS last_call_at,\n CAST(COUNT(*) AS TEXT) AS call_count,\n CAST(COUNT(total_tokens) AS TEXT) AS token_count,\n CAST(COUNT(CASE WHEN total_tokens IS NULL AND model_kind IN (${TOKENLESS_KINDS}) THEN 1 END) AS TEXT)\n AS tokenless_count,\n CAST(SUM(total_tokens) AS TEXT) AS total_tokens,\n CAST(SUM(output_images) AS TEXT) AS output_images,\n CAST(SUM(input_characters) AS TEXT) AS input_characters,\n CAST(SUM(audio_duration_ms) AS TEXT) AS audio_duration_ms,\n valuation_status, amount_currency,\n CAST(SUM(amount_nanos / 1000000000000) AS TEXT) AS amount_high,\n CAST(SUM((amount_nanos / 1000000) % 1000000) AS TEXT) AS amount_middle,\n CAST(SUM(amount_nanos % 1000000) AS TEXT) AS amount_low,\n MAX(root_agent_run_id) AS root_agent_run_id,\n MAX(executor_kind) AS executor_kind, MAX(executor_id) AS executor_id, MAX(primitive_id) AS primitive_id,\n MAX(root_thread_id) AS root_thread_id,\n MAX(direct_kind) AS direct_kind,\n MAX(direct_run_id) AS direct_run_id,\n MAX(parent_run_id) AS parent_run_id,\n MAX(workflow_agent_step_id) AS workflow_agent_step_id,\n MAX(workflow_node_run_id) AS workflow_node_run_id,\n MAX(workflow_id) AS workflow_id,\n MAX(workflow_run_id) AS workflow_run_id\nFROM filtered JOIN page ON page.root_execution_id = filtered.root_execution_id\nGROUP BY filtered.root_execution_id, execution_id, provider_id, requested_model_id,\n valuation_status, amount_currency\n`\n",
23
+ "import type { FileRef } from \"@sixb/core/blob-storage/server\"\nimport {\n assertAiUsageExecutionId,\n assertSameCallExecution,\n normalizeAiModelCallFilesRecord,\n normalizeAiModelCallRecord,\n} from \"@sixb/core/internal/storage\"\nimport { isModelReasoning, normalizeModelProviderIds } from \"@sixb/core/models\"\nimport type { ReadonlyJsonObject } from \"@sixb/core/storage\"\nimport {\n type AiModelCallFilesRecord,\n type AiModelCallUsageInput,\n type AiModelCallUsageRecord,\n type AiUsageExecutionSummary,\n type AiUsageStorage,\n AiUsageStorageError,\n aggregateAiModelCallUsage,\n type GetAiModelCallFilesInput,\n type GetLatestAiModelCallForExecutionInput,\n type RecordAiModelCallFilesInput,\n type RecordAiModelCallInput,\n type RecordAiModelCallResult,\n type SummarizeAiUsageExecutionInput,\n type SummarizeAiUsageExecutionsInput,\n} from \"@sixb/core/storage\"\nimport { isUniqueConstraintError } from \"./storage-errors\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n runImmediateTransaction,\n type SqliteStoreConnection,\n} from \"./transactions\"\n\nexport interface SqliteAiUsageStorageOptions {\n readonly path?: string\n readonly connection?: SqliteStoreConnection\n}\n\n/** SQLite-backed append-only model-call usage ledger. */\nexport class SqliteAiUsageStorage implements AiUsageStorage {\n private readonly connection: SqliteStoreConnection\n\n constructor(options: SqliteAiUsageStorageOptions = {}) {\n this.connection = openSqliteStoreConnection(options)\n }\n\n async recordModelCall(input: RecordAiModelCallInput): Promise<RecordAiModelCallResult> {\n const record = normalizeAiModelCallRecord(input)\n return runImmediateTransaction(this.connection.db, () => {\n const existing = this.findByIdempotencyKey(record)\n if (existing) return { record: existing, created: false }\n this.assertExecutionExists(record.projectId, record.executionId)\n\n try {\n this.insertRecord(record)\n } catch (error) {\n if (!isUniqueConstraintError(error)) throw error\n\n const concurrent = this.findByIdempotencyKey(record)\n if (concurrent) return { record: concurrent, created: false }\n throw new AiUsageStorageError(\n \"duplicate_id\",\n `[SixbSqlite] AI usage record '${record.id}' already exists for project '${record.projectId}'.`\n )\n }\n\n for (const groupId of record.requesterGroupIds) {\n this.connection.db\n .query(\n `\n INSERT INTO ai_model_call_usage_groups (\n project_id, usage_record_id, group_id, occurred_at\n ) VALUES (?, ?, ?, ?)\n `\n )\n .run(record.projectId, record.id, groupId, record.occurredAt.toISOString())\n }\n\n return { record: this.requireById(record.projectId, record.id), created: true }\n })\n }\n\n async summarizeExecution(\n input: SummarizeAiUsageExecutionInput\n ): Promise<AiUsageExecutionSummary> {\n const [summary] = await this.summarizeExecutions({\n projectId: input.projectId,\n executionIds: [input.executionId],\n })\n return summary!\n }\n\n async getLatestForExecution(\n input: GetLatestAiModelCallForExecutionInput\n ): Promise<AiModelCallUsageRecord | null> {\n assertNonBlankProjectId(input.projectId)\n assertAiUsageExecutionId(input.executionId)\n const row = this.connection.db\n .query(\n `\n SELECT * FROM ai_model_call_usage\n WHERE project_id = ? AND execution_id = ?\n ORDER BY occurred_at DESC, id DESC\n LIMIT 1\n `\n )\n .get(input.projectId, input.executionId) as AiUsageRow | null\n return row ? this.rowToRecord(row) : null\n }\n\n async summarizeExecutions(\n input: SummarizeAiUsageExecutionsInput\n ): Promise<readonly AiUsageExecutionSummary[]> {\n assertNonBlankProjectId(input.projectId)\n for (const executionId of input.executionIds) assertAiUsageExecutionId(executionId)\n if (input.executionIds.length === 0) return []\n\n const rows = this.executionRows(input)\n return aggregateExecutionRows(input.executionIds, rows)\n }\n\n async recordModelCallFiles(input: RecordAiModelCallFilesInput): Promise<AiModelCallFilesRecord> {\n const record = normalizeAiModelCallFilesRecord(input)\n return runImmediateTransaction(this.connection.db, () => {\n const existing = this.findCallFiles(record.projectId, record.callId)\n if (existing) return assertSameCallExecution(existing, record)\n this.assertExecutionExists(record.projectId, record.executionId)\n this.connection.db\n .query(\n `\n INSERT INTO ai_model_call_files (project_id, call_id, execution_id, files, recorded_at)\n VALUES (?, ?, ?, ?, ?)\n `\n )\n .run(\n record.projectId,\n record.callId,\n record.executionId,\n JSON.stringify(record.files),\n record.recordedAt.toISOString()\n )\n return record\n })\n }\n\n async getModelCallFiles(input: GetAiModelCallFilesInput): Promise<AiModelCallFilesRecord | null> {\n assertNonBlankProjectId(input.projectId)\n return this.findCallFiles(input.projectId, input.callId)\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n\n private findCallFiles(projectId: string, callId: string): AiModelCallFilesRecord | null {\n const row = this.connection.db\n .query(\"SELECT * FROM ai_model_call_files WHERE project_id = ? AND call_id = ?\")\n .get(projectId, callId) as CallFilesRow | null\n return row\n ? {\n projectId: row.project_id,\n executionId: row.execution_id,\n callId: row.call_id,\n files: JSON.parse(row.files) as FileRef[],\n recordedAt: new Date(row.recorded_at),\n }\n : null\n }\n\n private insertRecord(record: AiModelCallUsageRecord): void {\n this.connection.db\n .query(\n `\n INSERT INTO ai_model_call_usage (\n project_id,\n id,\n execution_id,\n attempt,\n call_id,\n provider_id,\n provider_ids,\n requested_model_id,\n model_kind,\n requested_reasoning,\n response_model_id,\n response_id,\n input_tokens,\n output_tokens,\n total_tokens,\n uncached_input_tokens,\n cache_read_input_tokens,\n cache_write_input_tokens,\n text_output_tokens,\n reasoning_output_tokens,\n audio_duration_ms,\n image_output_tokens,\n audio_output_tokens,\n output_images,\n input_characters,\n reporting_status,\n raw_usage,\n occurred_at,\n recorded_at\n ) VALUES (\n ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?\n )\n `\n )\n .run(\n record.projectId,\n record.id,\n record.executionId,\n record.attempt,\n record.callId,\n record.providerId,\n record.providerIds === undefined ? null : JSON.stringify(record.providerIds),\n record.requestedModelId,\n record.modelKind ?? null,\n record.requestedReasoning === undefined ? null : JSON.stringify(record.requestedReasoning),\n record.responseModelId ?? null,\n record.responseId,\n record.usage.inputTokens ?? null,\n record.usage.outputTokens ?? null,\n record.usage.totalTokens ?? null,\n record.usage.uncachedInputTokens ?? null,\n record.usage.cacheReadInputTokens ?? null,\n record.usage.cacheWriteInputTokens ?? null,\n record.usage.textOutputTokens ?? null,\n record.usage.reasoningOutputTokens ?? null,\n record.usage.audioDurationMs ?? null,\n record.usage.imageOutputTokens ?? null,\n record.usage.audioOutputTokens ?? null,\n record.usage.outputImages ?? null,\n record.usage.inputCharacters ?? null,\n record.usage.reportingStatus,\n record.rawUsage === undefined ? null : JSON.stringify(record.rawUsage),\n record.occurredAt.toISOString(),\n record.recordedAt.toISOString()\n )\n }\n\n private findByIdempotencyKey(\n record: Pick<\n AiModelCallUsageRecord,\n \"projectId\" | \"executionId\" | \"attempt\" | \"callId\" | \"responseId\"\n >\n ): AiModelCallUsageRecord | null {\n const row = this.connection.db\n .query(\n `\n SELECT * FROM ai_model_call_usage\n WHERE project_id = ?\n AND execution_id = ?\n AND attempt = ?\n AND call_id = ?\n AND response_id = ?\n `\n )\n .get(\n record.projectId,\n record.executionId,\n record.attempt,\n record.callId,\n record.responseId\n ) as AiUsageRow | null\n return row ? this.rowToRecord(row) : null\n }\n\n private requireById(projectId: string, id: string): AiModelCallUsageRecord {\n const row = this.connection.db\n .query(\"SELECT * FROM ai_model_call_usage WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AiUsageRow | null\n if (!row) throw new Error(`[SixbSqlite] AI usage record '${id}' disappeared after insert.`)\n return this.rowToRecord(row)\n }\n\n private rowToRecord(row: AiUsageRow): AiModelCallUsageRecord {\n const groupRows = this.connection.db\n .query(\n `\n SELECT group_id FROM ai_model_call_usage_groups\n WHERE project_id = ? AND usage_record_id = ?\n ORDER BY group_id\n `\n )\n .all(row.project_id, row.id) as Array<{ group_id: string }>\n\n return {\n id: row.id,\n projectId: row.project_id,\n executionId: row.execution_id,\n attempt: row.attempt,\n callId: row.call_id,\n requesterGroupIds: groupRows.map((group) => group.group_id),\n providerId: row.provider_id,\n ...(row.provider_ids === null\n ? {}\n : { providerIds: normalizeModelProviderIds(JSON.parse(row.provider_ids)) }),\n requestedModelId: row.requested_model_id,\n ...(row.model_kind === null ? {} : { modelKind: row.model_kind }),\n ...(row.requested_reasoning === null\n ? {}\n : { requestedReasoning: requestedReasoningFromRow(row.requested_reasoning) }),\n ...(row.response_model_id === null ? {} : { responseModelId: row.response_model_id }),\n responseId: row.response_id,\n usage: {\n ...usageFromRow(row),\n ...(row.total_tokens === null ? {} : { totalTokens: row.total_tokens }),\n reportingStatus: row.reporting_status,\n },\n ...(row.raw_usage === null\n ? {}\n : { rawUsage: JSON.parse(row.raw_usage) as ReadonlyJsonObject }),\n occurredAt: new Date(row.occurred_at),\n recordedAt: new Date(row.recorded_at),\n }\n }\n\n private executionRows(input: SummarizeAiUsageExecutionsInput): AiUsageRow[] {\n const requested = JSON.stringify([...new Set(input.executionIds)])\n return this.connection.db\n .query(\n `\n WITH requested AS (\n SELECT DISTINCT value AS execution_id\n FROM json_each(?)\n )\n SELECT usage.* FROM requested\n JOIN ai_model_call_usage AS usage\n ON usage.project_id = ?\n AND usage.execution_id = requested.execution_id\n `\n )\n .all(requested, input.projectId) as AiUsageRow[]\n }\n\n private assertExecutionExists(projectId: string, executionId: string): void {\n const execution = this.connection.db\n .query(\"SELECT 1 FROM executions WHERE project_id = ? AND id = ?\")\n .get(projectId, executionId)\n if (execution) return\n throw new AiUsageStorageError(\n \"missing_execution\",\n `[SixbSqlite] AI usage execution '${executionId}' does not exist in project '${projectId}'.`\n )\n }\n}\n\ninterface CallFilesRow {\n readonly project_id: string\n readonly call_id: string\n readonly execution_id: string\n readonly files: string\n readonly recorded_at: string\n}\n\ninterface AiUsageRow {\n readonly project_id: string\n readonly id: string\n readonly execution_id: string\n readonly attempt: number\n readonly call_id: string\n readonly provider_id: string\n readonly provider_ids: string | null\n readonly requested_model_id: string\n readonly model_kind: AiModelCallUsageRecord[\"modelKind\"] | null\n readonly requested_reasoning: string | null\n readonly response_model_id: string | null\n readonly response_id: string\n readonly input_tokens: number | null\n readonly output_tokens: number | null\n readonly total_tokens: number | null\n readonly uncached_input_tokens: number | null\n readonly cache_read_input_tokens: number | null\n readonly cache_write_input_tokens: number | null\n readonly text_output_tokens: number | null\n readonly reasoning_output_tokens: number | null\n readonly audio_duration_ms: number | null\n readonly image_output_tokens: number | null\n readonly audio_output_tokens: number | null\n readonly output_images: number | null\n readonly input_characters: number | null\n readonly reporting_status: AiModelCallUsageRecord[\"usage\"][\"reportingStatus\"]\n readonly raw_usage: string | null\n readonly occurred_at: string\n readonly recorded_at: string\n}\n\nfunction aggregateExecutionRows(\n executionIds: readonly string[],\n rows: readonly AiUsageRow[]\n): readonly AiUsageExecutionSummary[] {\n const usageByExecutionId = new Map<string, AiModelCallUsageInput[]>()\n for (const executionId of executionIds) usageByExecutionId.set(executionId, [])\n for (const row of rows) {\n usageByExecutionId.get(row.execution_id)?.push(usageFromRow(row))\n }\n return executionIds.map((executionId) => {\n const usages = usageByExecutionId.get(executionId) ?? []\n return {\n modelCallCount: usages.length,\n usage: aggregateAiModelCallUsage(usages),\n }\n })\n}\n\nfunction usageFromRow(row: AiUsageRow): AiModelCallUsageInput {\n return {\n ...(row.input_tokens === null ? {} : { inputTokens: row.input_tokens }),\n ...(row.output_tokens === null ? {} : { outputTokens: row.output_tokens }),\n ...(row.uncached_input_tokens === null\n ? {}\n : { uncachedInputTokens: row.uncached_input_tokens }),\n ...(row.cache_read_input_tokens === null\n ? {}\n : { cacheReadInputTokens: row.cache_read_input_tokens }),\n ...(row.cache_write_input_tokens === null\n ? {}\n : { cacheWriteInputTokens: row.cache_write_input_tokens }),\n ...(row.text_output_tokens === null ? {} : { textOutputTokens: row.text_output_tokens }),\n ...(row.reasoning_output_tokens === null\n ? {}\n : { reasoningOutputTokens: row.reasoning_output_tokens }),\n ...(row.audio_duration_ms === null ? {} : { audioDurationMs: row.audio_duration_ms }),\n ...(row.image_output_tokens === null ? {} : { imageOutputTokens: row.image_output_tokens }),\n ...(row.audio_output_tokens === null ? {} : { audioOutputTokens: row.audio_output_tokens }),\n ...(row.output_images === null ? {} : { outputImages: row.output_images }),\n ...(row.input_characters === null ? {} : { inputCharacters: row.input_characters }),\n }\n}\n\nexport function requestedReasoningFromRow(\n value: string\n): AiModelCallUsageRecord[\"requestedReasoning\"] {\n const parsed: unknown = JSON.parse(value)\n if (!isModelReasoning(parsed)) {\n throw new Error(\"[SixbSqlite] Stored AI usage requested reasoning is invalid.\")\n }\n return parsed\n}\n\nfunction assertNonBlankProjectId(projectId: string): void {\n if (typeof projectId !== \"string\" || projectId.trim().length === 0) {\n throw new TypeError(\"[Sixb] AI usage projectId must be nonblank.\")\n }\n}\n",
21
24
  "import type { SQLQueryBindings } from \"bun:sqlite\"\nimport {\n type AiLimitAccountingEntry,\n aiLimitAmountKey,\n aiLimitMeterApplies,\n aiLimitQuantityFromAmount,\n aiLimitReservationBuckets,\n aiLimitReservationRequestKey,\n aiLimitReservationRequestMatches,\n aiLimitSubjectFromParts,\n aiLimitSubjectKey,\n aiLimitSubjectParts,\n aiLimitSubjectsFromAccountingEntry,\n assertAiLimitAccountingMatchesReservation,\n assertNonBlank,\n cloneValidDate,\n type NormalizedAiLimitAmount,\n normalizeAiLimitAmount,\n normalizeAiLimitQuantities,\n normalizeAiModelCallReservationIdentity,\n normalizeCreateAiLimitPolicy,\n normalizeReserveAiModelCall,\n normalizeUpdateAiLimitPolicy,\n resolveAiLimitActual,\n} from \"@sixb/core/internal/ai-limit-storage-provider\"\nimport type {\n AiLimitPeriod,\n AiLimitPolicy,\n AiLimitPolicyStatus,\n AiLimitQuantity,\n AiLimitReservationBucket,\n AiLimitStorage,\n AiLimitSubject,\n AiModelCallReservation,\n CreateAiLimitPolicyInput,\n DeleteAiLimitPolicyInput,\n GetAiLimitPolicyInput,\n ListAiLimitPoliciesInput,\n ListAiLimitPolicyStatusesInput,\n MarkAiModelCallReservationUnknownInput,\n ReconcileAiModelCallInput,\n RecordAiModelCallLimitActualsInput,\n ReserveAiModelCallInput,\n ReserveAiModelCallResult,\n UpdateAiLimitPolicyInput,\n} from \"@sixb/core/storage\"\nimport { AiLimitStorageError, aiLimitCalendarMonth } from \"@sixb/core/storage\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n runImmediateTransaction,\n type SqliteStoreConnection,\n} from \"./transactions\"\n\nexport interface SqliteAiLimitStorageOptions {\n readonly path?: string\n readonly connection?: SqliteStoreConnection\n}\n\n/** SQLite-backed editable AI limits and atomic model-call reservations. */\nexport class SqliteAiLimitStorage implements AiLimitStorage {\n private readonly connection: SqliteStoreConnection\n\n constructor(options: SqliteAiLimitStorageOptions = {}) {\n this.connection = openSqliteStoreConnection(options)\n }\n\n async createPolicy(input: CreateAiLimitPolicyInput): Promise<AiLimitPolicy> {\n const policy = normalizeCreateAiLimitPolicy(input)\n return runImmediateTransaction(this.connection.db, () => {\n const subject = aiLimitSubjectParts(policy.subject)\n const limit = normalizeAiLimitAmount(policy.limit)\n try {\n this.connection.db\n .query(\n `\n INSERT INTO ai_usage_limits (\n project_id, id, subject_type, subject_id, meter, currency, limit_amount,\n period_kind, enabled, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n policy.projectId,\n policy.id,\n subject.type,\n subject.id,\n limit.meter,\n limit.currency,\n limit.amount.toString(),\n policy.period,\n policy.enabled ? 1 : 0,\n policy.createdAt.toISOString(),\n policy.updatedAt.toISOString()\n )\n } catch (error) {\n if (!isConstraintError(error)) throw error\n throw duplicatePolicy(policy)\n }\n return this.requirePolicy(policy.projectId, policy.id)\n })\n }\n\n async updatePolicy(input: UpdateAiLimitPolicyInput): Promise<AiLimitPolicy> {\n const update = normalizeUpdateAiLimitPolicy(input)\n return runImmediateTransaction(this.connection.db, () => {\n const existing = this.requirePolicy(update.projectId, update.id)\n if (update.limit !== undefined) assertSameDimension(existing.limit, update.limit)\n const limit = normalizeAiLimitAmount(update.limit ?? existing.limit)\n this.connection.db\n .query(\n `\n UPDATE ai_usage_limits\n SET limit_amount = ?, enabled = ?, updated_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n limit.amount.toString(),\n (update.enabled ?? existing.enabled) ? 1 : 0,\n update.updatedAt.toISOString(),\n update.projectId,\n update.id\n )\n return this.requirePolicy(update.projectId, update.id)\n })\n }\n\n async deletePolicy(input: DeleteAiLimitPolicyInput): Promise<boolean> {\n validatePolicyIdentity(input)\n return runImmediateTransaction(this.connection.db, () => {\n const result = this.connection.db\n .query(\"DELETE FROM ai_usage_limits WHERE project_id = ? AND id = ?\")\n .run(input.projectId, input.id)\n return result.changes > 0\n })\n }\n\n async getPolicy(input: GetAiLimitPolicyInput): Promise<AiLimitPolicy | null> {\n validatePolicyIdentity(input)\n const row = this.connection.db\n .query(\"SELECT * FROM ai_usage_limits WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as AiLimitPolicyRow | null\n return row ? policyFromRow(row) : null\n }\n\n async listPolicies(input: ListAiLimitPoliciesInput): Promise<readonly AiLimitPolicy[]> {\n assertNonBlank(input.projectId, \"projectId\")\n return this.policyRows(input.projectId, input.includeDisabled ?? false).map(policyFromRow)\n }\n\n async listPolicyStatuses(\n input: ListAiLimitPolicyStatusesInput\n ): Promise<readonly AiLimitPolicyStatus[]> {\n assertNonBlank(input.projectId, \"projectId\")\n const period = aiLimitCalendarMonth(input.at ?? new Date())\n const existingGroups =\n input.existingGroupIds === undefined ? undefined : new Set(input.existingGroupIds)\n return runImmediateTransaction(this.connection.db, () =>\n this.policyRows(input.projectId, input.includeDisabled ?? false).map((row) =>\n this.statusForPolicy(policyFromRow(row), period, existingGroups)\n )\n )\n }\n\n async reserveModelCall(input: ReserveAiModelCallInput): Promise<ReserveAiModelCallResult> {\n const request = normalizeReserveAiModelCall(input)\n return runImmediateTransaction(this.connection.db, () => {\n const existing = this.findReservation(request.identity)\n if (existing) {\n if (!aiLimitReservationRequestMatches(existing, request)) {\n throw new AiLimitStorageError(\n \"reservation_conflict\",\n `[SixbSqlite] AI model-call reservation '${input.callId}' was replayed with different subjects, estimates, or period.`\n )\n }\n if (existing.state !== \"active\") {\n return { status: \"terminal\", reservation: existing, created: false }\n }\n return { status: \"reserved\", reservation: existing, created: false }\n }\n this.assertExecutionExists(request.identity.projectId, request.identity.executionId)\n\n const subjectKeys = new Set(request.subjects.map(aiLimitSubjectKey))\n const estimates = new Map(\n request.estimates.map((quantity) => {\n const amount = normalizeAiLimitAmount(quantity)\n return [aiLimitAmountKey(amount), amount] as const\n })\n )\n const enabledPolicies = this.policyRows(request.identity.projectId, false).map(policyFromRow)\n const exhaustedPolicies: AiLimitPolicyStatus[] = []\n const unavailablePolicies: AiLimitPolicyStatus[] = []\n const unavailableReasons = new Set<\"missingEstimate\" | \"incompleteAccounting\">()\n for (const policy of enabledPolicies) {\n if (\n !subjectKeys.has(aiLimitSubjectKey(policy.subject)) ||\n !aiLimitMeterApplies(policy.limit.meter, request.modelKind)\n ) {\n continue\n }\n const limit = normalizeAiLimitAmount(policy.limit)\n const estimate = estimates.get(aiLimitAmountKey(limit))\n const status = this.statusForPolicy(policy, request.period)\n if (!estimate || status.accountingStatus === \"unavailable\") {\n unavailablePolicies.push(status)\n if (!estimate) unavailableReasons.add(\"missingEstimate\")\n if (status.accountingStatus === \"unavailable\") {\n unavailableReasons.add(\"incompleteAccounting\")\n }\n continue\n }\n const consumption = status.consumption\n const consumed =\n normalizeAiLimitAmount(consumption.actual).amount +\n normalizeAiLimitAmount(consumption.reserved).amount +\n normalizeAiLimitAmount(consumption.unknown).amount\n if (consumed + estimate.amount > limit.amount) exhaustedPolicies.push(status)\n }\n if (unavailablePolicies.length > 0) {\n unavailablePolicies.sort((left, right) => left.policy.id.localeCompare(right.policy.id))\n return {\n status: \"unavailable\",\n unavailablePolicies,\n reasons: [...unavailableReasons].sort(),\n }\n }\n if (exhaustedPolicies.length > 0) {\n exhaustedPolicies.sort((left, right) => left.policy.id.localeCompare(right.policy.id))\n return {\n status: \"denied\",\n exhaustedPolicies,\n resetAt: new Date(\n Math.min(...exhaustedPolicies.map((status) => status.period.resetAt.getTime()))\n ),\n }\n }\n\n const buckets = aiLimitReservationBuckets(\n enabledPolicies,\n request.subjects,\n request.estimates,\n request.modelKind\n )\n if (buckets.length === 0) return { status: \"notRequired\" }\n for (const bucket of buckets) {\n const amount = normalizeAiLimitAmount(bucket.estimate)\n this.changeCounters(\n request.identity.projectId,\n bucket.subject,\n amount,\n request.period,\n { reserved: amount.amount },\n request.reservedAt\n )\n }\n const reservation: AiModelCallReservation = {\n ...request.identity,\n buckets,\n requestKey: aiLimitReservationRequestKey(request),\n period: request.period,\n state: \"active\",\n reservedAt: request.reservedAt,\n updatedAt: new Date(request.reservedAt),\n }\n this.insertReservation(reservation)\n return { status: \"reserved\", reservation: structuredClone(reservation), created: true }\n })\n }\n\n async recordModelCallActuals(input: RecordAiModelCallLimitActualsInput): Promise<void> {\n assertNonBlank(input.projectId, \"projectId\")\n assertNonBlank(input.usageRecordId, \"usageRecordId\")\n const recordedAt = cloneValidDate(input.recordedAt ?? new Date(), \"recordedAt\")\n runImmediateTransaction(this.connection.db, () => {\n const entry = this.requireAccountingEntry(input.projectId, input.usageRecordId)\n const period = aiLimitCalendarMonth(entry.occurredAt)\n for (const subjectValue of aiLimitSubjectsFromAccountingEntry(entry)) {\n const subject = aiLimitSubjectParts(subjectValue)\n const rows = this.connection.db\n .query(\n `\n SELECT meter, currency, actual_amount, accounting_status\n FROM ai_usage_limit_periods\n WHERE project_id = ? AND subject_type = ? AND subject_id = ?\n AND period_start = ?\n `\n )\n .all(\n input.projectId,\n subject.type,\n subject.id,\n period.start.toISOString()\n ) as AiLimitActualStateRow[]\n for (const row of rows) {\n const actual = resolveAiLimitActual([entry], row)\n this.connection.db\n .query(\n `\n UPDATE ai_usage_limit_periods\n SET actual_amount = ?, accounting_status = ?, updated_at = ?\n WHERE project_id = ? AND subject_type = ? AND subject_id = ?\n AND meter = ? AND currency = ? AND period_start = ?\n `\n )\n .run(\n (BigInt(row.actual_amount) + actual.amount).toString(),\n row.accounting_status === \"unavailable\" || actual.accountingStatus === \"unavailable\"\n ? \"unavailable\"\n : \"complete\",\n recordedAt.toISOString(),\n input.projectId,\n subject.type,\n subject.id,\n row.meter,\n row.currency,\n period.start.toISOString()\n )\n }\n }\n })\n }\n\n async reconcileModelCall(input: ReconcileAiModelCallInput): Promise<AiModelCallReservation> {\n const identity = normalizeAiModelCallReservationIdentity(input)\n assertNonBlank(input.usageRecordId, \"usageRecordId\")\n const reconciledAt = cloneValidDate(input.reconciledAt ?? new Date(), \"reconciledAt\")\n return runImmediateTransaction(this.connection.db, () => {\n const reservation = this.findReservation(identity)\n if (!reservation) throw missingReservation(identity)\n if (reservation.state === \"reconciled\") {\n if (reservation.usageRecordId === input.usageRecordId) {\n return reservation\n }\n throw reconciliationConflict(identity.callId)\n }\n const accounting = this.requireAccountingEntry(identity.projectId, input.usageRecordId)\n assertAiLimitAccountingMatchesReservation(reservation, accounting)\n this.reconcileEstimateCounters(reservation, accounting, reconciledAt)\n const reconciled: AiModelCallReservation = {\n ...reservation,\n state: \"reconciled\",\n usageRecordId: input.usageRecordId,\n updatedAt: reconciledAt,\n }\n this.updateReservation(reconciled)\n return structuredClone(reconciled)\n })\n }\n\n async markReservationUnknown(\n input: MarkAiModelCallReservationUnknownInput\n ): Promise<AiModelCallReservation> {\n const identity = normalizeAiModelCallReservationIdentity(input)\n const markedAt = cloneValidDate(input.markedAt ?? new Date(), \"markedAt\")\n return runImmediateTransaction(this.connection.db, () => {\n const reservation = this.findReservation(identity)\n if (!reservation) throw missingReservation(identity)\n if (reservation.state === \"unknown\") return reservation\n if (reservation.state !== \"active\") throw invalidState(reservation, \"mark unknown\")\n this.moveEstimateCounters(reservation, { reserved: -1n, unknown: 1n }, markedAt)\n const unknown = { ...reservation, state: \"unknown\" as const, updatedAt: markedAt }\n this.updateReservation(unknown)\n return structuredClone(unknown)\n })\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n\n private policyRows(projectId: string, includeDisabled: boolean): AiLimitPolicyRow[] {\n return this.connection.db\n .query(\n `\n SELECT * FROM ai_usage_limits\n WHERE project_id = ? AND (? = 1 OR enabled = 1)\n ORDER BY id\n `\n )\n .all(projectId, includeDisabled ? 1 : 0) as AiLimitPolicyRow[]\n }\n\n private requirePolicy(projectId: string, id: string): AiLimitPolicy {\n const row = this.connection.db\n .query(\"SELECT * FROM ai_usage_limits WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as AiLimitPolicyRow | null\n if (row) return policyFromRow(row)\n throw new AiLimitStorageError(\n \"missing_policy\",\n `[SixbSqlite] AI limit policy '${id}' does not exist in project '${projectId}'.`\n )\n }\n\n private statusForPolicy(\n policy: AiLimitPolicy,\n period: AiLimitPeriod,\n existingGroups?: ReadonlySet<string>\n ): AiLimitPolicyStatus {\n const subject = aiLimitSubjectParts(policy.subject)\n const limit = normalizeAiLimitAmount(policy.limit)\n let row = this.connection.db\n .query(\n `\n SELECT actual_amount, reserved_amount, unknown_amount, accounting_status\n FROM ai_usage_limit_periods\n WHERE project_id = ? AND subject_type = ? AND subject_id = ?\n AND meter = ? AND currency = ? AND period_start = ?\n `\n )\n .get(\n policy.projectId,\n subject.type,\n subject.id,\n limit.meter,\n limit.currency,\n period.start.toISOString()\n ) as AiLimitPeriodStateRow | null\n // Re-read incomplete accounting inside the transaction; retain in-flight estimates.\n if (!row || row.accounting_status === \"unavailable\") {\n const actual = resolveAiLimitActual(this.accountingEntries(policy, period), limit)\n row = {\n actual_amount: actual.amount.toString(),\n reserved_amount: row?.reserved_amount ?? \"0\",\n unknown_amount: row?.unknown_amount ?? \"0\",\n accounting_status: actual.accountingStatus,\n }\n this.connection.db\n .query(\n `\n INSERT INTO ai_usage_limit_periods (\n project_id, subject_type, subject_id, meter, currency, period_start, period_end,\n actual_amount, reserved_amount, unknown_amount, accounting_status, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '0', '0', ?, ?)\n ON CONFLICT (project_id, subject_type, subject_id, meter, currency, period_start)\n DO UPDATE SET\n actual_amount = excluded.actual_amount,\n accounting_status = excluded.accounting_status,\n updated_at = excluded.updated_at\n `\n )\n .run(\n policy.projectId,\n subject.type,\n subject.id,\n limit.meter,\n limit.currency,\n period.start.toISOString(),\n period.end.toISOString(),\n row.actual_amount,\n row.accounting_status,\n new Date().toISOString()\n )\n }\n return policyStatus(policy, period, row, existingGroups)\n }\n\n private changeCounters(\n projectId: string,\n subjectValue: AiLimitSubject,\n amount: NormalizedAiLimitAmount,\n period: AiLimitPeriod,\n changes: { readonly reserved?: bigint; readonly unknown?: bigint },\n updatedAt: Date\n ): void {\n const subject = aiLimitSubjectParts(subjectValue)\n const row = this.connection.db\n .query(\n `\n SELECT actual_amount, reserved_amount, unknown_amount, accounting_status\n FROM ai_usage_limit_periods\n WHERE project_id = ? AND subject_type = ? AND subject_id = ?\n AND meter = ? AND currency = ? AND period_start = ?\n `\n )\n .get(\n projectId,\n subject.type,\n subject.id,\n amount.meter,\n amount.currency,\n period.start.toISOString()\n ) as AiLimitPeriodStateRow | null\n const reserved = BigInt(row?.reserved_amount ?? \"0\") + (changes.reserved ?? 0n)\n const unknown = BigInt(row?.unknown_amount ?? \"0\") + (changes.unknown ?? 0n)\n if (reserved < 0n || unknown < 0n) {\n throw new Error(\"[SixbSqlite] AI limit period counter became negative.\")\n }\n this.connection.db\n .query(\n `\n INSERT INTO ai_usage_limit_periods (\n project_id, subject_type, subject_id, meter, currency, period_start, period_end,\n actual_amount, reserved_amount, unknown_amount, accounting_status, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (project_id, subject_type, subject_id, meter, currency, period_start)\n DO UPDATE SET\n period_end = excluded.period_end,\n actual_amount = excluded.actual_amount,\n reserved_amount = excluded.reserved_amount,\n unknown_amount = excluded.unknown_amount,\n accounting_status = excluded.accounting_status,\n updated_at = excluded.updated_at\n `\n )\n .run(\n projectId,\n subject.type,\n subject.id,\n amount.meter,\n amount.currency,\n period.start.toISOString(),\n period.end.toISOString(),\n row?.actual_amount ?? \"0\",\n reserved.toString(),\n unknown.toString(),\n row?.accounting_status ?? \"complete\",\n updatedAt.toISOString()\n )\n }\n\n private moveEstimateCounters(\n reservation: AiModelCallReservation,\n directions: { readonly reserved?: bigint; readonly unknown?: bigint },\n updatedAt: Date\n ): void {\n for (const bucket of reservation.buckets) {\n const amount = normalizeAiLimitAmount(bucket.estimate)\n this.changeCounters(\n reservation.projectId,\n bucket.subject,\n amount,\n reservation.period,\n {\n ...(directions.reserved === undefined\n ? {}\n : { reserved: directions.reserved * amount.amount }),\n ...(directions.unknown === undefined\n ? {}\n : { unknown: directions.unknown * amount.amount }),\n },\n updatedAt\n )\n }\n }\n\n private reconcileEstimateCounters(\n reservation: AiModelCallReservation,\n entry: AiLimitAccountingEntry,\n updatedAt: Date\n ): void {\n for (const bucket of reservation.buckets) {\n const amount = normalizeAiLimitAmount(bucket.estimate)\n const actual = resolveAiLimitActual([entry], amount)\n if (actual.accountingStatus === \"complete\") {\n this.changeCounters(\n reservation.projectId,\n bucket.subject,\n amount,\n reservation.period,\n reservation.state === \"active\"\n ? { reserved: -amount.amount }\n : { unknown: -amount.amount },\n updatedAt\n )\n } else if (reservation.state === \"active\") {\n this.changeCounters(\n reservation.projectId,\n bucket.subject,\n amount,\n reservation.period,\n { reserved: -amount.amount, unknown: amount.amount },\n updatedAt\n )\n }\n }\n }\n\n private insertReservation(reservation: AiModelCallReservation): void {\n this.connection.db\n .query(\n `\n INSERT INTO ai_model_call_reservations (\n project_id, execution_id, attempt, call_id, buckets, request_key,\n period_start, period_end, state, usage_record_id, reserved_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(...reservationSqlValues(reservation))\n }\n\n private updateReservation(reservation: AiModelCallReservation): void {\n this.connection.db\n .query(\n `\n UPDATE ai_model_call_reservations\n SET state = ?, usage_record_id = ?, updated_at = ?\n WHERE project_id = ? AND execution_id = ? AND attempt = ? AND call_id = ?\n `\n )\n .run(\n reservation.state,\n reservation.usageRecordId ?? null,\n reservation.updatedAt.toISOString(),\n reservation.projectId,\n reservation.executionId,\n reservation.attempt,\n reservation.callId\n )\n }\n\n private findReservation(input: {\n readonly projectId: string\n readonly executionId: string\n readonly attempt: number\n readonly callId: string\n }): AiModelCallReservation | null {\n const row = this.connection.db\n .query(\n `\n SELECT * FROM ai_model_call_reservations\n WHERE project_id = ? AND execution_id = ? AND attempt = ? AND call_id = ?\n `\n )\n .get(\n input.projectId,\n input.executionId,\n input.attempt,\n input.callId\n ) as AiModelCallReservationRow | null\n return row ? reservationFromRow(row) : null\n }\n\n private accountingEntries(\n policy: AiLimitPolicy,\n period: AiLimitPeriod\n ): readonly AiLimitAccountingEntry[] {\n const subject = aiLimitSubjectParts(policy.subject)\n const rows = this.connection.db\n .query(\n `\n SELECT usage.project_id, usage.id AS usage_record_id, usage.execution_id,\n usage.attempt, usage.call_id, usage.occurred_at,\n CAST(usage.total_tokens AS TEXT) AS total_tokens,\n usage.model_kind,\n executions.requested_by_user_id,\n executions.requested_by_service_account_id,\n valuations.status AS valuation_status,\n valuations.currency AS valuation_currency,\n CAST(valuations.amount_nanos AS TEXT) AS valuation_amount_nanos\n FROM ai_model_call_usage AS usage\n JOIN executions\n ON executions.project_id = usage.project_id AND executions.id = usage.execution_id\n LEFT JOIN ai_model_call_valuations AS valuations\n ON valuations.project_id = usage.project_id\n AND valuations.usage_record_id = usage.id\n WHERE usage.project_id = ? AND usage.occurred_at >= ? AND usage.occurred_at < ?\n AND (\n ? = 'project'\n OR (\n ? = 'group'\n AND EXISTS (\n SELECT 1 FROM ai_model_call_usage_groups AS usage_groups\n WHERE usage_groups.project_id = usage.project_id\n AND usage_groups.usage_record_id = usage.id\n AND usage_groups.group_id = ?\n )\n )\n OR (? = 'user' AND executions.requested_by_user_id = ?)\n OR (\n ? = 'serviceAccount'\n AND executions.requested_by_service_account_id = ?\n )\n )\n ORDER BY usage.occurred_at, usage.id\n `\n )\n .all(\n policy.projectId,\n period.start.toISOString(),\n period.end.toISOString(),\n subject.type,\n subject.type,\n subject.id,\n subject.type,\n subject.id,\n subject.type,\n subject.id\n ) as AiLimitAccountingRow[]\n return rows.map((row) => accountingEntryFromRow(row, policy.subject))\n }\n\n private requireAccountingEntry(projectId: string, usageRecordId: string): AiLimitAccountingEntry {\n const row = this.connection.db\n .query(\n `\n SELECT usage.project_id, usage.id AS usage_record_id, usage.execution_id,\n usage.attempt, usage.call_id, usage.occurred_at,\n CAST(usage.total_tokens AS TEXT) AS total_tokens,\n usage.model_kind,\n executions.requested_by_user_id,\n executions.requested_by_service_account_id,\n valuations.status AS valuation_status,\n valuations.currency AS valuation_currency,\n CAST(valuations.amount_nanos AS TEXT) AS valuation_amount_nanos\n FROM ai_model_call_usage AS usage\n JOIN executions\n ON executions.project_id = usage.project_id AND executions.id = usage.execution_id\n LEFT JOIN ai_model_call_valuations AS valuations\n ON valuations.project_id = usage.project_id\n AND valuations.usage_record_id = usage.id\n WHERE usage.project_id = ? AND usage.id = ?\n `\n )\n .get(projectId, usageRecordId) as AiLimitAccountingRow | null\n if (row) {\n const groups = this.connection.db\n .query(\n `\n SELECT group_id FROM ai_model_call_usage_groups\n WHERE project_id = ? AND usage_record_id = ?\n ORDER BY group_id\n `\n )\n .all(projectId, usageRecordId) as { readonly group_id: string }[]\n return accountingEntryFromRow(\n row,\n undefined,\n groups.map((group) => group.group_id)\n )\n }\n throw new AiLimitStorageError(\n \"missing_usage_record\",\n `[SixbSqlite] AI usage record '${usageRecordId}' does not exist in project '${projectId}'.`\n )\n }\n\n private assertExecutionExists(projectId: string, executionId: string): void {\n const row = this.connection.db\n .query(\"SELECT 1 FROM executions WHERE project_id = ? AND id = ?\")\n .get(projectId, executionId)\n if (row) return\n throw new AiLimitStorageError(\n \"missing_execution\",\n `[SixbSqlite] AI limit execution '${executionId}' does not exist in project '${projectId}'.`\n )\n }\n}\n\ninterface AiLimitPolicyRow {\n readonly project_id: string\n readonly id: string\n readonly subject_type: AiLimitSubject[\"type\"]\n readonly subject_id: string\n readonly meter: AiLimitQuantity[\"meter\"]\n readonly currency: string\n readonly limit_amount: string\n readonly period_kind: \"calendarMonth\"\n readonly enabled: number\n readonly created_at: string\n readonly updated_at: string\n}\n\ninterface AiLimitPeriodStateRow {\n readonly actual_amount: string\n readonly reserved_amount: string\n readonly unknown_amount: string\n readonly accounting_status: \"complete\" | \"unavailable\"\n}\n\ninterface AiLimitActualStateRow {\n readonly meter: AiLimitQuantity[\"meter\"]\n readonly currency: string\n readonly actual_amount: string\n readonly accounting_status: \"complete\" | \"unavailable\"\n}\n\ninterface AiLimitAccountingRow {\n readonly project_id: string\n readonly usage_record_id: string\n readonly execution_id: string\n readonly attempt: number\n readonly call_id: string\n readonly occurred_at: string\n readonly total_tokens: string | null\n readonly model_kind: AiLimitAccountingEntry[\"modelKind\"] | null\n readonly requested_by_user_id: string | null\n readonly requested_by_service_account_id: string | null\n readonly valuation_status: \"rated\" | \"unpriceable\" | null\n readonly valuation_currency: string | null\n readonly valuation_amount_nanos: string | null\n}\n\ninterface AiModelCallReservationRow {\n readonly project_id: string\n readonly execution_id: string\n readonly attempt: number\n readonly call_id: string\n readonly buckets: string\n readonly request_key: string\n readonly period_start: string\n readonly period_end: string\n readonly state: AiModelCallReservation[\"state\"]\n readonly usage_record_id: string | null\n readonly reserved_at: string\n readonly updated_at: string\n}\n\nfunction policyFromRow(row: AiLimitPolicyRow): AiLimitPolicy {\n return {\n id: row.id,\n projectId: row.project_id,\n subject: aiLimitSubjectFromParts(row.subject_type, row.subject_id),\n limit: aiLimitQuantityFromAmount({\n meter: row.meter,\n currency: row.currency,\n amount: BigInt(row.limit_amount),\n }),\n period: row.period_kind,\n enabled: row.enabled === 1,\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n }\n}\n\nfunction policyStatus(\n policy: AiLimitPolicy,\n period: AiLimitPeriod,\n row: AiLimitPeriodStateRow,\n existingGroups?: ReadonlySet<string>\n): AiLimitPolicyStatus {\n const limit = normalizeAiLimitAmount(policy.limit)\n const actual = BigInt(row.actual_amount)\n const reserved = BigInt(row.reserved_amount)\n const unknown = BigInt(row.unknown_amount)\n const consumed = actual + reserved + unknown\n const quantity = (amount: bigint) => aiLimitQuantityFromAmount({ ...limit, amount })\n return {\n policy,\n period: structuredClone(period),\n consumption: {\n actual: quantity(actual),\n reserved: quantity(reserved),\n unknown: quantity(unknown),\n remaining: quantity(limit.amount > consumed ? limit.amount - consumed : 0n),\n },\n accountingStatus: row.accounting_status,\n exhausted: consumed >= limit.amount,\n orphaned:\n policy.subject.type === \"group\" &&\n existingGroups !== undefined &&\n !existingGroups.has(policy.subject.id),\n }\n}\n\nfunction accountingEntryFromRow(\n row: AiLimitAccountingRow,\n subject?: AiLimitSubject,\n requesterGroupIds = subject?.type === \"group\" ? [subject.id] : []\n): AiLimitAccountingEntry {\n const totalTokens = row.total_tokens === null ? undefined : Number(row.total_tokens)\n const requester = row.requested_by_user_id\n ? ({ type: \"user\", id: row.requested_by_user_id } as const)\n : row.requested_by_service_account_id\n ? ({ type: \"serviceAccount\", id: row.requested_by_service_account_id } as const)\n : undefined\n return {\n projectId: row.project_id,\n usageRecordId: row.usage_record_id,\n executionId: row.execution_id,\n attempt: row.attempt,\n callId: row.call_id,\n occurredAt: new Date(row.occurred_at),\n ...(row.model_kind === null ? {} : { modelKind: row.model_kind }),\n ...(totalTokens !== undefined && Number.isSafeInteger(totalTokens) ? { totalTokens } : {}),\n requesterGroupIds,\n ...(requester ? { requester } : {}),\n ...(row.valuation_status === \"rated\" &&\n row.valuation_currency !== null &&\n row.valuation_amount_nanos !== null\n ? {\n valuation: {\n status: \"rated\" as const,\n money: {\n currency: row.valuation_currency,\n amountNanos: row.valuation_amount_nanos,\n },\n },\n }\n : row.valuation_status === \"unpriceable\"\n ? { valuation: { status: \"unavailable\" as const } }\n : {}),\n }\n}\n\nfunction reservationFromRow(row: AiModelCallReservationRow): AiModelCallReservation {\n return {\n projectId: row.project_id,\n executionId: row.execution_id,\n attempt: row.attempt,\n callId: row.call_id,\n buckets: normalizeBucketsJson(row.buckets),\n requestKey: row.request_key,\n period: {\n kind: \"calendarMonth\",\n start: new Date(row.period_start),\n end: new Date(row.period_end),\n resetAt: new Date(row.period_end),\n },\n state: row.state,\n ...(row.usage_record_id === null ? {} : { usageRecordId: row.usage_record_id }),\n reservedAt: new Date(row.reserved_at),\n updatedAt: new Date(row.updated_at),\n }\n}\n\nfunction normalizeBucketsJson(value: string): readonly AiLimitReservationBucket[] {\n const buckets = JSON.parse(value) as readonly AiLimitReservationBucket[]\n return buckets.map((bucket) => ({\n subject: structuredClone(bucket.subject),\n estimate: normalizeAiLimitQuantities([bucket.estimate], \"stored bucket\")[0]!,\n }))\n}\n\nfunction reservationSqlValues(reservation: AiModelCallReservation): SQLQueryBindings[] {\n return [\n reservation.projectId,\n reservation.executionId,\n reservation.attempt,\n reservation.callId,\n JSON.stringify(reservation.buckets),\n reservation.requestKey,\n reservation.period.start.toISOString(),\n reservation.period.end.toISOString(),\n reservation.state,\n reservation.usageRecordId ?? null,\n reservation.reservedAt.toISOString(),\n reservation.updatedAt.toISOString(),\n ]\n}\n\nfunction assertSameDimension(previous: AiLimitQuantity, next: AiLimitQuantity): void {\n if (\n aiLimitAmountKey(normalizeAiLimitAmount(previous)) !==\n aiLimitAmountKey(normalizeAiLimitAmount(next))\n ) {\n throw new TypeError(\"[Sixb] AI limit policy meter and cost currency are immutable.\")\n }\n}\n\nfunction validatePolicyIdentity(input: GetAiLimitPolicyInput): void {\n assertNonBlank(input.projectId, \"projectId\")\n assertNonBlank(input.id, \"policy id\")\n}\n\nfunction duplicatePolicy(policy: AiLimitPolicy): AiLimitStorageError {\n return new AiLimitStorageError(\n \"duplicate_policy\",\n `[SixbSqlite] An AI limit policy already exists for policy ID or subject-meter dimension '${policy.id}'.`\n )\n}\n\nfunction missingReservation(input: {\n readonly executionId: string\n readonly attempt: number\n readonly callId: string\n}): AiLimitStorageError {\n return new AiLimitStorageError(\n \"missing_reservation\",\n `[SixbSqlite] AI model-call reservation '${input.callId}' does not exist for execution '${input.executionId}' attempt ${input.attempt}.`\n )\n}\n\nfunction reconciliationConflict(callId: string): AiLimitStorageError {\n return new AiLimitStorageError(\n \"reconciliation_conflict\",\n `[SixbSqlite] AI model-call reservation '${callId}' was reconciled with a different usage record.`\n )\n}\n\nfunction invalidState(reservation: AiModelCallReservation, operation: string): AiLimitStorageError {\n return new AiLimitStorageError(\n \"invalid_reservation_state\",\n `[SixbSqlite] Cannot ${operation} AI model-call reservation '${reservation.callId}' in state '${reservation.state}'.`\n )\n}\n\nfunction isConstraintError(error: unknown): boolean {\n return error instanceof Error && /constraint/i.test(error.message)\n}\n",
22
- "import type { Database, SQLQueryBindings } from \"bun:sqlite\"\nimport {\n artifactStorageErrors,\n parseArtifactFrameGrantRow,\n parseArtifactRow,\n parseArtifactVersionRow,\n} from \"@sixb/core/internal/storage\"\nimport type {\n ArtifactFrameGrantRecord,\n ArtifactRecord,\n ArtifactStorage,\n ArtifactVersionInput,\n ArtifactVersionRecord,\n CreateArtifactInput,\n DeleteArtifactInput,\n DeleteArtifactVersionsByOriginInput,\n DeleteExpiredArtifactFrameGrantsInput,\n FindArtifactFrameGrantInput,\n GetArtifactInput,\n GetArtifactVersionInput,\n ListArtifactsInput,\n ListArtifactsResult,\n ListArtifactVersionsInput,\n ListArtifactVersionsResult,\n ListReferencingVersionsInput,\n PublishArtifactVersionInput,\n PublishedArtifactVersion,\n} from \"@sixb/core/storage\"\nimport { runImmediateTransaction, type SqliteStoreConnection } from \"./transactions\"\n\nconst ARTIFACT_COLUMNS = `\n project_id AS projectId, id, kind, title,\n owner_principal_type AS ownerPrincipalType, owner_principal_id AS ownerPrincipalId,\n latest_version AS latestVersion, created_at AS createdAt, updated_at AS updatedAt\n`\n\nconst VERSION_COLUMNS = `\n project_id AS projectId, artifact_id AS artifactId, version, title, entry, files, outline, refs,\n author_principal_type AS authorPrincipalType, author_principal_id AS authorPrincipalId,\n origin_thread_id AS originThreadId, origin_run_id AS originRunId, created_at AS createdAt\n`\n\nconst FRAME_GRANT_COLUMNS = `\n project_id AS projectId, token_hash AS tokenHash, artifact_id AS artifactId, version, targets,\n created_at AS createdAt, expires_at AS expiresAt\n`\n\ntype Row = Record<string, unknown>\n\nexport class SqliteArtifactStorage implements ArtifactStorage {\n private readonly db: Database\n\n constructor(connection: SqliteStoreConnection) {\n this.db = connection.db\n }\n\n async create(input: CreateArtifactInput): Promise<PublishedArtifactVersion> {\n return runImmediateTransaction(this.db, () => {\n const createdAt = input.version.createdAt.toISOString()\n const artifact = this.db\n .query(\n `INSERT INTO artifacts (\n project_id, id, kind, title, owner_principal_type, owner_principal_id,\n latest_version, next_version, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, 1, 2, ?, ?)\n ON CONFLICT (project_id, id) DO NOTHING\n RETURNING ${ARTIFACT_COLUMNS}`\n )\n .get(\n input.projectId,\n input.id,\n input.kind,\n input.version.title,\n input.owner.type,\n input.owner.id,\n createdAt,\n createdAt\n ) as Row | null\n if (!artifact) throw artifactStorageErrors.exists(input.id)\n return {\n artifact: parseArtifactRow(artifact),\n version: this.insertVersion(input.projectId, input.id, 1, input.version),\n }\n })\n }\n\n async publish(input: PublishArtifactVersionInput): Promise<PublishedArtifactVersion> {\n return runImmediateTransaction(this.db, () => {\n const current = this.db\n .query(\n \"SELECT kind, next_version AS nextVersion FROM artifacts WHERE project_id = ? AND id = ?\"\n )\n .get(input.projectId, input.artifactId) as {\n readonly kind: ArtifactRecord[\"kind\"]\n readonly nextVersion: number\n } | null\n if (!current) throw artifactStorageErrors.notFound(input.artifactId)\n if (current.kind !== input.kind) {\n throw artifactStorageErrors.kindMismatch(input.artifactId, current.kind, input.kind)\n }\n const version = this.insertVersion(\n input.projectId,\n input.artifactId,\n current.nextVersion,\n input.version\n )\n const artifact = this.db\n .query(\n `UPDATE artifacts\n SET title = ?, latest_version = ?, next_version = ?, updated_at = ?\n WHERE project_id = ? AND id = ?\n RETURNING ${ARTIFACT_COLUMNS}`\n )\n .get(\n input.version.title,\n version.version,\n version.version + 1,\n input.version.createdAt.toISOString(),\n input.projectId,\n input.artifactId\n ) as Row\n return { artifact: parseArtifactRow(artifact), version }\n })\n }\n\n async get(input: GetArtifactInput): Promise<ArtifactRecord | null> {\n const row = this.db\n .query(`SELECT ${ARTIFACT_COLUMNS} FROM artifacts WHERE project_id = ? AND id = ?`)\n .get(input.projectId, input.id) as Row | null\n return row ? parseArtifactRow(row) : null\n }\n\n async list(input: ListArtifactsInput): Promise<ListArtifactsResult> {\n const where = [\"a.project_id = ?\"]\n const params: SQLQueryBindings[] = [input.projectId]\n if (input.owner) {\n where.push(\"a.owner_principal_type = ? AND a.owner_principal_id = ?\")\n params.push(input.owner.type, input.owner.id)\n }\n if (input.originThreadId !== undefined) {\n where.push(\n `EXISTS (\n SELECT 1 FROM artifact_versions v\n WHERE v.project_id = a.project_id AND v.artifact_id = a.id AND v.origin_thread_id = ?\n )`\n )\n params.push(input.originThreadId)\n }\n if (input.kind !== undefined) {\n where.push(\"a.kind = ?\")\n params.push(input.kind)\n }\n const clause = where.join(\" AND \")\n const { total } = this.db\n .query(`SELECT COUNT(*) AS total FROM artifacts a WHERE ${clause}`)\n .get(...params) as { readonly total: number }\n const offset = input.offset ?? 0\n const rows = this.db\n .query(\n `SELECT ${ARTIFACT_COLUMNS} FROM artifacts a WHERE ${clause}\n ORDER BY a.updated_at DESC, a.id ASC LIMIT ? OFFSET ?`\n )\n .all(...params, input.limit ?? -1, offset) as Row[]\n return {\n artifacts: rows.map(parseArtifactRow),\n hasMore: offset + rows.length < total,\n total,\n }\n }\n\n async getVersion(input: GetArtifactVersionInput): Promise<ArtifactVersionRecord | null> {\n const row = this.db\n .query(\n `SELECT ${VERSION_COLUMNS} FROM artifact_versions\n WHERE project_id = ? AND artifact_id = ? AND version = ?`\n )\n .get(input.projectId, input.artifactId, input.version) as Row | null\n return row ? parseArtifactVersionRow(row) : null\n }\n\n async listVersions(input: ListArtifactVersionsInput): Promise<ListArtifactVersionsResult> {\n const { total } = this.db\n .query(\n \"SELECT COUNT(*) AS total FROM artifact_versions WHERE project_id = ? AND artifact_id = ?\"\n )\n .get(input.projectId, input.artifactId) as { readonly total: number }\n const offset = input.offset ?? 0\n const rows = this.db\n .query(\n `SELECT ${VERSION_COLUMNS} FROM artifact_versions\n WHERE project_id = ? AND artifact_id = ?\n ORDER BY version DESC LIMIT ? OFFSET ?`\n )\n .all(input.projectId, input.artifactId, input.limit ?? -1, offset) as Row[]\n return {\n versions: rows.map(parseArtifactVersionRow),\n hasMore: offset + rows.length < total,\n total,\n }\n }\n\n async listReferencingVersions(\n input: ListReferencingVersionsInput\n ): Promise<ArtifactVersionRecord[]> {\n // An address names the artifact when the id is followed by nothing, a version, a file, or a\n // part.\n const prefix = `artifact:${input.artifactId}`\n const rows = this.db\n .query(\n `SELECT ${VERSION_COLUMNS} FROM artifact_versions v\n WHERE (project_id, artifact_id, version) IN (\n SELECT project_id, id, latest_version FROM artifacts WHERE project_id = ?\n ) AND EXISTS (\n SELECT 1 FROM json_each(v.refs) r\n WHERE substr(json_extract(r.value, '$.address'), 1, ?) = ?\n AND substr(json_extract(r.value, '$.address'), ? + 1, 1) IN ('', '@', '/', '#')\n )\n ORDER BY artifact_id`\n )\n .all(input.projectId, prefix.length, prefix, prefix.length) as Row[]\n return rows.map(parseArtifactVersionRow)\n }\n\n async createFrameGrant(record: ArtifactFrameGrantRecord): Promise<void> {\n runImmediateTransaction(this.db, () => {\n const exists = this.db\n .query(\"SELECT 1 FROM artifacts WHERE project_id = ? AND id = ?\")\n .get(record.projectId, record.artifactId)\n if (!exists) throw artifactStorageErrors.notFound(record.artifactId)\n this.db\n .query(\n `INSERT INTO artifact_frame_grants\n (project_id, token_hash, artifact_id, version, targets, created_at, expires_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`\n )\n .run(\n record.projectId,\n record.tokenHash,\n record.artifactId,\n record.version,\n JSON.stringify(record.targets),\n record.createdAt.toISOString(),\n record.expiresAt.toISOString()\n )\n })\n }\n\n async findFrameGrant(\n input: FindArtifactFrameGrantInput\n ): Promise<ArtifactFrameGrantRecord | null> {\n const row = this.db\n .query(\n `SELECT ${FRAME_GRANT_COLUMNS} FROM artifact_frame_grants\n WHERE project_id = ? AND token_hash = ?`\n )\n .get(input.projectId, input.tokenHash) as Row | null\n return row ? parseArtifactFrameGrantRow(row) : null\n }\n\n async deleteExpiredFrameGrants(input: DeleteExpiredArtifactFrameGrantsInput): Promise<number> {\n return this.db\n .query(\n `DELETE FROM artifact_frame_grants WHERE rowid IN (\n SELECT rowid FROM artifact_frame_grants\n WHERE project_id = ? AND expires_at < ?\n ORDER BY expires_at LIMIT ?\n )`\n )\n .run(input.projectId, input.expiredBefore.toISOString(), input.limit).changes\n }\n\n async delete(input: DeleteArtifactInput): Promise<boolean> {\n // Versions and frame grants go with the artifact through ON DELETE CASCADE.\n return (\n this.db\n .query(\"DELETE FROM artifacts WHERE project_id = ? AND id = ?\")\n .run(input.projectId, input.id).changes > 0\n )\n }\n\n async deleteVersionsByOrigin(input: DeleteArtifactVersionsByOriginInput): Promise<number> {\n return runImmediateTransaction(this.db, () => {\n const affected = this.db\n .query(\n `SELECT DISTINCT artifact_id AS artifactId FROM artifact_versions\n WHERE project_id = ? AND origin_run_id = ?`\n )\n .all(input.projectId, input.runId) as { readonly artifactId: string }[]\n const deleted = this.db\n .query(\"DELETE FROM artifact_versions WHERE project_id = ? AND origin_run_id = ?\")\n .run(input.projectId, input.runId).changes\n for (const { artifactId } of affected) {\n this.repointLatest(input.projectId, artifactId)\n }\n return deleted\n })\n }\n\n /** Point an artifact at its newest remaining version, or delete it when none remains. */\n private repointLatest(projectId: string, artifactId: string): void {\n const latest = this.db\n .query(\n `SELECT version, title, created_at AS createdAt FROM artifact_versions\n WHERE project_id = ? AND artifact_id = ? ORDER BY version DESC LIMIT 1`\n )\n .get(projectId, artifactId) as {\n readonly version: number\n readonly title: string\n readonly createdAt: string\n } | null\n if (!latest) {\n this.db\n .query(\"DELETE FROM artifacts WHERE project_id = ? AND id = ?\")\n .run(projectId, artifactId)\n return\n }\n this.db\n .query(\n `UPDATE artifacts SET title = ?, latest_version = ?, updated_at = ?\n WHERE project_id = ? AND id = ?`\n )\n .run(latest.title, latest.version, latest.createdAt, projectId, artifactId)\n }\n\n private insertVersion(\n projectId: string,\n artifactId: string,\n version: number,\n input: ArtifactVersionInput\n ): ArtifactVersionRecord {\n const row = this.db\n .query(\n `INSERT INTO artifact_versions (\n project_id, artifact_id, version, title, entry, files, outline, refs,\n author_principal_type, author_principal_id, origin_thread_id, origin_run_id, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n RETURNING ${VERSION_COLUMNS}`\n )\n .get(\n projectId,\n artifactId,\n version,\n input.title,\n input.entry,\n JSON.stringify(input.files),\n JSON.stringify(input.outline),\n JSON.stringify(input.references),\n input.author.type,\n input.author.id,\n input.origin?.threadId ?? null,\n input.origin?.runId ?? null,\n input.createdAt.toISOString()\n ) as Row\n return parseArtifactVersionRow(row)\n }\n}\n",
23
- "import type { Database } from \"bun:sqlite\"\nimport type {\n AuthStorage,\n CompleteDeviceAuthorizationInput,\n CompleteDeviceAuthorizationResult,\n CompleteMagicLinkSignInInput,\n CompleteOidcSignInInput,\n CompleteSignInResult,\n DeviceAuthorizationRecord,\n GroupMembershipRecord,\n GroupMembershipSource,\n InvitationRecord,\n SessionRecord,\n SuspendUserAndRevokeSessionsInput,\n UserIdentityRecord,\n UserRecord,\n} from \"@sixb/core/storage\"\nimport { AuthStorageError } from \"@sixb/core/storage\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n runImmediateTransaction,\n type SqliteStoreConnection,\n} from \"../transactions\"\nimport { SqliteAuthAccessTokenStore } from \"./access-tokens\"\nimport {\n getDeviceAuthorizationById,\n SqliteAuthDeviceAuthorizationStore,\n} from \"./device-authorizations\"\nimport { SqliteAuthGroupMembershipStore } from \"./group-memberships\"\nimport { SqliteAuthUserIdentityStore } from \"./identities\"\nimport { SqliteAuthInvitationStore } from \"./invitations\"\nimport { SqliteAuthMagicLinkStore } from \"./magic-links\"\nimport { SqliteAuthOidcAuthorizationAttemptStore } from \"./oidc-attempts\"\nimport type { SqliteAuthMagicLinkRow, SqliteAuthOidcAttemptRow } from \"./rows\"\nimport { rowToIdentityRecord, rowToUserRecord, serializeOptionalRecord } from \"./rows\"\nimport { SqliteAuthServiceAccountGroupMembershipStore } from \"./service-account-group-memberships\"\nimport { SqliteAuthServiceAccountStore } from \"./service-accounts\"\nimport { SqliteAuthSessionStore } from \"./sessions\"\nimport {\n assertNonEmpty,\n consumeMagicLink,\n consumeOidcAttempt,\n createSession,\n getActiveInvitationByEmail,\n getIdentityRowBySubject,\n getMagicLinkRowById,\n getOidcAttemptRowById,\n getUserRowByEmail,\n getUserRowById,\n mapUniqueConstraintError,\n normalizeEmail,\n normalizeGroupIds,\n revokeActiveSessionsForUser,\n toIso,\n upsertGroupMembership,\n validateCompleteSessionInput,\n} from \"./shared\"\nimport { SqliteAuthUserStore } from \"./users\"\n\ninterface AuthTransactionError {\n readonly error: AuthStorageError\n}\n\nexport interface SqliteAuthStorageOptions {\n /** Path to SQLite database file. Defaults to ':memory:' for in-memory database. */\n path?: string\n /** Internal shared connection used by bundled SqliteStorage. */\n connection?: SqliteStoreConnection\n}\n\nexport class SqliteAuthStorage implements AuthStorage {\n private readonly connection: SqliteStoreConnection\n private readonly db: Database\n\n readonly users: SqliteAuthUserStore\n readonly identities: SqliteAuthUserIdentityStore\n readonly serviceAccounts: SqliteAuthServiceAccountStore\n readonly serviceAccountGroupMemberships: SqliteAuthServiceAccountGroupMembershipStore\n readonly sessions: SqliteAuthSessionStore\n readonly accessTokens: SqliteAuthAccessTokenStore\n readonly invitations: SqliteAuthInvitationStore\n readonly groupMemberships: SqliteAuthGroupMembershipStore\n readonly magicLinks: SqliteAuthMagicLinkStore\n readonly oidcAuthorizationAttempts: SqliteAuthOidcAuthorizationAttemptStore\n readonly deviceAuthorizations: SqliteAuthDeviceAuthorizationStore\n\n constructor(options: SqliteAuthStorageOptions = {}) {\n this.connection = openSqliteStoreConnection(options)\n this.db = this.connection.db\n\n this.users = new SqliteAuthUserStore(this.db)\n this.identities = new SqliteAuthUserIdentityStore(this.db)\n this.serviceAccounts = new SqliteAuthServiceAccountStore(this.db)\n this.serviceAccountGroupMemberships = new SqliteAuthServiceAccountGroupMembershipStore(this.db)\n this.sessions = new SqliteAuthSessionStore(this.db)\n this.accessTokens = new SqliteAuthAccessTokenStore(this.db)\n this.invitations = new SqliteAuthInvitationStore(this.db)\n this.groupMemberships = new SqliteAuthGroupMembershipStore(this.db)\n this.magicLinks = new SqliteAuthMagicLinkStore(this.db)\n this.oidcAuthorizationAttempts = new SqliteAuthOidcAuthorizationAttemptStore(this.db)\n this.deviceAuthorizations = new SqliteAuthDeviceAuthorizationStore(this.db)\n }\n\n async completeDeviceAuthorization(\n input: CompleteDeviceAuthorizationInput\n ): Promise<CompleteDeviceAuthorizationResult> {\n return runImmediateTransaction(this.db, () => {\n const authorization = getDeviceAuthorizationById(this.db, input.projectId, input.id)\n if (!authorization) {\n throw new AuthStorageError(\n \"missing_device_authorization\",\n `[Sixb] Device authorization '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n assertCompletableDeviceAuthorization(authorization, input)\n const session = createSession(this.db, input.session)\n this.db\n .query(`\n UPDATE auth_device_authorizations\n SET status = 'consumed', consumed_at = ?\n WHERE project_id = ? AND id = ? AND status = 'approved'\n `)\n .run(toIso(input.completedAt), input.projectId, input.id)\n return {\n authorization: {\n ...authorization,\n status: \"consumed\",\n consumedAt: new Date(input.completedAt),\n },\n session,\n }\n })\n }\n\n async completeMagicLinkSignIn(\n input: CompleteMagicLinkSignInInput\n ): Promise<CompleteSignInResult> {\n const result = runImmediateTransaction(\n this.db,\n (): CompleteSignInResult | AuthTransactionError => {\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const completedAt = new Date(input.completedAt)\n const magicLink = getMagicLinkRowById(this.db, {\n projectId,\n id: input.magicLinkId,\n })\n\n this.assertMagicLinkUsable(\n projectId,\n input.magicLinkId,\n input.tokenHash,\n completedAt,\n magicLink\n )\n\n const existingUserRow = getUserRowByEmail(this.db, {\n projectId,\n email: magicLink.email,\n })\n const activeInvitation = getActiveInvitationByEmail(this.db, {\n projectId,\n email: magicLink.email,\n now: completedAt,\n })\n const shouldCreateUser = !existingUserRow\n const manualGroupIds = normalizeGroupIds(input.manualGroupIds)\n\n if (existingUserRow?.status === \"suspended\") {\n consumeMagicLink(this.db, {\n projectId,\n id: input.magicLinkId,\n tokenHash: input.tokenHash,\n consumedAt: completedAt,\n })\n return {\n error: new AuthStorageError(\n \"suspended_user\",\n `[Sixb] User '${existingUserRow.id}' is suspended for project '${projectId}'.`\n ),\n }\n }\n\n if (shouldCreateUser && !activeInvitation && !input.allowUserCreationWithoutInvitation) {\n consumeMagicLink(this.db, {\n projectId,\n id: input.magicLinkId,\n tokenHash: input.tokenHash,\n consumedAt: completedAt,\n })\n return {\n error: new AuthStorageError(\n \"user_creation_not_allowed\",\n `[Sixb] Magic link '${input.magicLinkId}' cannot create a user for project '${projectId}'.`\n ),\n }\n }\n\n validateCompleteSessionInput(this.db, projectId, input.session)\n\n let newUserId: string | undefined\n if (shouldCreateUser) {\n newUserId = assertNonEmpty(input.newUserId, \"User id\")\n if (getUserRowById(this.db, { projectId, id: newUserId })) {\n throw new AuthStorageError(\n \"duplicate_user\",\n `[Sixb] User '${newUserId}' already exists for project '${projectId}'.`\n )\n }\n }\n\n consumeMagicLink(this.db, {\n projectId,\n id: input.magicLinkId,\n tokenHash: input.tokenHash,\n consumedAt: completedAt,\n })\n\n const user = existingUserRow\n ? rowToUserRecord(existingUserRow)\n : this.insertUser({\n id: newUserId ?? assertNonEmpty(input.newUserId, \"User id\"),\n projectId,\n email: magicLink.email,\n displayName: input.newUserDisplayName,\n avatarUrl: input.newUserAvatarUrl,\n createdAt: completedAt,\n })\n\n const invitation = this.acceptInvitationAndApplyGroups({\n activeInvitation,\n completedAt,\n projectId,\n user,\n })\n const groupMemberships = this.applyGroups({\n completedAt,\n source: \"manual\",\n existing: invitation.groupMemberships,\n groupIds: manualGroupIds,\n projectId,\n userId: user.id,\n })\n const session = this.createSignInSession({\n projectId,\n strategyId: magicLink.strategy_id,\n session: input.session,\n userId: user.id,\n })\n\n return {\n user,\n session,\n invitation: invitation.invitation,\n groupMemberships,\n }\n }\n )\n\n if (\"error\" in result) {\n throw result.error\n }\n\n return result\n }\n\n async completeOidcSignIn(input: CompleteOidcSignInInput): Promise<CompleteSignInResult> {\n const result = runImmediateTransaction(\n this.db,\n (): CompleteSignInResult | AuthTransactionError => {\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const completedAt = new Date(input.completedAt)\n const attempt = getOidcAttemptRowById(this.db, {\n projectId,\n id: input.oidcAuthorizationAttemptId,\n })\n\n this.assertOidcAttemptUsable(\n projectId,\n input.oidcAuthorizationAttemptId,\n input.stateHash,\n completedAt,\n attempt\n )\n\n const subject = assertNonEmpty(input.subject, \"Subject\")\n const email = normalizeEmail(input.email)\n const identity = getIdentityRowBySubject(this.db, {\n projectId,\n strategyId: attempt.strategy_id,\n subject,\n })\n const activeInvitation = identity\n ? null\n : getActiveInvitationByEmail(this.db, {\n projectId,\n email,\n now: completedAt,\n })\n let userRow = identity\n ? getUserRowById(this.db, { projectId, id: identity.user_id })\n : getUserRowByEmail(this.db, { projectId, email })\n const shouldCreateUser = !identity && !userRow\n const manualGroupIds = normalizeGroupIds(input.manualGroupIds)\n\n if (identity && !userRow) {\n this.consumeOidcAttempt(input, completedAt, projectId)\n return {\n error: new AuthStorageError(\n \"missing_user\",\n `[Sixb] User '${identity.user_id}' not found for linked OIDC identity.`\n ),\n }\n }\n\n if (userRow?.status === \"suspended\") {\n this.consumeOidcAttempt(input, completedAt, projectId)\n return {\n error: new AuthStorageError(\n \"suspended_user\",\n `[Sixb] User '${userRow.id}' is suspended for project '${projectId}'.`\n ),\n }\n }\n\n if (shouldCreateUser && !activeInvitation && !input.allowUserCreationWithoutInvitation) {\n this.consumeOidcAttempt(input, completedAt, projectId)\n return {\n error: new AuthStorageError(\n \"user_creation_not_allowed\",\n `[Sixb] OIDC authorization attempt '${input.oidcAuthorizationAttemptId}' cannot create a user for project '${projectId}'.`\n ),\n }\n }\n\n validateCompleteSessionInput(this.db, projectId, input.session)\n\n let newUserId: string | undefined\n if (shouldCreateUser) {\n newUserId = assertNonEmpty(input.newUserId, \"User id\")\n if (getUserRowById(this.db, { projectId, id: newUserId })) {\n throw new AuthStorageError(\n \"duplicate_user\",\n `[Sixb] User '${newUserId}' already exists for project '${projectId}'.`\n )\n }\n }\n\n this.consumeOidcAttempt(input, completedAt, projectId)\n\n if (!userRow) {\n const user = this.insertUser({\n id: newUserId ?? assertNonEmpty(input.newUserId, \"User id\"),\n projectId,\n email,\n displayName: input.displayName,\n avatarUrl: input.avatarUrl,\n createdAt: completedAt,\n })\n userRow = {\n project_id: user.projectId,\n id: user.id,\n email: user.email,\n display_name: user.displayName ?? null,\n avatar_url: user.avatarUrl ?? null,\n status: user.status,\n created_at: toIso(user.createdAt),\n updated_at: toIso(user.updatedAt),\n }\n }\n\n const user = rowToUserRecord(userRow)\n const invitation = this.acceptInvitationAndApplyGroups({\n activeInvitation,\n completedAt,\n projectId,\n user,\n })\n const groupMemberships = this.syncDirectoryGroups({\n completedAt,\n existing: this.applyGroups({\n completedAt,\n source: \"manual\",\n existing: invitation.groupMemberships,\n groupIds: manualGroupIds,\n projectId,\n userId: user.id,\n }),\n groupIds: input.directoryGroupIds,\n projectId,\n userId: user.id,\n })\n const nextIdentity = this.upsertIdentity({\n projectId,\n strategyId: attempt.strategy_id,\n subject,\n userId: user.id,\n claims: input.claims,\n createdAt: identity ? new Date(identity.created_at) : completedAt,\n updatedAt: completedAt,\n })\n const session = this.createSignInSession({\n projectId,\n strategyId: attempt.strategy_id,\n session: input.session,\n userId: user.id,\n })\n\n return {\n user,\n session,\n identity: nextIdentity,\n invitation: invitation.invitation,\n groupMemberships,\n }\n }\n )\n\n if (\"error\" in result) {\n throw result.error\n }\n\n return result\n }\n\n async suspendUserAndRevokeSessions(\n input: SuspendUserAndRevokeSessionsInput\n ): Promise<UserRecord> {\n return runImmediateTransaction(this.db, () => {\n const existing = getUserRowById(this.db, {\n projectId: input.projectId,\n id: input.userId,\n })\n\n if (!existing) {\n throw new AuthStorageError(\n \"missing_user\",\n `[Sixb] User '${input.userId}' not found for project '${input.projectId}'.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE auth_users\n SET status = 'suspended',\n updated_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(toIso(input.suspendedAt), input.projectId, input.userId)\n revokeActiveSessionsForUser(this.db, {\n projectId: input.projectId,\n userId: input.userId,\n revokedAt: input.suspendedAt,\n })\n\n return rowToUserRecord({\n ...existing,\n status: \"suspended\",\n updated_at: toIso(input.suspendedAt),\n })\n })\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n\n private assertMagicLinkUsable(\n projectId: string,\n id: string,\n tokenHash: string,\n completedAt: Date,\n row: SqliteAuthMagicLinkRow | null\n ): asserts row is SqliteAuthMagicLinkRow {\n if (!row) {\n throw new AuthStorageError(\n \"missing_magic_link\",\n `[Sixb] Magic link '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (row.token_hash !== tokenHash || row.consumed_at || row.revoked_at) {\n throw new AuthStorageError(\n \"invalid_magic_link\",\n `[Sixb] Magic link '${id}' is not valid for project '${projectId}'.`\n )\n }\n\n if (new Date(row.expires_at) <= completedAt) {\n throw new AuthStorageError(\n \"expired_magic_link\",\n `[Sixb] Magic link '${id}' is expired for project '${projectId}'.`\n )\n }\n }\n\n private assertOidcAttemptUsable(\n projectId: string,\n id: string,\n stateHash: string,\n completedAt: Date,\n row: SqliteAuthOidcAttemptRow | null\n ): asserts row is SqliteAuthOidcAttemptRow {\n if (!row) {\n throw new AuthStorageError(\n \"missing_oidc_attempt\",\n `[Sixb] OIDC authorization attempt '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (row.state_hash !== stateHash || row.consumed_at) {\n throw new AuthStorageError(\n \"invalid_oidc_attempt\",\n `[Sixb] OIDC authorization attempt '${id}' is not valid for project '${projectId}'.`\n )\n }\n\n if (new Date(row.expires_at) <= completedAt) {\n throw new AuthStorageError(\n \"expired_oidc_attempt\",\n `[Sixb] OIDC authorization attempt '${id}' is expired for project '${projectId}'.`\n )\n }\n }\n\n private insertUser(input: {\n readonly id: string\n readonly projectId: string\n readonly email: string\n readonly displayName?: string\n readonly avatarUrl?: string\n readonly createdAt: Date\n }): UserRecord {\n try {\n this.db\n .query(\n `\n INSERT INTO auth_users (\n project_id,\n id,\n email,\n display_name,\n avatar_url,\n status,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?, 'active', ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.email,\n input.displayName ?? null,\n input.avatarUrl ?? null,\n toIso(input.createdAt),\n toIso(input.createdAt)\n )\n } catch (error) {\n mapUniqueConstraintError(\n error,\n \"duplicate_user\",\n `[Sixb] User '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n return {\n id: input.id,\n projectId: input.projectId,\n email: input.email,\n displayName: input.displayName,\n avatarUrl: input.avatarUrl,\n status: \"active\",\n createdAt: new Date(input.createdAt),\n updatedAt: new Date(input.createdAt),\n }\n }\n\n private acceptInvitationAndApplyGroups(input: {\n readonly activeInvitation: InvitationRecord | null\n readonly completedAt: Date\n readonly projectId: string\n readonly user: UserRecord\n }): {\n readonly invitation?: InvitationRecord\n readonly groupMemberships: readonly GroupMembershipRecord[]\n } {\n if (!input.activeInvitation) {\n return { groupMemberships: [] }\n }\n\n this.db\n .query(\n `\n UPDATE auth_invitations\n SET status = 'accepted',\n accepted_at = ?,\n updated_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(\n toIso(input.completedAt),\n toIso(input.completedAt),\n input.projectId,\n input.activeInvitation.id\n )\n\n const invitation: InvitationRecord = {\n ...input.activeInvitation,\n status: \"accepted\",\n acceptedAt: new Date(input.completedAt),\n updatedAt: new Date(input.completedAt),\n }\n const groupMemberships = input.activeInvitation.groupIds.map((groupId) =>\n upsertGroupMembership(this.db, {\n projectId: input.projectId,\n userId: input.user.id,\n groupId,\n source: \"invitation\",\n createdAt: input.completedAt,\n })\n )\n\n return { invitation, groupMemberships }\n }\n\n private applyGroups(input: {\n readonly completedAt: Date\n readonly existing: readonly GroupMembershipRecord[]\n readonly groupIds: readonly string[]\n readonly projectId: string\n readonly source: GroupMembershipSource\n readonly userId: string\n }): readonly GroupMembershipRecord[] {\n const groupMemberships = [...input.existing]\n\n for (const groupId of input.groupIds) {\n groupMemberships.push(\n upsertGroupMembership(this.db, {\n projectId: input.projectId,\n userId: input.userId,\n groupId,\n source: input.source,\n createdAt: input.completedAt,\n })\n )\n }\n\n return groupMemberships\n }\n // Directory memberships become exactly `groupIds`. A group the user already holds from another\n // source keeps that source, and memberships from other sources are never removed.\n private syncDirectoryGroups(input: {\n readonly completedAt: Date\n readonly existing: readonly GroupMembershipRecord[]\n readonly groupIds?: readonly string[]\n readonly projectId: string\n readonly userId: string\n }): readonly GroupMembershipRecord[] {\n if (!input.groupIds) {\n return input.existing\n }\n\n const groupIds = normalizeGroupIds(input.groupIds)\n this.db\n .query(\n `\n DELETE FROM auth_group_memberships\n WHERE project_id = ?\n AND user_id = ?\n AND source = 'directory'\n AND group_id NOT IN (${groupIds.map(() => \"?\").join(\", \")})\n `\n )\n .run(input.projectId, input.userId, ...groupIds)\n\n return this.applyGroups({ ...input, groupIds, source: \"directory\" })\n }\n\n private createSignInSession(input: {\n readonly projectId: string\n readonly strategyId: string\n readonly session: CompleteMagicLinkSignInInput[\"session\"]\n readonly userId: string\n }): SessionRecord {\n return createSession(this.db, {\n id: input.session.id,\n projectId: input.projectId,\n userId: input.userId,\n strategyId: input.strategyId,\n tokenHash: input.session.tokenHash,\n createdAt: input.session.createdAt,\n expiresAt: input.session.expiresAt,\n absoluteExpiresAt: input.session.absoluteExpiresAt,\n userAgent: input.session.userAgent,\n ipAddress: input.session.ipAddress,\n })\n }\n\n private consumeOidcAttempt(\n input: CompleteOidcSignInInput,\n completedAt: Date,\n projectId: string\n ): void {\n consumeOidcAttempt(this.db, {\n projectId,\n id: input.oidcAuthorizationAttemptId,\n stateHash: input.stateHash,\n consumedAt: completedAt,\n })\n }\n\n private upsertIdentity(input: {\n readonly projectId: string\n readonly strategyId: string\n readonly subject: string\n readonly userId: string\n readonly claims?: Readonly<Record<string, unknown>>\n readonly createdAt: Date\n readonly updatedAt: Date\n }): UserIdentityRecord {\n this.db\n .query(\n `\n INSERT INTO auth_user_identities (\n project_id,\n strategy_id,\n subject,\n user_id,\n claims,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(project_id, strategy_id, subject)\n DO UPDATE SET\n user_id = excluded.user_id,\n claims = excluded.claims,\n updated_at = excluded.updated_at\n `\n )\n .run(\n input.projectId,\n input.strategyId,\n input.subject,\n input.userId,\n serializeOptionalRecord(input.claims),\n toIso(input.createdAt),\n toIso(input.updatedAt)\n )\n\n return rowToIdentityRecord({\n project_id: input.projectId,\n strategy_id: input.strategyId,\n subject: input.subject,\n user_id: input.userId,\n claims: serializeOptionalRecord(input.claims),\n created_at: toIso(input.createdAt),\n updated_at: toIso(input.updatedAt),\n })\n }\n}\n\nfunction assertCompletableDeviceAuthorization(\n authorization: DeviceAuthorizationRecord,\n input: CompleteDeviceAuthorizationInput\n): void {\n if (authorization.deviceCodeHash !== input.deviceCodeHash) {\n throw new AuthStorageError(\n \"invalid_device_authorization\",\n \"[Sixb] Invalid device authorization.\"\n )\n }\n if (authorization.status === \"pending\") {\n throw new AuthStorageError(\n \"pending_device_authorization\",\n \"[Sixb] Device authorization is pending.\"\n )\n }\n if (authorization.status === \"denied\") {\n throw new AuthStorageError(\n \"device_authorization_denied\",\n \"[Sixb] Device authorization was denied.\"\n )\n }\n if (\n authorization.status !== \"approved\" ||\n authorization.expiresAt <= input.completedAt ||\n !authorization.approvedUserId ||\n !authorization.approvedSessionId ||\n input.session.projectId !== input.projectId ||\n input.session.userId !== authorization.approvedUserId\n ) {\n throw new AuthStorageError(\n \"invalid_device_authorization\",\n \"[Sixb] Device authorization is invalid.\"\n )\n }\n}\n",
25
+ "import type { Database, SQLQueryBindings } from \"bun:sqlite\"\nimport {\n artifactStateBytes,\n artifactStorageErrors,\n checkArtifactStateWrite,\n parseArtifactFrameGrantRow,\n parseArtifactRow,\n parseArtifactStateRow,\n parseArtifactVersionRow,\n} from \"@sixb/core/internal/storage\"\nimport type {\n ArtifactFrameGrantRecord,\n ArtifactRecord,\n ArtifactStateEntry,\n ArtifactStateKeyInput,\n ArtifactStateScope,\n ArtifactStorage,\n ArtifactVersionInput,\n ArtifactVersionRecord,\n CopyArtifactInput,\n CreateArtifactInput,\n DeleteArtifactInput,\n DeleteArtifactVersionsByOriginInput,\n DeleteExpiredArtifactFrameGrantsInput,\n FindArtifactFrameGrantInput,\n GetArtifactInput,\n GetArtifactVersionInput,\n ListArtifactsInput,\n ListArtifactsResult,\n ListArtifactVersionsInput,\n ListArtifactVersionsResult,\n ListReferencingVersionsInput,\n PublishArtifactVersionInput,\n PublishedArtifactVersion,\n SetArtifactStateInput,\n} from \"@sixb/core/storage\"\nimport { runImmediateTransaction, type SqliteStoreConnection } from \"./transactions\"\n\nconst ARTIFACT_COLUMNS = `\n project_id AS projectId, id, kind, title,\n owner_principal_type AS ownerPrincipalType, owner_principal_id AS ownerPrincipalId,\n latest_version AS latestVersion, created_at AS createdAt, updated_at AS updatedAt\n`\n\nconst VERSION_COLUMNS = `\n project_id AS projectId, artifact_id AS artifactId, version, title, entry, files, outline, refs,\n author_principal_type AS authorPrincipalType, author_principal_id AS authorPrincipalId,\n origin_thread_id AS originThreadId, origin_run_id AS originRunId, created_at AS createdAt\n`\n\nconst FRAME_GRANT_COLUMNS = `\n project_id AS projectId, token_hash AS tokenHash, artifact_id AS artifactId, version, targets,\n created_at AS createdAt, expires_at AS expiresAt\n`\n\nconst STATE_COLUMNS = \"key, value, size_bytes AS sizeBytes, updated_at AS updatedAt\"\n\n/** One reader of one artifact: the bindings that follow `STATE_SCOPE`. */\nconst STATE_SCOPE = \"project_id = ? AND artifact_id = ? AND principal_type = ? AND principal_id = ?\"\n\nfunction stateScope(input: ArtifactStateScope): SQLQueryBindings[] {\n return [input.projectId, input.artifactId, input.principal.type, input.principal.id]\n}\n\ntype Row = Record<string, unknown>\n\nexport class SqliteArtifactStorage implements ArtifactStorage {\n private readonly db: Database\n\n constructor(connection: SqliteStoreConnection) {\n this.db = connection.db\n }\n\n async create(input: CreateArtifactInput): Promise<PublishedArtifactVersion> {\n return runImmediateTransaction(this.db, () => {\n const createdAt = input.version.createdAt.toISOString()\n const artifact = this.db\n .query(\n `INSERT INTO artifacts (\n project_id, id, kind, title, owner_principal_type, owner_principal_id,\n latest_version, next_version, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, 1, 2, ?, ?)\n ON CONFLICT (project_id, id) DO NOTHING\n RETURNING ${ARTIFACT_COLUMNS}`\n )\n .get(\n input.projectId,\n input.id,\n input.kind,\n input.version.title,\n input.owner.type,\n input.owner.id,\n createdAt,\n createdAt\n ) as Row | null\n if (!artifact) throw artifactStorageErrors.exists(input.id)\n return {\n artifact: parseArtifactRow(artifact),\n version: this.insertVersion(input.projectId, input.id, 1, input.version),\n }\n })\n }\n\n async publish(input: PublishArtifactVersionInput): Promise<PublishedArtifactVersion> {\n return runImmediateTransaction(this.db, () => {\n const current = this.db\n .query(\n `SELECT kind, next_version AS nextVersion, latest_version AS latestVersion\n FROM artifacts WHERE project_id = ? AND id = ?`\n )\n .get(input.projectId, input.artifactId) as {\n readonly kind: ArtifactRecord[\"kind\"]\n readonly nextVersion: number\n readonly latestVersion: number\n } | null\n if (!current) throw artifactStorageErrors.notFound(input.artifactId)\n if (current.kind !== input.kind) {\n throw artifactStorageErrors.kindMismatch(input.artifactId, current.kind, input.kind)\n }\n // Inside the write transaction: a publish from the same base after this one finds it moved.\n if (input.baseVersion !== undefined && current.latestVersion !== input.baseVersion) {\n const latest = parseArtifactVersionRow(\n this.db\n .query(\n `SELECT ${VERSION_COLUMNS} FROM artifact_versions\n WHERE project_id = ? AND artifact_id = ? AND version = ?`\n )\n .get(input.projectId, input.artifactId, current.latestVersion) as Row\n )\n throw artifactStorageErrors.moved(input.artifactId, input.baseVersion, {\n version: latest.version,\n author: latest.author,\n })\n }\n const version = this.insertVersion(\n input.projectId,\n input.artifactId,\n current.nextVersion,\n input.version\n )\n const artifact = this.db\n .query(\n `UPDATE artifacts\n SET title = ?, latest_version = ?, next_version = ?, updated_at = ?\n WHERE project_id = ? AND id = ?\n RETURNING ${ARTIFACT_COLUMNS}`\n )\n .get(\n input.version.title,\n version.version,\n version.version + 1,\n input.version.createdAt.toISOString(),\n input.projectId,\n input.artifactId\n ) as Row\n return { artifact: parseArtifactRow(artifact), version }\n })\n }\n\n async get(input: GetArtifactInput): Promise<ArtifactRecord | null> {\n const row = this.db\n .query(`SELECT ${ARTIFACT_COLUMNS} FROM artifacts WHERE project_id = ? AND id = ?`)\n .get(input.projectId, input.id) as Row | null\n return row ? parseArtifactRow(row) : null\n }\n\n async list(input: ListArtifactsInput): Promise<ListArtifactsResult> {\n const where = [\"a.project_id = ?\"]\n const params: SQLQueryBindings[] = [input.projectId]\n if (input.owner) {\n where.push(\"a.owner_principal_type = ? AND a.owner_principal_id = ?\")\n params.push(input.owner.type, input.owner.id)\n }\n if (input.threadId !== undefined) {\n where.push(\n `EXISTS (\n SELECT 1 FROM artifact_threads t\n WHERE t.project_id = a.project_id AND t.artifact_id = a.id AND t.thread_id = ?\n )`\n )\n params.push(input.threadId)\n }\n if (input.kind !== undefined) {\n where.push(\"a.kind = ?\")\n params.push(input.kind)\n }\n const clause = where.join(\" AND \")\n const { total } = this.db\n .query(`SELECT COUNT(*) AS total FROM artifacts a WHERE ${clause}`)\n .get(...params) as { readonly total: number }\n const offset = input.offset ?? 0\n const rows = this.db\n .query(\n `SELECT ${ARTIFACT_COLUMNS} FROM artifacts a WHERE ${clause}\n ORDER BY a.updated_at DESC, a.id ASC LIMIT ? OFFSET ?`\n )\n .all(...params, input.limit ?? -1, offset) as Row[]\n return {\n artifacts: rows.map(parseArtifactRow),\n hasMore: offset + rows.length < total,\n total,\n }\n }\n\n async getVersion(input: GetArtifactVersionInput): Promise<ArtifactVersionRecord | null> {\n const row = this.db\n .query(\n `SELECT ${VERSION_COLUMNS} FROM artifact_versions\n WHERE project_id = ? AND artifact_id = ? AND version = ?`\n )\n .get(input.projectId, input.artifactId, input.version) as Row | null\n return row ? parseArtifactVersionRow(row) : null\n }\n\n async listVersions(input: ListArtifactVersionsInput): Promise<ListArtifactVersionsResult> {\n const { total } = this.db\n .query(\n \"SELECT COUNT(*) AS total FROM artifact_versions WHERE project_id = ? AND artifact_id = ?\"\n )\n .get(input.projectId, input.artifactId) as { readonly total: number }\n const offset = input.offset ?? 0\n const rows = this.db\n .query(\n `SELECT ${VERSION_COLUMNS} FROM artifact_versions\n WHERE project_id = ? AND artifact_id = ?\n ORDER BY version DESC LIMIT ? OFFSET ?`\n )\n .all(input.projectId, input.artifactId, input.limit ?? -1, offset) as Row[]\n return {\n versions: rows.map(parseArtifactVersionRow),\n hasMore: offset + rows.length < total,\n total,\n }\n }\n\n async listReferencingVersions(\n input: ListReferencingVersionsInput\n ): Promise<ArtifactVersionRecord[]> {\n // An address names the artifact when the id is followed by nothing, a version, a file, or a\n // part.\n const prefix = `artifact:${input.artifactId}`\n const rows = this.db\n .query(\n `SELECT ${VERSION_COLUMNS} FROM artifact_versions v\n WHERE (project_id, artifact_id, version) IN (\n SELECT project_id, id, latest_version FROM artifacts WHERE project_id = ?\n ) AND EXISTS (\n SELECT 1 FROM json_each(v.refs) r\n WHERE substr(json_extract(r.value, '$.address'), 1, ?) = ?\n AND substr(json_extract(r.value, '$.address'), ? + 1, 1) IN ('', '@', '/', '#')\n )\n ORDER BY artifact_id`\n )\n .all(input.projectId, prefix.length, prefix, prefix.length) as Row[]\n return rows.map(parseArtifactVersionRow)\n }\n\n async listThreadIds(input: GetArtifactInput): Promise<string[]> {\n const rows = this.db\n .query(\n `SELECT thread_id AS threadId FROM artifact_threads\n WHERE project_id = ? AND artifact_id = ? ORDER BY thread_id`\n )\n .all(input.projectId, input.id) as { readonly threadId: string }[]\n return rows.map((row) => row.threadId)\n }\n\n async copy(input: CopyArtifactInput): Promise<ArtifactRecord> {\n return runImmediateTransaction(this.db, () => {\n const source = this.db\n .query(\"SELECT id FROM artifacts WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.sourceId)\n if (!source) throw artifactStorageErrors.notFound(input.sourceId)\n\n const artifact = this.db\n .query(\n `INSERT INTO artifacts (\n project_id, id, kind, title, owner_principal_type, owner_principal_id,\n latest_version, next_version, created_at, updated_at\n )\n SELECT project_id, ?, kind, title, ?, ?, latest_version, next_version, created_at,\n updated_at\n FROM artifacts WHERE project_id = ? AND id = ?\n ON CONFLICT (project_id, id) DO NOTHING\n RETURNING ${ARTIFACT_COLUMNS}`\n )\n .get(\n input.id,\n input.owner.type,\n input.owner.id,\n input.projectId,\n input.sourceId\n ) as Row | null\n if (!artifact) throw artifactStorageErrors.exists(input.id)\n\n this.db\n .query(\n `INSERT INTO artifact_versions (\n project_id, artifact_id, version, title, entry, files, outline, refs,\n author_principal_type, author_principal_id, created_at\n )\n SELECT project_id, ?, version, title, entry, files, outline, refs,\n author_principal_type, author_principal_id, created_at\n FROM artifact_versions WHERE project_id = ? AND artifact_id = ?`\n )\n .run(input.id, input.projectId, input.sourceId)\n this.db\n .query(\n `INSERT INTO artifact_threads (project_id, artifact_id, thread_id, shared_at, copied)\n VALUES (?, ?, ?, ?, 1)`\n )\n .run(\n input.projectId,\n input.id,\n input.threadId,\n (input.copiedAt ?? new Date()).toISOString()\n )\n return parseArtifactRow(artifact)\n })\n }\n\n async createFrameGrant(record: ArtifactFrameGrantRecord): Promise<void> {\n runImmediateTransaction(this.db, () => {\n const exists = this.db\n .query(\"SELECT 1 FROM artifacts WHERE project_id = ? AND id = ?\")\n .get(record.projectId, record.artifactId)\n if (!exists) throw artifactStorageErrors.notFound(record.artifactId)\n this.db\n .query(\n `INSERT INTO artifact_frame_grants\n (project_id, token_hash, artifact_id, version, targets, created_at, expires_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)`\n )\n .run(\n record.projectId,\n record.tokenHash,\n record.artifactId,\n record.version,\n JSON.stringify(record.targets),\n record.createdAt.toISOString(),\n record.expiresAt.toISOString()\n )\n })\n }\n\n async findFrameGrant(\n input: FindArtifactFrameGrantInput\n ): Promise<ArtifactFrameGrantRecord | null> {\n const row = this.db\n .query(\n `SELECT ${FRAME_GRANT_COLUMNS} FROM artifact_frame_grants\n WHERE project_id = ? AND token_hash = ?`\n )\n .get(input.projectId, input.tokenHash) as Row | null\n return row ? parseArtifactFrameGrantRow(row) : null\n }\n\n async deleteExpiredFrameGrants(input: DeleteExpiredArtifactFrameGrantsInput): Promise<number> {\n return this.db\n .query(\n `DELETE FROM artifact_frame_grants WHERE rowid IN (\n SELECT rowid FROM artifact_frame_grants\n WHERE project_id = ? AND expires_at < ?\n ORDER BY expires_at LIMIT ?\n )`\n )\n .run(input.projectId, input.expiredBefore.toISOString(), input.limit).changes\n }\n\n async getState(input: ArtifactStateKeyInput): Promise<ArtifactStateEntry | null> {\n const row = this.db\n .query(`SELECT ${STATE_COLUMNS} FROM artifact_state WHERE ${STATE_SCOPE} AND key = ?`)\n .get(...stateScope(input), input.key) as Row | null\n return row ? parseArtifactStateRow(row) : null\n }\n\n async setState(input: SetArtifactStateInput): Promise<void> {\n runImmediateTransaction(this.db, () => {\n const artifact = this.db\n .query(\"SELECT 1 FROM artifacts WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.artifactId)\n if (!artifact) throw artifactStorageErrors.notFound(input.artifactId)\n // In the write transaction: two writes at once cannot both fit under the limits.\n const others = this.db\n .query(\n `SELECT count(*) AS keys, coalesce(sum(size_bytes), 0) AS bytes FROM artifact_state\n WHERE ${STATE_SCOPE} AND key <> ?`\n )\n .get(...stateScope(input), input.key) as { readonly keys: number; readonly bytes: number }\n const sizeBytes = artifactStateBytes(input.value)\n checkArtifactStateWrite({ key: input.key, valueBytes: sizeBytes, others })\n this.db\n .query(\n `INSERT INTO artifact_state (\n project_id, artifact_id, principal_type, principal_id, key, value, size_bytes,\n updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (project_id, artifact_id, principal_type, principal_id, key) DO UPDATE SET\n value = excluded.value, size_bytes = excluded.size_bytes,\n updated_at = excluded.updated_at`\n )\n .run(...stateScope(input), input.key, input.value, sizeBytes, input.updatedAt.toISOString())\n })\n }\n\n async deleteState(input: ArtifactStateKeyInput): Promise<boolean> {\n return (\n this.db\n .query(`DELETE FROM artifact_state WHERE ${STATE_SCOPE} AND key = ?`)\n .run(...stateScope(input), input.key).changes > 0\n )\n }\n\n async listState(input: ArtifactStateScope): Promise<ArtifactStateEntry[]> {\n const rows = this.db\n .query(`SELECT ${STATE_COLUMNS} FROM artifact_state WHERE ${STATE_SCOPE} ORDER BY key`)\n .all(...stateScope(input)) as Row[]\n return rows.map(parseArtifactStateRow)\n }\n\n async clearState(input: ArtifactStateScope): Promise<number> {\n return this.db\n .query(`DELETE FROM artifact_state WHERE ${STATE_SCOPE}`)\n .run(...stateScope(input)).changes\n }\n\n async delete(input: DeleteArtifactInput): Promise<boolean> {\n // Versions, frame grants, and state go with the artifact through ON DELETE CASCADE.\n return (\n this.db\n .query(\"DELETE FROM artifacts WHERE project_id = ? AND id = ?\")\n .run(input.projectId, input.id).changes > 0\n )\n }\n\n async deleteVersionsByOrigin(input: DeleteArtifactVersionsByOriginInput): Promise<number> {\n return runImmediateTransaction(this.db, () => {\n const affected = this.db\n .query(\n `SELECT DISTINCT artifact_id AS artifactId FROM artifact_versions\n WHERE project_id = ? AND origin_run_id = ?`\n )\n .all(input.projectId, input.runId) as { readonly artifactId: string }[]\n const deleted = this.db\n .query(\n `DELETE FROM artifact_versions WHERE project_id = ? AND origin_run_id = ?\n RETURNING origin_thread_id AS threadId`\n )\n .all(input.projectId, input.runId) as { readonly threadId: string }[]\n // A run publishes from one thread: its artifacts stay shared there only while a version\n // from it remains, or when they were copied for it.\n const threadId = deleted[0]?.threadId\n for (const { artifactId } of affected) {\n this.db\n .query(\n `DELETE FROM artifact_threads\n WHERE project_id = ? AND artifact_id = ? AND thread_id = ? AND copied = 0\n AND NOT EXISTS (\n SELECT 1 FROM artifact_versions\n WHERE project_id = ? AND artifact_id = ? AND origin_thread_id = ?\n )`\n )\n .run(\n input.projectId,\n artifactId,\n threadId ?? null,\n input.projectId,\n artifactId,\n threadId ?? null\n )\n this.repointLatest(input.projectId, artifactId)\n }\n return deleted.length\n })\n }\n\n /** Point an artifact at its newest remaining version, or delete it when none remains. */\n private repointLatest(projectId: string, artifactId: string): void {\n const latest = this.db\n .query(\n `SELECT version, title, created_at AS createdAt FROM artifact_versions\n WHERE project_id = ? AND artifact_id = ? ORDER BY version DESC LIMIT 1`\n )\n .get(projectId, artifactId) as {\n readonly version: number\n readonly title: string\n readonly createdAt: string\n } | null\n if (!latest) {\n this.db\n .query(\"DELETE FROM artifacts WHERE project_id = ? AND id = ?\")\n .run(projectId, artifactId)\n return\n }\n this.db\n .query(\n `UPDATE artifacts SET title = ?, latest_version = ?, updated_at = ?\n WHERE project_id = ? AND id = ?`\n )\n .run(latest.title, latest.version, latest.createdAt, projectId, artifactId)\n }\n\n private insertVersion(\n projectId: string,\n artifactId: string,\n version: number,\n input: ArtifactVersionInput\n ): ArtifactVersionRecord {\n const row = this.db\n .query(\n `INSERT INTO artifact_versions (\n project_id, artifact_id, version, title, entry, files, outline, refs,\n author_principal_type, author_principal_id, origin_thread_id, origin_run_id, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n RETURNING ${VERSION_COLUMNS}`\n )\n .get(\n projectId,\n artifactId,\n version,\n input.title,\n input.entry,\n JSON.stringify(input.files),\n JSON.stringify(input.outline),\n JSON.stringify(input.references),\n input.author.type,\n input.author.id,\n input.origin?.threadId ?? null,\n input.origin?.runId ?? null,\n input.createdAt.toISOString()\n ) as Row\n if (input.origin) {\n this.linkThread(projectId, artifactId, input.origin.threadId, input.createdAt)\n }\n return parseArtifactVersionRow(row)\n }\n\n /** Shares an artifact in a thread, keeping when it was first shared there. */\n private linkThread(\n projectId: string,\n artifactId: string,\n threadId: string,\n sharedAt: Date\n ): void {\n this.db\n .query(\n `INSERT INTO artifact_threads (project_id, artifact_id, thread_id, shared_at)\n VALUES (?, ?, ?, ?)\n ON CONFLICT (project_id, artifact_id, thread_id) DO NOTHING`\n )\n .run(projectId, artifactId, threadId, sharedAt.toISOString())\n }\n}\n",
26
+ "import type { Database } from \"bun:sqlite\"\nimport type {\n AuthStorage,\n CompleteDeviceAuthorizationInput,\n CompleteDeviceAuthorizationResult,\n CompleteMagicLinkSignInInput,\n CompleteOidcSignInInput,\n CompleteSignInResult,\n DeviceAuthorizationRecord,\n GroupMembershipRecord,\n GroupMembershipSource,\n InvitationRecord,\n SessionRecord,\n SuspendUserAndRevokeSessionsInput,\n UpdateAuthUserResult,\n UserIdentityRecord,\n UserRecord,\n} from \"@sixb/core/storage\"\nimport { AuthStorageError } from \"@sixb/core/storage\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n runImmediateTransaction,\n type SqliteStoreConnection,\n} from \"../transactions\"\nimport { SqliteAuthAccessTokenStore } from \"./access-tokens\"\nimport {\n getDeviceAuthorizationById,\n SqliteAuthDeviceAuthorizationStore,\n} from \"./device-authorizations\"\nimport { SqliteAuthGroupMembershipStore } from \"./group-memberships\"\nimport { SqliteAuthUserIdentityStore } from \"./identities\"\nimport { SqliteAuthInvitationStore } from \"./invitations\"\nimport { SqliteAuthMagicLinkStore } from \"./magic-links\"\nimport { SqliteAuthOidcAuthorizationAttemptStore } from \"./oidc-attempts\"\nimport type { SqliteAuthMagicLinkRow, SqliteAuthOidcAttemptRow, SqliteAuthUserRow } from \"./rows\"\nimport { rowToIdentityRecord, rowToUserRecord, serializeOptionalRecord } from \"./rows\"\nimport { SqliteAuthServiceAccountGroupMembershipStore } from \"./service-account-group-memberships\"\nimport { SqliteAuthServiceAccountStore } from \"./service-accounts\"\nimport { SqliteAuthSessionStore } from \"./sessions\"\nimport {\n assertNonEmpty,\n consumeMagicLink,\n consumeOidcAttempt,\n createSession,\n getActiveInvitationByEmail,\n getIdentityRowBySubject,\n getMagicLinkRowById,\n getOidcAttemptRowById,\n getUserRowByEmail,\n getUserRowById,\n mapUniqueConstraintError,\n normalizeEmail,\n normalizeGroupIds,\n revokeActiveSessionsForUser,\n toIso,\n upsertGroupMembership,\n validateCompleteSessionInput,\n} from \"./shared\"\nimport { SqliteAuthUserStore } from \"./users\"\n\ninterface AuthTransactionError {\n readonly error: AuthStorageError\n}\n\nexport interface SqliteAuthStorageOptions {\n /** Path to SQLite database file. Defaults to ':memory:' for in-memory database. */\n path?: string\n /** Internal shared connection used by bundled SqliteStorage. */\n connection?: SqliteStoreConnection\n}\n\nexport class SqliteAuthStorage implements AuthStorage {\n private readonly connection: SqliteStoreConnection\n private readonly db: Database\n\n readonly users: SqliteAuthUserStore\n readonly identities: SqliteAuthUserIdentityStore\n readonly serviceAccounts: SqliteAuthServiceAccountStore\n readonly serviceAccountGroupMemberships: SqliteAuthServiceAccountGroupMembershipStore\n readonly sessions: SqliteAuthSessionStore\n readonly accessTokens: SqliteAuthAccessTokenStore\n readonly invitations: SqliteAuthInvitationStore\n readonly groupMemberships: SqliteAuthGroupMembershipStore\n readonly magicLinks: SqliteAuthMagicLinkStore\n readonly oidcAuthorizationAttempts: SqliteAuthOidcAuthorizationAttemptStore\n readonly deviceAuthorizations: SqliteAuthDeviceAuthorizationStore\n\n constructor(options: SqliteAuthStorageOptions = {}) {\n this.connection = openSqliteStoreConnection(options)\n this.db = this.connection.db\n\n this.users = new SqliteAuthUserStore(this.db)\n this.identities = new SqliteAuthUserIdentityStore(this.db)\n this.serviceAccounts = new SqliteAuthServiceAccountStore(this.db)\n this.serviceAccountGroupMemberships = new SqliteAuthServiceAccountGroupMembershipStore(this.db)\n this.sessions = new SqliteAuthSessionStore(this.db)\n this.accessTokens = new SqliteAuthAccessTokenStore(this.db)\n this.invitations = new SqliteAuthInvitationStore(this.db)\n this.groupMemberships = new SqliteAuthGroupMembershipStore(this.db)\n this.magicLinks = new SqliteAuthMagicLinkStore(this.db)\n this.oidcAuthorizationAttempts = new SqliteAuthOidcAuthorizationAttemptStore(this.db)\n this.deviceAuthorizations = new SqliteAuthDeviceAuthorizationStore(this.db)\n }\n\n async completeDeviceAuthorization(\n input: CompleteDeviceAuthorizationInput\n ): Promise<CompleteDeviceAuthorizationResult> {\n return runImmediateTransaction(this.db, () => {\n const authorization = getDeviceAuthorizationById(this.db, input.projectId, input.id)\n if (!authorization) {\n throw new AuthStorageError(\n \"missing_device_authorization\",\n `[Sixb] Device authorization '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n assertCompletableDeviceAuthorization(authorization, input)\n const session = createSession(this.db, input.session)\n this.db\n .query(`\n UPDATE auth_device_authorizations\n SET status = 'consumed', consumed_at = ?\n WHERE project_id = ? AND id = ? AND status = 'approved'\n `)\n .run(toIso(input.completedAt), input.projectId, input.id)\n return {\n authorization: {\n ...authorization,\n status: \"consumed\",\n consumedAt: new Date(input.completedAt),\n },\n session,\n }\n })\n }\n\n async completeMagicLinkSignIn(\n input: CompleteMagicLinkSignInInput\n ): Promise<CompleteSignInResult> {\n const result = runImmediateTransaction(\n this.db,\n (): CompleteSignInResult | AuthTransactionError => {\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const completedAt = new Date(input.completedAt)\n const magicLink = getMagicLinkRowById(this.db, {\n projectId,\n id: input.magicLinkId,\n })\n\n this.assertMagicLinkUsable(\n projectId,\n input.magicLinkId,\n input.tokenHash,\n completedAt,\n magicLink\n )\n\n const existingUserRow = getUserRowByEmail(this.db, {\n projectId,\n email: magicLink.email,\n })\n const activeInvitation = getActiveInvitationByEmail(this.db, {\n projectId,\n email: magicLink.email,\n now: completedAt,\n })\n const shouldCreateUser = !existingUserRow\n const manualGroupIds = normalizeGroupIds(input.manualGroupIds)\n\n if (existingUserRow?.status === \"suspended\") {\n consumeMagicLink(this.db, {\n projectId,\n id: input.magicLinkId,\n tokenHash: input.tokenHash,\n consumedAt: completedAt,\n })\n return {\n error: new AuthStorageError(\n \"suspended_user\",\n `[Sixb] User '${existingUserRow.id}' is suspended for project '${projectId}'.`\n ),\n }\n }\n\n if (shouldCreateUser && !activeInvitation && !input.allowUserCreationWithoutInvitation) {\n consumeMagicLink(this.db, {\n projectId,\n id: input.magicLinkId,\n tokenHash: input.tokenHash,\n consumedAt: completedAt,\n })\n return {\n error: new AuthStorageError(\n \"user_creation_not_allowed\",\n `[Sixb] Magic link '${input.magicLinkId}' cannot create a user for project '${projectId}'.`\n ),\n }\n }\n\n validateCompleteSessionInput(this.db, projectId, input.session)\n\n let newUserId: string | undefined\n if (shouldCreateUser) {\n newUserId = assertNonEmpty(input.newUserId, \"User id\")\n if (getUserRowById(this.db, { projectId, id: newUserId })) {\n throw new AuthStorageError(\n \"duplicate_user\",\n `[Sixb] User '${newUserId}' already exists for project '${projectId}'.`\n )\n }\n }\n\n consumeMagicLink(this.db, {\n projectId,\n id: input.magicLinkId,\n tokenHash: input.tokenHash,\n consumedAt: completedAt,\n })\n\n const previousUser = existingUserRow ? rowToUserRecord(existingUserRow) : null\n const user =\n previousUser ??\n this.insertUser({\n id: newUserId ?? assertNonEmpty(input.newUserId, \"User id\"),\n projectId,\n email: magicLink.email,\n displayName: input.newUserDisplayName,\n avatarUrl: input.newUserAvatarUrl,\n createdAt: completedAt,\n })\n\n const invitation = this.acceptInvitationAndApplyGroups({\n activeInvitation,\n completedAt,\n projectId,\n user,\n })\n const groupMemberships = this.applyGroups({\n completedAt,\n source: \"manual\",\n existing: invitation.groupMemberships,\n groupIds: manualGroupIds,\n projectId,\n userId: user.id,\n })\n const session = this.createSignInSession({\n projectId,\n strategyId: magicLink.strategy_id,\n session: input.session,\n userId: user.id,\n })\n\n return {\n user,\n session,\n invitation: invitation.invitation,\n groupMemberships,\n previousUser,\n }\n }\n )\n\n if (\"error\" in result) {\n throw result.error\n }\n\n return result\n }\n\n async completeOidcSignIn(input: CompleteOidcSignInInput): Promise<CompleteSignInResult> {\n const result = runImmediateTransaction(\n this.db,\n (): CompleteSignInResult | AuthTransactionError => {\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const completedAt = new Date(input.completedAt)\n const attempt = getOidcAttemptRowById(this.db, {\n projectId,\n id: input.oidcAuthorizationAttemptId,\n })\n\n this.assertOidcAttemptUsable(\n projectId,\n input.oidcAuthorizationAttemptId,\n input.stateHash,\n completedAt,\n attempt\n )\n\n const subject = assertNonEmpty(input.subject, \"Subject\")\n const email = normalizeEmail(input.email)\n const identity = getIdentityRowBySubject(this.db, {\n projectId,\n strategyId: attempt.strategy_id,\n subject,\n })\n const activeInvitation = identity\n ? null\n : getActiveInvitationByEmail(this.db, {\n projectId,\n email,\n now: completedAt,\n })\n const userRow = identity\n ? getUserRowById(this.db, { projectId, id: identity.user_id })\n : getUserRowByEmail(this.db, { projectId, email })\n const shouldCreateUser = !identity && !userRow\n const manualGroupIds = normalizeGroupIds(input.manualGroupIds)\n\n if (identity && !userRow) {\n this.consumeOidcAttempt(input, completedAt, projectId)\n return {\n error: new AuthStorageError(\n \"missing_user\",\n `[Sixb] User '${identity.user_id}' not found for linked OIDC identity.`\n ),\n }\n }\n\n if (userRow?.status === \"suspended\") {\n this.consumeOidcAttempt(input, completedAt, projectId)\n return {\n error: new AuthStorageError(\n \"suspended_user\",\n `[Sixb] User '${userRow.id}' is suspended for project '${projectId}'.`\n ),\n }\n }\n\n if (shouldCreateUser && !activeInvitation && !input.allowUserCreationWithoutInvitation) {\n this.consumeOidcAttempt(input, completedAt, projectId)\n return {\n error: new AuthStorageError(\n \"user_creation_not_allowed\",\n `[Sixb] OIDC authorization attempt '${input.oidcAuthorizationAttemptId}' cannot create a user for project '${projectId}'.`\n ),\n }\n }\n\n validateCompleteSessionInput(this.db, projectId, input.session)\n\n let newUserId: string | undefined\n if (shouldCreateUser) {\n newUserId = assertNonEmpty(input.newUserId, \"User id\")\n if (getUserRowById(this.db, { projectId, id: newUserId })) {\n throw new AuthStorageError(\n \"duplicate_user\",\n `[Sixb] User '${newUserId}' already exists for project '${projectId}'.`\n )\n }\n }\n\n this.consumeOidcAttempt(input, completedAt, projectId)\n\n const previousUser = userRow ? rowToUserRecord(userRow) : null\n let user: UserRecord\n if (!userRow) {\n user = this.insertUser({\n id: newUserId ?? assertNonEmpty(input.newUserId, \"User id\"),\n projectId,\n email,\n displayName: input.displayName,\n avatarUrl: input.avatarUrl,\n createdAt: completedAt,\n })\n } else {\n user = this.refreshProviderProfile(userRow, input, completedAt)\n }\n\n const invitation = this.acceptInvitationAndApplyGroups({\n activeInvitation,\n completedAt,\n projectId,\n user,\n })\n const groupMemberships = this.syncDirectoryGroups({\n completedAt,\n existing: this.applyGroups({\n completedAt,\n source: \"manual\",\n existing: invitation.groupMemberships,\n groupIds: manualGroupIds,\n projectId,\n userId: user.id,\n }),\n groupIds: input.directoryGroupIds,\n projectId,\n userId: user.id,\n })\n const nextIdentity = this.upsertIdentity({\n projectId,\n strategyId: attempt.strategy_id,\n subject,\n userId: user.id,\n claims: input.claims,\n createdAt: identity ? new Date(identity.created_at) : completedAt,\n updatedAt: completedAt,\n })\n const session = this.createSignInSession({\n projectId,\n strategyId: attempt.strategy_id,\n session: input.session,\n userId: user.id,\n })\n\n return {\n user,\n session,\n identity: nextIdentity,\n invitation: invitation.invitation,\n groupMemberships,\n previousUser,\n }\n }\n )\n\n if (\"error\" in result) {\n throw result.error\n }\n\n return result\n }\n\n async suspendUserAndRevokeSessions(\n input: SuspendUserAndRevokeSessionsInput\n ): Promise<UpdateAuthUserResult> {\n return runImmediateTransaction(this.db, () => {\n const existing = getUserRowById(this.db, {\n projectId: input.projectId,\n id: input.userId,\n })\n\n if (!existing) {\n throw new AuthStorageError(\n \"missing_user\",\n `[Sixb] User '${input.userId}' not found for project '${input.projectId}'.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE auth_users\n SET status = 'suspended',\n updated_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(toIso(input.suspendedAt), input.projectId, input.userId)\n revokeActiveSessionsForUser(this.db, {\n projectId: input.projectId,\n userId: input.userId,\n revokedAt: input.suspendedAt,\n })\n\n const user = rowToUserRecord({\n ...existing,\n status: \"suspended\",\n updated_at: toIso(input.suspendedAt),\n })\n return { user, previousUser: rowToUserRecord(existing) }\n })\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n\n private assertMagicLinkUsable(\n projectId: string,\n id: string,\n tokenHash: string,\n completedAt: Date,\n row: SqliteAuthMagicLinkRow | null\n ): asserts row is SqliteAuthMagicLinkRow {\n if (!row) {\n throw new AuthStorageError(\n \"missing_magic_link\",\n `[Sixb] Magic link '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (row.token_hash !== tokenHash || row.consumed_at || row.revoked_at) {\n throw new AuthStorageError(\n \"invalid_magic_link\",\n `[Sixb] Magic link '${id}' is not valid for project '${projectId}'.`\n )\n }\n\n if (new Date(row.expires_at) <= completedAt) {\n throw new AuthStorageError(\n \"expired_magic_link\",\n `[Sixb] Magic link '${id}' is expired for project '${projectId}'.`\n )\n }\n }\n\n private assertOidcAttemptUsable(\n projectId: string,\n id: string,\n stateHash: string,\n completedAt: Date,\n row: SqliteAuthOidcAttemptRow | null\n ): asserts row is SqliteAuthOidcAttemptRow {\n if (!row) {\n throw new AuthStorageError(\n \"missing_oidc_attempt\",\n `[Sixb] OIDC authorization attempt '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (row.state_hash !== stateHash || row.consumed_at) {\n throw new AuthStorageError(\n \"invalid_oidc_attempt\",\n `[Sixb] OIDC authorization attempt '${id}' is not valid for project '${projectId}'.`\n )\n }\n\n if (new Date(row.expires_at) <= completedAt) {\n throw new AuthStorageError(\n \"expired_oidc_attempt\",\n `[Sixb] OIDC authorization attempt '${id}' is expired for project '${projectId}'.`\n )\n }\n }\n\n // The identity provider owns the name and picture it sends: every sign-in overwrites them, and\n // one it leaves out keeps the stored value.\n private refreshProviderProfile(\n row: SqliteAuthUserRow,\n input: CompleteOidcSignInInput,\n updatedAt: Date\n ): UserRecord {\n const displayName = input.displayName ?? row.display_name\n const avatarUrl = input.avatarUrl ?? row.avatar_url\n if (displayName === row.display_name && avatarUrl === row.avatar_url) {\n return rowToUserRecord(row)\n }\n\n this.db\n .query(\n `\n UPDATE auth_users\n SET display_name = ?,\n avatar_url = ?,\n updated_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(displayName, avatarUrl, toIso(updatedAt), row.project_id, row.id)\n\n return rowToUserRecord({\n ...row,\n display_name: displayName,\n avatar_url: avatarUrl,\n updated_at: toIso(updatedAt),\n })\n }\n\n private insertUser(input: {\n readonly id: string\n readonly projectId: string\n readonly email: string\n readonly displayName?: string\n readonly avatarUrl?: string\n readonly createdAt: Date\n }): UserRecord {\n try {\n this.db\n .query(\n `\n INSERT INTO auth_users (\n project_id,\n id,\n email,\n display_name,\n avatar_url,\n status,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?, 'active', ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.email,\n input.displayName ?? null,\n input.avatarUrl ?? null,\n toIso(input.createdAt),\n toIso(input.createdAt)\n )\n } catch (error) {\n mapUniqueConstraintError(\n error,\n \"duplicate_user\",\n `[Sixb] User '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n return {\n id: input.id,\n projectId: input.projectId,\n email: input.email,\n displayName: input.displayName,\n avatarUrl: input.avatarUrl,\n status: \"active\",\n createdAt: new Date(input.createdAt),\n updatedAt: new Date(input.createdAt),\n }\n }\n\n private acceptInvitationAndApplyGroups(input: {\n readonly activeInvitation: InvitationRecord | null\n readonly completedAt: Date\n readonly projectId: string\n readonly user: UserRecord\n }): {\n readonly invitation?: InvitationRecord\n readonly groupMemberships: readonly GroupMembershipRecord[]\n } {\n if (!input.activeInvitation) {\n return { groupMemberships: [] }\n }\n\n this.db\n .query(\n `\n UPDATE auth_invitations\n SET status = 'accepted',\n accepted_at = ?,\n updated_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(\n toIso(input.completedAt),\n toIso(input.completedAt),\n input.projectId,\n input.activeInvitation.id\n )\n\n const invitation: InvitationRecord = {\n ...input.activeInvitation,\n status: \"accepted\",\n acceptedAt: new Date(input.completedAt),\n updatedAt: new Date(input.completedAt),\n }\n const groupMemberships = input.activeInvitation.groupIds.map((groupId) =>\n upsertGroupMembership(this.db, {\n projectId: input.projectId,\n userId: input.user.id,\n groupId,\n source: \"invitation\",\n createdAt: input.completedAt,\n })\n )\n\n return { invitation, groupMemberships }\n }\n\n private applyGroups(input: {\n readonly completedAt: Date\n readonly existing: readonly GroupMembershipRecord[]\n readonly groupIds: readonly string[]\n readonly projectId: string\n readonly source: GroupMembershipSource\n readonly userId: string\n }): readonly GroupMembershipRecord[] {\n const groupMemberships = [...input.existing]\n\n for (const groupId of input.groupIds) {\n groupMemberships.push(\n upsertGroupMembership(this.db, {\n projectId: input.projectId,\n userId: input.userId,\n groupId,\n source: input.source,\n createdAt: input.completedAt,\n })\n )\n }\n\n return groupMemberships\n }\n // Directory memberships become exactly `groupIds`. A group the user already holds from another\n // source keeps that source, and memberships from other sources are never removed.\n private syncDirectoryGroups(input: {\n readonly completedAt: Date\n readonly existing: readonly GroupMembershipRecord[]\n readonly groupIds?: readonly string[]\n readonly projectId: string\n readonly userId: string\n }): readonly GroupMembershipRecord[] {\n if (!input.groupIds) {\n return input.existing\n }\n\n const groupIds = normalizeGroupIds(input.groupIds)\n this.db\n .query(\n `\n DELETE FROM auth_group_memberships\n WHERE project_id = ?\n AND user_id = ?\n AND source = 'directory'\n AND group_id NOT IN (${groupIds.map(() => \"?\").join(\", \")})\n `\n )\n .run(input.projectId, input.userId, ...groupIds)\n\n return this.applyGroups({ ...input, groupIds, source: \"directory\" })\n }\n\n private createSignInSession(input: {\n readonly projectId: string\n readonly strategyId: string\n readonly session: CompleteMagicLinkSignInInput[\"session\"]\n readonly userId: string\n }): SessionRecord {\n return createSession(this.db, {\n id: input.session.id,\n projectId: input.projectId,\n userId: input.userId,\n strategyId: input.strategyId,\n tokenHash: input.session.tokenHash,\n createdAt: input.session.createdAt,\n expiresAt: input.session.expiresAt,\n absoluteExpiresAt: input.session.absoluteExpiresAt,\n userAgent: input.session.userAgent,\n ipAddress: input.session.ipAddress,\n })\n }\n\n private consumeOidcAttempt(\n input: CompleteOidcSignInInput,\n completedAt: Date,\n projectId: string\n ): void {\n consumeOidcAttempt(this.db, {\n projectId,\n id: input.oidcAuthorizationAttemptId,\n stateHash: input.stateHash,\n consumedAt: completedAt,\n })\n }\n\n private upsertIdentity(input: {\n readonly projectId: string\n readonly strategyId: string\n readonly subject: string\n readonly userId: string\n readonly claims?: Readonly<Record<string, unknown>>\n readonly createdAt: Date\n readonly updatedAt: Date\n }): UserIdentityRecord {\n this.db\n .query(\n `\n INSERT INTO auth_user_identities (\n project_id,\n strategy_id,\n subject,\n user_id,\n claims,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(project_id, strategy_id, subject)\n DO UPDATE SET\n user_id = excluded.user_id,\n claims = excluded.claims,\n updated_at = excluded.updated_at\n `\n )\n .run(\n input.projectId,\n input.strategyId,\n input.subject,\n input.userId,\n serializeOptionalRecord(input.claims),\n toIso(input.createdAt),\n toIso(input.updatedAt)\n )\n\n return rowToIdentityRecord({\n project_id: input.projectId,\n strategy_id: input.strategyId,\n subject: input.subject,\n user_id: input.userId,\n claims: serializeOptionalRecord(input.claims),\n created_at: toIso(input.createdAt),\n updated_at: toIso(input.updatedAt),\n })\n }\n}\n\nfunction assertCompletableDeviceAuthorization(\n authorization: DeviceAuthorizationRecord,\n input: CompleteDeviceAuthorizationInput\n): void {\n if (authorization.deviceCodeHash !== input.deviceCodeHash) {\n throw new AuthStorageError(\n \"invalid_device_authorization\",\n \"[Sixb] Invalid device authorization.\"\n )\n }\n if (authorization.status === \"pending\") {\n throw new AuthStorageError(\n \"pending_device_authorization\",\n \"[Sixb] Device authorization is pending.\"\n )\n }\n if (authorization.status === \"denied\") {\n throw new AuthStorageError(\n \"device_authorization_denied\",\n \"[Sixb] Device authorization was denied.\"\n )\n }\n if (\n authorization.status !== \"approved\" ||\n authorization.expiresAt <= input.completedAt ||\n !authorization.approvedUserId ||\n !authorization.approvedSessionId ||\n input.session.projectId !== input.projectId ||\n input.session.userId !== authorization.approvedUserId\n ) {\n throw new AuthStorageError(\n \"invalid_device_authorization\",\n \"[Sixb] Device authorization is invalid.\"\n )\n }\n}\n",
24
27
  "import type { Database } from \"bun:sqlite\"\nimport type {\n AccessTokenRecord,\n AuthAccessTokenStore,\n CreateAuthAccessTokenInput,\n ListAuthAccessTokensInput,\n ListAuthAccessTokensResult,\n} from \"@sixb/core/storage\"\nimport { AuthStorageError } from \"@sixb/core/storage\"\nimport type {\n SqliteAuthAccessTokenRow,\n SqliteAuthServiceAccountRow,\n SqliteAuthUserRow,\n} from \"./rows\"\nimport { rowToAccessTokenRecord, serializeOptionalStringArray } from \"./rows\"\nimport {\n appendPagination,\n assertNonEmpty,\n mapUniqueConstraintError,\n normalizeGroupIds,\n type SqliteValue,\n toIso,\n} from \"./shared\"\n\nfunction createAuthAccessToken(db: Database, input: CreateAuthAccessTokenInput): AccessTokenRecord {\n const id = assertNonEmpty(input.id, \"Access token id\")\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const name = assertNonEmpty(input.name, \"Access token name\")\n const subjectId = assertNonEmpty(input.subject.id, \"Access token subject id\")\n const tokenHash = assertNonEmpty(input.tokenHash, \"Access token hash\")\n assertKindMatchesSubject(input)\n assertSubjectExists(db, projectId, input.subject.type, subjectId)\n const groupIds = input.groupIds === undefined ? undefined : normalizeGroupIds(input.groupIds)\n\n try {\n db.query(\n `\n INSERT INTO auth_access_tokens (\n project_id,\n id,\n name,\n kind,\n subject_type,\n subject_id,\n token_hash,\n group_ids,\n created_by_principal_type,\n created_by_principal_id,\n created_by_session_id,\n created_at,\n expires_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n ).run(\n projectId,\n id,\n name,\n input.kind,\n input.subject.type,\n subjectId,\n tokenHash,\n serializeOptionalStringArray(groupIds),\n input.createdByPrincipal?.type ?? null,\n input.createdByPrincipal?.id ?? null,\n input.createdBySessionId ?? null,\n toIso(input.createdAt),\n toIso(input.expiresAt)\n )\n } catch (error) {\n mapUniqueConstraintError(\n error,\n \"duplicate_access_token\",\n `[Sixb] Access token '${id}' already exists for project '${projectId}'.`\n )\n }\n\n const row = db\n .query(\"SELECT * FROM auth_access_tokens WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as SqliteAuthAccessTokenRow | null\n const token = row ? rowToAccessTokenRecord(row) : null\n if (!token) {\n throw new AuthStorageError(\n \"missing_access_token\",\n `[Sixb] Access token '${id}' not found for project '${projectId}'.`\n )\n }\n return token\n}\n\nexport class SqliteAuthAccessTokenStore implements AuthAccessTokenStore {\n constructor(private readonly db: Database) {}\n\n async create(input: CreateAuthAccessTokenInput): Promise<AccessTokenRecord> {\n return createAuthAccessToken(this.db, input)\n }\n\n async getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<AccessTokenRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM auth_access_tokens WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as SqliteAuthAccessTokenRow | null\n return row ? rowToAccessTokenRecord(row) : null\n }\n\n async list(input: ListAuthAccessTokensInput): Promise<ListAuthAccessTokensResult> {\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n if (input.kind) {\n whereClauses.push(\"kind = ?\")\n args.push(input.kind)\n }\n if (input.subject) {\n whereClauses.push(\"subject_type = ?\", \"subject_id = ?\")\n args.push(input.subject.type, input.subject.id)\n }\n if (!input.includeRevoked) {\n whereClauses.push(\"revoked_at IS NULL\")\n }\n\n const where = `WHERE ${whereClauses.join(\" AND \")}`\n const order = input.order === \"desc\" ? \"DESC\" : \"ASC\"\n const totalRow = this.db\n .query(`SELECT COUNT(*) AS count FROM auth_access_tokens ${where}`)\n .get(...args) as { readonly count: number }\n const queryArgs = [...args]\n const query = appendPagination(\n `\n SELECT *\n FROM auth_access_tokens\n ${where}\n ORDER BY created_at ${order}, id ${order}\n `,\n queryArgs,\n input\n )\n const rows = this.db.query(query).all(...queryArgs) as SqliteAuthAccessTokenRow[]\n\n return {\n accessTokens: rows.map(rowToAccessTokenRecord),\n hasMore:\n input.limit === undefined ? false : (input.offset ?? 0) + input.limit < totalRow.count,\n total: totalRow.count,\n }\n }\n\n async findValidByTokenHash(params: {\n readonly projectId: string\n readonly id: string\n readonly kind: AccessTokenRecord[\"kind\"]\n readonly tokenHash: string\n readonly now: Date\n }): Promise<AccessTokenRecord | null> {\n const row = this.db\n .query(\n `\n SELECT *\n FROM auth_access_tokens\n WHERE project_id = ?\n AND id = ?\n AND kind = ?\n AND token_hash = ?\n AND revoked_at IS NULL\n AND expires_at > ?\n `\n )\n .get(\n params.projectId,\n params.id,\n params.kind,\n params.tokenHash,\n toIso(params.now)\n ) as SqliteAuthAccessTokenRow | null\n\n return row ? rowToAccessTokenRecord(row) : null\n }\n\n async revoke(params: {\n readonly projectId: string\n readonly id: string\n readonly revokedAt: Date\n }): Promise<AccessTokenRecord> {\n const existing = await this.getById(params)\n if (!existing) {\n throw new AuthStorageError(\n \"missing_access_token\",\n `[Sixb] Access token '${params.id}' not found for project '${params.projectId}'.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE auth_access_tokens\n SET revoked_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(toIso(params.revokedAt), params.projectId, params.id)\n\n return { ...existing, revokedAt: new Date(params.revokedAt) }\n }\n\n async touch(params: {\n readonly projectId: string\n readonly id: string\n readonly lastUsedAt: Date\n readonly userAgent?: string\n readonly ipAddress?: string\n }): Promise<AccessTokenRecord> {\n const existing = await this.getById(params)\n if (!existing) {\n throw new AuthStorageError(\n \"missing_access_token\",\n `[Sixb] Access token '${params.id}' not found for project '${params.projectId}'.`\n )\n }\n\n const lastUsedUserAgent = params.userAgent ?? existing.lastUsedUserAgent\n const lastUsedIpAddress = params.ipAddress ?? existing.lastUsedIpAddress\n\n this.db\n .query(\n `\n UPDATE auth_access_tokens\n SET last_used_at = ?,\n last_used_user_agent = ?,\n last_used_ip_address = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(\n toIso(params.lastUsedAt),\n lastUsedUserAgent ?? null,\n lastUsedIpAddress ?? null,\n params.projectId,\n params.id\n )\n\n return {\n ...existing,\n lastUsedAt: new Date(params.lastUsedAt),\n lastUsedUserAgent,\n lastUsedIpAddress,\n }\n }\n}\n\nfunction assertSubjectExists(\n db: Database,\n projectId: string,\n subjectType: CreateAuthAccessTokenInput[\"subject\"][\"type\"],\n subjectId: string\n): void {\n if (subjectType === \"user\") {\n const row = db\n .query(\"SELECT * FROM auth_users WHERE project_id = ? AND id = ?\")\n .get(projectId, subjectId) as SqliteAuthUserRow | null\n if (row) return\n throw new AuthStorageError(\n \"missing_user\",\n `[Sixb] User '${subjectId}' not found for project '${projectId}'.`\n )\n }\n\n const row = db\n .query(\"SELECT * FROM auth_service_accounts WHERE project_id = ? AND id = ?\")\n .get(projectId, subjectId) as SqliteAuthServiceAccountRow | null\n if (row) return\n throw new AuthStorageError(\n \"missing_service_account\",\n `[Sixb] Service account '${subjectId}' not found for project '${projectId}'.`\n )\n}\n\nfunction assertKindMatchesSubject(input: CreateAuthAccessTokenInput): void {\n if (\n (input.kind === \"personal\" && input.subject.type === \"user\") ||\n (input.kind === \"serviceAccount\" && input.subject.type === \"serviceAccount\")\n ) {\n return\n }\n\n throw new AuthStorageError(\n \"invalid_input\",\n `[Sixb] Access token kind '${input.kind}' cannot target subject type '${input.subject.type}'.`\n )\n}\n",
25
28
  "import type { Principal } from \"@sixb/core\"\nimport type {\n AccessTokenRecord,\n DeviceAuthorizationRecord,\n GroupMembershipRecord,\n GroupMembershipSource,\n InvitationRecord,\n InvitationStatus,\n MagicLinkRecord,\n OidcAuthorizationAttemptRecord,\n ServiceAccountGroupMembershipRecord,\n ServiceAccountRecord,\n ServiceAccountStatus,\n SessionRecord,\n UserIdentityRecord,\n UserRecord,\n UserStatus,\n} from \"@sixb/core/storage\"\n\nexport interface SqliteAuthUserRow {\n readonly project_id: string\n readonly id: string\n readonly email: string\n readonly display_name: string | null\n readonly avatar_url: string | null\n readonly status: UserStatus\n readonly created_at: string\n readonly updated_at: string\n}\n\nexport interface SqliteAuthUserIdentityRow {\n readonly project_id: string\n readonly strategy_id: string\n readonly subject: string\n readonly user_id: string\n readonly claims: string | null\n readonly created_at: string\n readonly updated_at: string\n}\n\nexport interface SqliteAuthServiceAccountRow {\n readonly project_id: string\n readonly id: string\n readonly name: string\n readonly description: string | null\n readonly status: ServiceAccountStatus\n readonly created_by_principal_type: Principal[\"type\"] | null\n readonly created_by_principal_id: string | null\n readonly created_by_session_id: string | null\n readonly created_at: string\n readonly updated_at: string\n}\n\nexport interface SqliteAuthServiceAccountGroupMembershipRow {\n readonly project_id: string\n readonly service_account_id: string\n readonly group_id: string\n readonly source: ServiceAccountGroupMembershipRecord[\"source\"]\n readonly created_at: string\n}\n\nexport interface SqliteAuthSessionRow {\n readonly project_id: string\n readonly id: string\n readonly user_id: string\n readonly strategy_id: string\n readonly token_hash: string\n readonly created_at: string\n readonly expires_at: string\n readonly absolute_expires_at: string | null\n readonly revoked_at: string | null\n readonly last_seen_at: string | null\n readonly user_agent: string | null\n readonly ip_address: string | null\n readonly client_name: string | null\n readonly access_expires_at: string | null\n readonly refresh_token_hash: string | null\n readonly previous_refresh_token_hash: string | null\n readonly refreshed_at: string | null\n}\n\nexport interface SqliteAuthAccessTokenRow {\n readonly project_id: string\n readonly id: string\n readonly name: string\n readonly kind: AccessTokenRecord[\"kind\"]\n readonly subject_type: AccessTokenRecord[\"subject\"][\"type\"]\n readonly subject_id: string\n readonly token_hash: string\n readonly group_ids: string | null\n readonly created_by_principal_type: Principal[\"type\"] | null\n readonly created_by_principal_id: string | null\n readonly created_by_session_id: string | null\n readonly created_at: string\n readonly expires_at: string\n readonly revoked_at: string | null\n readonly last_used_at: string | null\n readonly last_used_user_agent: string | null\n readonly last_used_ip_address: string | null\n}\n\nexport interface SqliteAuthInvitationRow {\n readonly project_id: string\n readonly id: string\n readonly email: string\n readonly status: InvitationStatus\n readonly created_by_principal_type: Principal[\"type\"] | null\n readonly created_by_principal_id: string | null\n readonly created_by_session_id: string | null\n readonly created_at: string\n readonly updated_at: string\n readonly expires_at: string\n readonly accepted_at: string | null\n readonly revoked_at: string | null\n}\n\nexport interface SqliteAuthGroupMembershipRow {\n readonly project_id: string\n readonly user_id: string\n readonly group_id: string\n readonly source: GroupMembershipSource\n readonly created_at: string\n}\n\nexport interface SqliteAuthMagicLinkRow {\n readonly project_id: string\n readonly id: string\n readonly strategy_id: string\n readonly email: string\n readonly token_hash: string\n readonly return_to: string | null\n readonly created_at: string\n readonly expires_at: string\n readonly consumed_at: string | null\n readonly revoked_at: string | null\n}\n\nexport interface SqliteAuthOidcAttemptRow {\n readonly project_id: string\n readonly id: string\n readonly strategy_id: string\n readonly state_hash: string\n readonly nonce_hash: string\n readonly code_verifier: string\n readonly return_to: string | null\n readonly created_at: string\n readonly expires_at: string\n readonly consumed_at: string | null\n}\n\nexport interface SqliteAuthDeviceAuthorizationRow {\n readonly project_id: string\n readonly id: string\n readonly device_code_hash: string\n readonly user_code: string\n readonly client_name: string\n readonly status: DeviceAuthorizationRecord[\"status\"]\n readonly approved_user_id: string | null\n readonly approved_session_id: string | null\n readonly created_at: string\n readonly expires_at: string\n readonly approved_at: string | null\n readonly denied_at: string | null\n readonly consumed_at: string | null\n}\n\nexport function rowToUserRecord(row: SqliteAuthUserRow): UserRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n email: row.email,\n displayName: row.display_name ?? undefined,\n avatarUrl: row.avatar_url ?? undefined,\n status: row.status,\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n }\n}\n\nexport function rowToIdentityRecord(row: SqliteAuthUserIdentityRow): UserIdentityRecord {\n return {\n projectId: row.project_id,\n strategyId: row.strategy_id,\n subject: row.subject,\n userId: row.user_id,\n claims: parseOptionalRecord(row.claims),\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n }\n}\n\nexport function rowToServiceAccountRecord(row: SqliteAuthServiceAccountRow): ServiceAccountRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n name: row.name,\n description: row.description ?? undefined,\n status: row.status,\n createdByPrincipal:\n row.created_by_principal_type && row.created_by_principal_id\n ? {\n type: row.created_by_principal_type,\n id: row.created_by_principal_id,\n }\n : undefined,\n createdBySessionId: row.created_by_session_id ?? undefined,\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n }\n}\n\nexport function rowToServiceAccountGroupMembershipRecord(\n row: SqliteAuthServiceAccountGroupMembershipRow\n): ServiceAccountGroupMembershipRecord {\n return {\n projectId: row.project_id,\n serviceAccountId: row.service_account_id,\n groupId: row.group_id,\n source: row.source,\n createdAt: new Date(row.created_at),\n }\n}\n\nexport function rowToSessionRecord(row: SqliteAuthSessionRow): SessionRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n userId: row.user_id,\n strategyId: row.strategy_id,\n tokenHash: row.token_hash,\n createdAt: new Date(row.created_at),\n expiresAt: new Date(row.expires_at),\n absoluteExpiresAt: row.absolute_expires_at ? new Date(row.absolute_expires_at) : undefined,\n revokedAt: row.revoked_at ? new Date(row.revoked_at) : undefined,\n lastSeenAt: row.last_seen_at ? new Date(row.last_seen_at) : undefined,\n userAgent: row.user_agent ?? undefined,\n ipAddress: row.ip_address ?? undefined,\n bearer:\n row.refresh_token_hash !== null && row.client_name !== null && row.access_expires_at !== null\n ? {\n clientName: row.client_name,\n accessExpiresAt: new Date(row.access_expires_at),\n refreshTokenHash: row.refresh_token_hash,\n previousRefreshTokenHash: row.previous_refresh_token_hash ?? undefined,\n refreshedAt: row.refreshed_at ? new Date(row.refreshed_at) : undefined,\n }\n : undefined,\n }\n}\n\nexport function rowToAccessTokenRecord(row: SqliteAuthAccessTokenRow): AccessTokenRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n name: row.name,\n kind: row.kind,\n subject: { type: row.subject_type, id: row.subject_id },\n tokenHash: row.token_hash,\n groupIds: parseOptionalStringArray(row.group_ids),\n createdByPrincipal:\n row.created_by_principal_type && row.created_by_principal_id\n ? {\n type: row.created_by_principal_type,\n id: row.created_by_principal_id,\n }\n : undefined,\n createdBySessionId: row.created_by_session_id ?? undefined,\n createdAt: new Date(row.created_at),\n expiresAt: new Date(row.expires_at),\n revokedAt: row.revoked_at ? new Date(row.revoked_at) : undefined,\n lastUsedAt: row.last_used_at ? new Date(row.last_used_at) : undefined,\n lastUsedUserAgent: row.last_used_user_agent ?? undefined,\n lastUsedIpAddress: row.last_used_ip_address ?? undefined,\n }\n}\n\nexport function rowToInvitationRecord(\n row: SqliteAuthInvitationRow,\n groupIds: readonly string[]\n): InvitationRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n email: row.email,\n groupIds,\n status: row.status,\n createdByPrincipal:\n row.created_by_principal_type && row.created_by_principal_id\n ? {\n type: row.created_by_principal_type,\n id: row.created_by_principal_id,\n }\n : undefined,\n createdBySessionId: row.created_by_session_id ?? undefined,\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n expiresAt: new Date(row.expires_at),\n acceptedAt: row.accepted_at ? new Date(row.accepted_at) : undefined,\n revokedAt: row.revoked_at ? new Date(row.revoked_at) : undefined,\n }\n}\n\nexport function rowToGroupMembershipRecord(\n row: SqliteAuthGroupMembershipRow\n): GroupMembershipRecord {\n return {\n projectId: row.project_id,\n userId: row.user_id,\n groupId: row.group_id,\n source: row.source,\n createdAt: new Date(row.created_at),\n }\n}\n\nexport function rowToMagicLinkRecord(row: SqliteAuthMagicLinkRow): MagicLinkRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n strategyId: row.strategy_id,\n email: row.email,\n tokenHash: row.token_hash,\n returnTo: row.return_to ?? undefined,\n createdAt: new Date(row.created_at),\n expiresAt: new Date(row.expires_at),\n consumedAt: row.consumed_at ? new Date(row.consumed_at) : undefined,\n revokedAt: row.revoked_at ? new Date(row.revoked_at) : undefined,\n }\n}\n\nexport function rowToOidcAuthorizationAttemptRecord(\n row: SqliteAuthOidcAttemptRow\n): OidcAuthorizationAttemptRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n strategyId: row.strategy_id,\n stateHash: row.state_hash,\n nonceHash: row.nonce_hash,\n codeVerifier: row.code_verifier,\n returnTo: row.return_to ?? undefined,\n createdAt: new Date(row.created_at),\n expiresAt: new Date(row.expires_at),\n consumedAt: row.consumed_at ? new Date(row.consumed_at) : undefined,\n }\n}\n\nexport function rowToDeviceAuthorizationRecord(\n row: SqliteAuthDeviceAuthorizationRow\n): DeviceAuthorizationRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n deviceCodeHash: row.device_code_hash,\n userCode: row.user_code,\n clientName: row.client_name,\n status: row.status,\n approvedUserId: row.approved_user_id ?? undefined,\n approvedSessionId: row.approved_session_id ?? undefined,\n createdAt: new Date(row.created_at),\n expiresAt: new Date(row.expires_at),\n approvedAt: row.approved_at ? new Date(row.approved_at) : undefined,\n deniedAt: row.denied_at ? new Date(row.denied_at) : undefined,\n consumedAt: row.consumed_at ? new Date(row.consumed_at) : undefined,\n }\n}\n\nexport function serializeOptionalRecord(\n value: Readonly<Record<string, unknown>> | undefined\n): string | null {\n return value ? JSON.stringify(value) : null\n}\n\nexport function serializeOptionalStringArray(value: readonly string[] | undefined): string | null {\n return value === undefined ? null : JSON.stringify(value)\n}\n\nfunction parseOptionalRecord(value: string | null): Readonly<Record<string, unknown>> | undefined {\n return value ? (JSON.parse(value) as Readonly<Record<string, unknown>>) : undefined\n}\n\nfunction parseOptionalStringArray(value: string | null): readonly string[] | undefined {\n return value === null ? undefined : (JSON.parse(value) as readonly string[])\n}\n",
26
29
  "import type { Database } from \"bun:sqlite\"\nimport type {\n CompleteAuthSessionInput,\n CreateAuthSessionInput,\n GroupMembershipRecord,\n InvitationRecord,\n MagicLinkRecord,\n OidcAuthorizationAttemptRecord,\n UpsertAuthGroupMembershipInput,\n} from \"@sixb/core/storage\"\nimport { AuthStorageError } from \"@sixb/core/storage\"\nimport { isUniqueConstraintError } from \"../storage-errors\"\nimport type {\n SqliteAuthGroupMembershipRow,\n SqliteAuthInvitationRow,\n SqliteAuthMagicLinkRow,\n SqliteAuthOidcAttemptRow,\n SqliteAuthSessionRow,\n SqliteAuthUserIdentityRow,\n SqliteAuthUserRow,\n} from \"./rows\"\nimport {\n rowToGroupMembershipRecord,\n rowToInvitationRecord,\n rowToMagicLinkRecord,\n rowToOidcAuthorizationAttemptRecord,\n rowToSessionRecord,\n} from \"./rows\"\n\nexport type SqliteValue = string | number | null\n\nexport function assertNonEmpty(value: string, label: string): string {\n const normalized = value.trim()\n if (!normalized) {\n throw new AuthStorageError(\"invalid_input\", `[Sixb] ${label} must be a non-empty string.`)\n }\n return normalized\n}\n\nexport function normalizeEmail(email: string): string {\n return assertNonEmpty(email, \"Email\").toLowerCase()\n}\n\nexport function normalizeGroupIds(groupIds: readonly string[] | undefined): readonly string[] {\n return [...new Set((groupIds ?? []).map((groupId) => assertNonEmpty(groupId, \"Group id\")))]\n}\n\nexport function dateOrNow(value: Date | undefined): Date {\n return value ? new Date(value) : new Date()\n}\n\nexport function toIso(value: Date): string {\n return value.toISOString()\n}\n\nexport function hasEmptyFilter(values: readonly unknown[] | undefined): boolean {\n return values !== undefined && values.length === 0\n}\n\nexport function appendPagination(\n query: string,\n args: SqliteValue[],\n input: { readonly limit?: number; readonly offset?: number }\n): string {\n const offset = input.offset ?? 0\n\n if (input.limit !== undefined) {\n args.push(input.limit, offset)\n return `${query} LIMIT ? OFFSET ?`\n }\n\n if (offset > 0) {\n args.push(offset)\n return `${query} LIMIT -1 OFFSET ?`\n }\n\n return query\n}\n\nexport function getUserRowById(\n db: Database,\n params: { readonly projectId: string; readonly id: string }\n): SqliteAuthUserRow | null {\n return db\n .query(\"SELECT * FROM auth_users WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as SqliteAuthUserRow | null\n}\n\nexport function getUserRowByEmail(\n db: Database,\n params: { readonly projectId: string; readonly email: string }\n): SqliteAuthUserRow | null {\n return db\n .query(\"SELECT * FROM auth_users WHERE project_id = ? AND email = ?\")\n .get(params.projectId, normalizeEmail(params.email)) as SqliteAuthUserRow | null\n}\n\nexport function getIdentityRowBySubject(\n db: Database,\n params: {\n readonly projectId: string\n readonly strategyId: string\n readonly subject: string\n }\n): SqliteAuthUserIdentityRow | null {\n return db\n .query(\n `\n SELECT *\n FROM auth_user_identities\n WHERE project_id = ?\n AND strategy_id = ?\n AND subject = ?\n `\n )\n .get(params.projectId, params.strategyId, params.subject) as SqliteAuthUserIdentityRow | null\n}\n\nexport function getSessionRowById(\n db: Database,\n params: { readonly projectId: string; readonly id: string }\n): SqliteAuthSessionRow | null {\n return db\n .query(\"SELECT * FROM auth_sessions WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as SqliteAuthSessionRow | null\n}\n\nexport function getSessionById(\n db: Database,\n params: { readonly projectId: string; readonly id: string }\n): ReturnType<typeof rowToSessionRecord> | null {\n const row = getSessionRowById(db, params)\n return row ? rowToSessionRecord(row) : null\n}\n\nexport function requireSessionById(\n db: Database,\n params: { readonly projectId: string; readonly id: string }\n): ReturnType<typeof rowToSessionRecord> {\n const session = getSessionById(db, params)\n if (!session) {\n throw new AuthStorageError(\n \"missing_session\",\n `[Sixb] Session '${params.id}' not found for project '${params.projectId}'.`\n )\n }\n return session\n}\n\nexport function getInvitationGroupIds(\n db: Database,\n params: { readonly projectId: string; readonly invitationId: string }\n): readonly string[] {\n const rows = db\n .query(\n `\n SELECT group_id\n FROM auth_invitation_groups\n WHERE project_id = ?\n AND invitation_id = ?\n ORDER BY position ASC, group_id ASC\n `\n )\n .all(params.projectId, params.invitationId) as Array<{ readonly group_id: string }>\n\n return rows.map((row) => row.group_id)\n}\n\nexport function getInvitationById(\n db: Database,\n params: { readonly projectId: string; readonly id: string }\n): InvitationRecord | null {\n const row = db\n .query(\"SELECT * FROM auth_invitations WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as SqliteAuthInvitationRow | null\n\n return row ? invitationRowToRecord(db, row) : null\n}\n\nexport function requireInvitationById(\n db: Database,\n params: { readonly projectId: string; readonly id: string }\n): InvitationRecord {\n const invitation = getInvitationById(db, params)\n if (!invitation) {\n throw new AuthStorageError(\n \"missing_invitation\",\n `[Sixb] Invitation '${params.id}' not found for project '${params.projectId}'.`\n )\n }\n return invitation\n}\n\nexport function getActiveInvitationByEmail(\n db: Database,\n params: { readonly projectId: string; readonly email: string; readonly now: Date }\n): InvitationRecord | null {\n const row = db\n .query(\n `\n SELECT *\n FROM auth_invitations\n WHERE project_id = ?\n AND email = ?\n AND status = 'pending'\n AND expires_at > ?\n ORDER BY created_at DESC, id DESC\n LIMIT 1\n `\n )\n .get(\n params.projectId,\n normalizeEmail(params.email),\n toIso(params.now)\n ) as SqliteAuthInvitationRow | null\n\n return row ? invitationRowToRecord(db, row) : null\n}\n\nexport function replaceInvitationGroups(\n db: Database,\n params: {\n readonly projectId: string\n readonly invitationId: string\n readonly groupIds: readonly string[]\n }\n): void {\n db.query(\"DELETE FROM auth_invitation_groups WHERE project_id = ? AND invitation_id = ?\").run(\n params.projectId,\n params.invitationId\n )\n\n for (const [index, groupId] of params.groupIds.entries()) {\n db.query(\n `\n INSERT INTO auth_invitation_groups (\n project_id,\n invitation_id,\n group_id,\n position\n ) VALUES (?, ?, ?, ?)\n `\n ).run(params.projectId, params.invitationId, groupId, index)\n }\n}\n\nexport function getMagicLinkRowById(\n db: Database,\n params: { readonly projectId: string; readonly id: string }\n): SqliteAuthMagicLinkRow | null {\n return db\n .query(\"SELECT * FROM auth_magic_links WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as SqliteAuthMagicLinkRow | null\n}\n\nexport function getMagicLinkById(\n db: Database,\n params: { readonly projectId: string; readonly id: string }\n): MagicLinkRecord | null {\n const row = getMagicLinkRowById(db, params)\n return row ? rowToMagicLinkRecord(row) : null\n}\n\nexport function consumeMagicLink(\n db: Database,\n params: {\n readonly projectId: string\n readonly id: string\n readonly tokenHash: string\n readonly consumedAt: Date\n }\n): MagicLinkRecord {\n const projectId = assertNonEmpty(params.projectId, \"Project id\")\n const id = assertNonEmpty(params.id, \"Magic link id\")\n const tokenHash = assertNonEmpty(params.tokenHash, \"Magic link token hash\")\n const row = getMagicLinkRowById(db, { projectId, id })\n\n if (!row) {\n throw new AuthStorageError(\n \"missing_magic_link\",\n `[Sixb] Magic link '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (row.token_hash !== tokenHash || row.consumed_at || row.revoked_at) {\n throw new AuthStorageError(\n \"invalid_magic_link\",\n `[Sixb] Magic link '${id}' is not valid for project '${projectId}'.`\n )\n }\n\n if (new Date(row.expires_at) <= params.consumedAt) {\n throw new AuthStorageError(\n \"expired_magic_link\",\n `[Sixb] Magic link '${id}' is expired for project '${projectId}'.`\n )\n }\n\n db.query(\n `\n UPDATE auth_magic_links\n SET consumed_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n ).run(toIso(params.consumedAt), projectId, id)\n\n return rowToMagicLinkRecord({\n ...row,\n consumed_at: toIso(params.consumedAt),\n })\n}\n\nexport function getOidcAttemptRowById(\n db: Database,\n params: { readonly projectId: string; readonly id: string }\n): SqliteAuthOidcAttemptRow | null {\n return db\n .query(\"SELECT * FROM auth_oidc_authorization_attempts WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as SqliteAuthOidcAttemptRow | null\n}\n\nexport function getOidcAttemptById(\n db: Database,\n params: { readonly projectId: string; readonly id: string }\n): OidcAuthorizationAttemptRecord | null {\n const row = getOidcAttemptRowById(db, params)\n return row ? rowToOidcAuthorizationAttemptRecord(row) : null\n}\n\nexport function consumeOidcAttempt(\n db: Database,\n params: {\n readonly projectId: string\n readonly id: string\n readonly stateHash: string\n readonly consumedAt: Date\n }\n): OidcAuthorizationAttemptRecord {\n const projectId = assertNonEmpty(params.projectId, \"Project id\")\n const id = assertNonEmpty(params.id, \"OIDC authorization attempt id\")\n const stateHash = assertNonEmpty(params.stateHash, \"OIDC state hash\")\n const row = getOidcAttemptRowById(db, { projectId, id })\n\n if (!row) {\n throw new AuthStorageError(\n \"missing_oidc_attempt\",\n `[Sixb] OIDC authorization attempt '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (row.state_hash !== stateHash || row.consumed_at) {\n throw new AuthStorageError(\n \"invalid_oidc_attempt\",\n `[Sixb] OIDC authorization attempt '${id}' is not valid for project '${projectId}'.`\n )\n }\n\n if (new Date(row.expires_at) <= params.consumedAt) {\n throw new AuthStorageError(\n \"expired_oidc_attempt\",\n `[Sixb] OIDC authorization attempt '${id}' is expired for project '${projectId}'.`\n )\n }\n\n db.query(\n `\n UPDATE auth_oidc_authorization_attempts\n SET consumed_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n ).run(toIso(params.consumedAt), projectId, id)\n\n return rowToOidcAuthorizationAttemptRecord({\n ...row,\n consumed_at: toIso(params.consumedAt),\n })\n}\n\nexport function validateCompleteSessionInput(\n db: Database,\n projectId: string,\n session: CompleteAuthSessionInput\n): void {\n const sessionId = assertNonEmpty(session.id, \"Session id\")\n assertNonEmpty(session.tokenHash, \"Session token hash\")\n assertSessionIdAvailable(db, projectId, sessionId)\n}\n\nexport function assertSessionIdAvailable(db: Database, projectId: string, sessionId: string): void {\n if (getSessionRowById(db, { projectId, id: sessionId })) {\n throw new AuthStorageError(\n \"duplicate_session\",\n `[Sixb] Session '${sessionId}' already exists for project '${projectId}'.`\n )\n }\n}\n\nexport function createSession(\n db: Database,\n input: CreateAuthSessionInput\n): ReturnType<typeof rowToSessionRecord> {\n const id = assertNonEmpty(input.id, \"Session id\")\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const userId = assertNonEmpty(input.userId, \"User id\")\n const strategyId = assertNonEmpty(input.strategyId, \"Strategy id\")\n const tokenHash = assertNonEmpty(input.tokenHash, \"Session token hash\")\n\n assertSessionIdAvailable(db, projectId, id)\n\n db.query(\n `\n INSERT INTO auth_sessions (\n project_id,\n id,\n user_id,\n strategy_id,\n token_hash,\n created_at,\n expires_at,\n absolute_expires_at,\n user_agent,\n ip_address,\n client_name,\n access_expires_at,\n refresh_token_hash\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n ).run(\n projectId,\n id,\n userId,\n strategyId,\n tokenHash,\n toIso(input.createdAt),\n toIso(input.expiresAt),\n input.absoluteExpiresAt ? toIso(input.absoluteExpiresAt) : null,\n input.userAgent ?? null,\n input.ipAddress ?? null,\n input.bearer ? assertNonEmpty(input.bearer.clientName, \"Session client name\") : null,\n input.bearer ? toIso(input.bearer.accessExpiresAt) : null,\n input.bearer ? assertNonEmpty(input.bearer.refreshTokenHash, \"Refresh token hash\") : null\n )\n\n const session = getSessionById(db, { projectId, id })\n if (!session) {\n throw new AuthStorageError(\n \"missing_session\",\n `[Sixb] Failed to load session '${id}' for project '${projectId}'.`\n )\n }\n return session\n}\n\nexport function revokeActiveSessionsForUser(\n db: Database,\n params: {\n readonly projectId: string\n readonly userId: string\n readonly revokedAt: Date\n }\n): readonly ReturnType<typeof rowToSessionRecord>[] {\n const revokedAt = toIso(params.revokedAt)\n const rows = db\n .query(\n `\n SELECT *\n FROM auth_sessions\n WHERE project_id = ?\n AND user_id = ?\n AND revoked_at IS NULL\n AND expires_at > ?\n AND (absolute_expires_at IS NULL OR absolute_expires_at > ?)\n ORDER BY created_at ASC, id ASC\n `\n )\n .all(params.projectId, params.userId, revokedAt, revokedAt) as SqliteAuthSessionRow[]\n\n db.query(\n `\n UPDATE auth_sessions\n SET revoked_at = ?\n WHERE project_id = ?\n AND user_id = ?\n AND revoked_at IS NULL\n AND expires_at > ?\n AND (absolute_expires_at IS NULL OR absolute_expires_at > ?)\n `\n ).run(revokedAt, params.projectId, params.userId, revokedAt, revokedAt)\n\n return rows.map((row) =>\n rowToSessionRecord({\n ...row,\n revoked_at: revokedAt,\n })\n )\n}\n\nexport function upsertGroupMembership(\n db: Database,\n input: UpsertAuthGroupMembershipInput\n): GroupMembershipRecord {\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const userId = assertNonEmpty(input.userId, \"User id\")\n const groupId = assertNonEmpty(input.groupId, \"Group id\")\n if (!getUserRowById(db, { projectId, id: userId })) {\n throw new AuthStorageError(\n \"missing_user\",\n `[Sixb] User '${userId}' not found for project '${projectId}'.`\n )\n }\n\n const existing = getGroupMembership(db, { projectId, userId, groupId })\n\n if (existing) {\n return existing\n }\n\n const createdAt = dateOrNow(input.createdAt)\n db.query(\n `\n INSERT INTO auth_group_memberships (\n project_id,\n user_id,\n group_id,\n source,\n created_at\n ) VALUES (?, ?, ?, ?, ?)\n `\n ).run(projectId, userId, groupId, input.source, toIso(createdAt))\n\n return {\n projectId,\n userId,\n groupId,\n source: input.source,\n createdAt,\n }\n}\n\nexport function removeGroupMembership(\n db: Database,\n params: { readonly projectId: string; readonly userId: string; readonly groupId: string }\n): GroupMembershipRecord | null {\n const projectId = assertNonEmpty(params.projectId, \"Project id\")\n const userId = assertNonEmpty(params.userId, \"User id\")\n const groupId = assertNonEmpty(params.groupId, \"Group id\")\n\n const existing = getGroupMembership(db, { projectId, userId, groupId })\n if (!existing) {\n return null\n }\n\n db.query(\n `\n DELETE FROM auth_group_memberships\n WHERE project_id = ?\n AND user_id = ?\n AND group_id = ?\n `\n ).run(projectId, userId, groupId)\n\n return existing\n}\n\nexport function getGroupMembership(\n db: Database,\n params: { readonly projectId: string; readonly userId: string; readonly groupId: string }\n): GroupMembershipRecord | null {\n const row = db\n .query(\n `\n SELECT *\n FROM auth_group_memberships\n WHERE project_id = ?\n AND user_id = ?\n AND group_id = ?\n `\n )\n .get(params.projectId, params.userId, params.groupId) as SqliteAuthGroupMembershipRow | null\n\n return row ? rowToGroupMembershipRecord(row) : null\n}\n\nexport function listMembershipsForUser(\n db: Database,\n params: { readonly projectId: string; readonly userId: string }\n): readonly GroupMembershipRecord[] {\n const rows = db\n .query(\n `\n SELECT *\n FROM auth_group_memberships\n WHERE project_id = ?\n AND user_id = ?\n ORDER BY group_id ASC\n `\n )\n .all(params.projectId, params.userId) as SqliteAuthGroupMembershipRow[]\n\n return rows.map(rowToGroupMembershipRecord)\n}\n\nexport function revokeActiveMagicLinksForEmail(\n db: Database,\n params: { readonly projectId: string; readonly email: string; readonly revokedAt: Date }\n): readonly MagicLinkRecord[] {\n const email = normalizeEmail(params.email)\n const revokedAt = toIso(params.revokedAt)\n const rows = db\n .query(\n `\n SELECT *\n FROM auth_magic_links\n WHERE project_id = ?\n AND email = ?\n AND consumed_at IS NULL\n AND revoked_at IS NULL\n AND expires_at > ?\n ORDER BY created_at ASC, id ASC\n `\n )\n .all(params.projectId, email, revokedAt) as SqliteAuthMagicLinkRow[]\n\n db.query(\n `\n UPDATE auth_magic_links\n SET revoked_at = ?\n WHERE project_id = ?\n AND email = ?\n AND consumed_at IS NULL\n AND revoked_at IS NULL\n AND expires_at > ?\n `\n ).run(revokedAt, params.projectId, email, revokedAt)\n\n return rows.map((row) =>\n rowToMagicLinkRecord({\n ...row,\n revoked_at: revokedAt,\n })\n )\n}\n\nexport function mapUniqueConstraintError(\n error: unknown,\n code:\n | \"duplicate_access_token\"\n | \"duplicate_device_authorization\"\n | \"duplicate_identity\"\n | \"duplicate_invitation\"\n | \"duplicate_magic_link\"\n | \"duplicate_oidc_attempt\"\n | \"duplicate_service_account\"\n | \"duplicate_session\"\n | \"duplicate_user\",\n message: string\n): never {\n if (isUniqueConstraintError(error)) {\n throw new AuthStorageError(code, message)\n }\n\n throw error\n}\n\nfunction invitationRowToRecord(db: Database, row: SqliteAuthInvitationRow): InvitationRecord {\n return rowToInvitationRecord(\n row,\n getInvitationGroupIds(db, {\n projectId: row.project_id,\n invitationId: row.id,\n })\n )\n}\n",
@@ -33,33 +36,36 @@
33
36
  "import type { Database } from \"bun:sqlite\"\nimport type {\n AuthServiceAccountGroupMembershipStore,\n ReconcileAuthServiceAccountGroupMembershipsInput,\n ServiceAccountGroupMembershipRecord,\n UpsertAuthServiceAccountGroupMembershipInput,\n} from \"@sixb/core/storage\"\nimport { AuthStorageError } from \"@sixb/core/storage\"\nimport type {\n SqliteAuthServiceAccountGroupMembershipRow,\n SqliteAuthServiceAccountRow,\n} from \"./rows\"\nimport { rowToServiceAccountGroupMembershipRecord } from \"./rows\"\nimport { assertNonEmpty, dateOrNow, normalizeGroupIds, toIso } from \"./shared\"\n\nexport class SqliteAuthServiceAccountGroupMembershipStore\n implements AuthServiceAccountGroupMembershipStore\n{\n constructor(private readonly db: Database) {}\n\n async upsert(\n input: UpsertAuthServiceAccountGroupMembershipInput\n ): Promise<ServiceAccountGroupMembershipRecord> {\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const serviceAccountId = assertNonEmpty(input.serviceAccountId, \"Service account id\")\n const groupId = assertNonEmpty(input.groupId, \"Group id\")\n const serviceAccount = this.db\n .query(\"SELECT * FROM auth_service_accounts WHERE project_id = ? AND id = ?\")\n .get(projectId, serviceAccountId) as SqliteAuthServiceAccountRow | null\n if (!serviceAccount) {\n throw new AuthStorageError(\n \"missing_service_account\",\n `[Sixb] Service account '${serviceAccountId}' not found for project '${projectId}'.`\n )\n }\n\n this.db\n .query(\n `\n INSERT OR IGNORE INTO auth_service_account_group_memberships (\n project_id,\n service_account_id,\n group_id,\n source,\n created_at\n ) VALUES (?, ?, ?, ?, ?)\n `\n )\n .run(projectId, serviceAccountId, groupId, input.source, toIso(dateOrNow(input.createdAt)))\n\n const row = this.db\n .query(\n `\n SELECT *\n FROM auth_service_account_group_memberships\n WHERE project_id = ?\n AND service_account_id = ?\n AND group_id = ?\n `\n )\n .get(projectId, serviceAccountId, groupId) as SqliteAuthServiceAccountGroupMembershipRow\n return rowToServiceAccountGroupMembershipRecord(row)\n }\n\n async reconcileForServiceAccount(\n input: ReconcileAuthServiceAccountGroupMembershipsInput\n ): Promise<readonly ServiceAccountGroupMembershipRecord[]> {\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const serviceAccountId = assertNonEmpty(input.serviceAccountId, \"Service account id\")\n const serviceAccount = this.db\n .query(\"SELECT * FROM auth_service_accounts WHERE project_id = ? AND id = ?\")\n .get(projectId, serviceAccountId) as SqliteAuthServiceAccountRow | null\n if (!serviceAccount) {\n throw new AuthStorageError(\n \"missing_service_account\",\n `[Sixb] Service account '${serviceAccountId}' not found for project '${projectId}'.`\n )\n }\n\n const groupIds = normalizeGroupIds(input.groupIds)\n const desired = new Set(groupIds)\n const existing = await this.listForServiceAccount({ projectId, serviceAccountId })\n for (const membership of existing) {\n if (membership.source === input.source && !desired.has(membership.groupId)) {\n this.db\n .query(\n `\n DELETE FROM auth_service_account_group_memberships\n WHERE project_id = ?\n AND service_account_id = ?\n AND group_id = ?\n AND source = ?\n `\n )\n .run(projectId, serviceAccountId, membership.groupId, input.source)\n }\n }\n\n const updatedAt = toIso(dateOrNow(input.updatedAt))\n for (const groupId of groupIds) {\n this.db\n .query(\n `\n INSERT INTO auth_service_account_group_memberships (\n project_id,\n service_account_id,\n group_id,\n source,\n created_at\n ) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(project_id, service_account_id, group_id) DO UPDATE\n SET source = excluded.source\n `\n )\n .run(projectId, serviceAccountId, groupId, input.source, updatedAt)\n }\n\n return this.listForServiceAccount({ projectId, serviceAccountId })\n }\n\n async listForServiceAccount(params: {\n readonly projectId: string\n readonly serviceAccountId: string\n }): Promise<readonly ServiceAccountGroupMembershipRecord[]> {\n const rows = this.db\n .query(\n `\n SELECT *\n FROM auth_service_account_group_memberships\n WHERE project_id = ?\n AND service_account_id = ?\n ORDER BY group_id ASC\n `\n )\n .all(\n params.projectId,\n params.serviceAccountId\n ) as SqliteAuthServiceAccountGroupMembershipRow[]\n\n return rows.map(rowToServiceAccountGroupMembershipRecord)\n }\n\n async listForGroup(params: {\n readonly projectId: string\n readonly groupId: string\n }): Promise<readonly ServiceAccountGroupMembershipRecord[]> {\n const rows = this.db\n .query(\n `\n SELECT *\n FROM auth_service_account_group_memberships\n WHERE project_id = ?\n AND group_id = ?\n ORDER BY service_account_id ASC\n `\n )\n .all(params.projectId, params.groupId) as SqliteAuthServiceAccountGroupMembershipRow[]\n\n return rows.map(rowToServiceAccountGroupMembershipRecord)\n }\n}\n",
34
37
  "import type { Database } from \"bun:sqlite\"\nimport type {\n AuthServiceAccountStore,\n CreateAuthServiceAccountInput,\n ListAuthServiceAccountsInput,\n ListAuthServiceAccountsResult,\n ServiceAccountRecord,\n UpdateAuthServiceAccountInput,\n} from \"@sixb/core/storage\"\nimport { AuthStorageError } from \"@sixb/core/storage\"\nimport type { SqliteAuthServiceAccountRow } from \"./rows\"\nimport { rowToServiceAccountRecord } from \"./rows\"\nimport {\n appendPagination,\n assertNonEmpty,\n dateOrNow,\n hasEmptyFilter,\n mapUniqueConstraintError,\n type SqliteValue,\n toIso,\n} from \"./shared\"\n\nexport class SqliteAuthServiceAccountStore implements AuthServiceAccountStore {\n constructor(private readonly db: Database) {}\n\n async create(input: CreateAuthServiceAccountInput): Promise<ServiceAccountRecord> {\n const id = assertNonEmpty(input.id, \"Service account id\")\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const name = assertNonEmpty(input.name, \"Service account name\")\n const createdAt = dateOrNow(input.createdAt)\n const updatedAt = input.updatedAt ? new Date(input.updatedAt) : createdAt\n\n try {\n this.db\n .query(\n `\n INSERT INTO auth_service_accounts (\n project_id,\n id,\n name,\n description,\n status,\n created_by_principal_type,\n created_by_principal_id,\n created_by_session_id,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n projectId,\n id,\n name,\n input.description ?? null,\n input.status ?? \"active\",\n input.createdByPrincipal?.type ?? null,\n input.createdByPrincipal?.id ?? null,\n input.createdBySessionId ?? null,\n toIso(createdAt),\n toIso(updatedAt)\n )\n } catch (error) {\n mapUniqueConstraintError(\n error,\n \"duplicate_service_account\",\n `[Sixb] Service account '${id}' already exists for project '${projectId}'.`\n )\n }\n\n return {\n id,\n projectId,\n name,\n description: input.description,\n status: input.status ?? \"active\",\n createdByPrincipal: input.createdByPrincipal,\n createdBySessionId: input.createdBySessionId,\n createdAt,\n updatedAt,\n }\n }\n\n async getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<ServiceAccountRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM auth_service_accounts WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as SqliteAuthServiceAccountRow | null\n return row ? rowToServiceAccountRecord(row) : null\n }\n\n async update(input: UpdateAuthServiceAccountInput): Promise<ServiceAccountRecord> {\n const id = assertNonEmpty(input.id, \"Service account id\")\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const updatedAt = dateOrNow(input.updatedAt)\n const name =\n input.name === undefined ? null : assertNonEmpty(input.name, \"Service account name\")\n this.db\n .query(\n `\n UPDATE auth_service_accounts\n SET name = COALESCE(?, name),\n description = COALESCE(?, description),\n status = COALESCE(?, status),\n updated_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(name, input.description ?? null, input.status ?? null, toIso(updatedAt), projectId, id)\n\n const updated = await this.getById({ projectId, id })\n if (!updated) {\n throw new AuthStorageError(\n \"missing_service_account\",\n `[Sixb] Service account '${id}' not found for project '${projectId}'.`\n )\n }\n return updated\n }\n\n async list(input: ListAuthServiceAccountsInput): Promise<ListAuthServiceAccountsResult> {\n if (hasEmptyFilter(input.statuses)) {\n return { serviceAccounts: [], hasMore: false, total: 0 }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n if (input.statuses) {\n whereClauses.push(`status IN (${input.statuses.map(() => \"?\").join(\", \")})`)\n args.push(...input.statuses)\n }\n\n const where = `WHERE ${whereClauses.join(\" AND \")}`\n const order = input.order === \"desc\" ? \"DESC\" : \"ASC\"\n const totalRow = this.db\n .query(`SELECT COUNT(*) AS count FROM auth_service_accounts ${where}`)\n .get(...args) as { readonly count: number }\n const queryArgs = [...args]\n const query = appendPagination(\n `\n SELECT *\n FROM auth_service_accounts\n ${where}\n ORDER BY created_at ${order}, id ${order}\n `,\n queryArgs,\n input\n )\n const rows = this.db.query(query).all(...queryArgs) as SqliteAuthServiceAccountRow[]\n\n return {\n serviceAccounts: rows.map(rowToServiceAccountRecord),\n hasMore:\n input.limit === undefined ? false : (input.offset ?? 0) + input.limit < totalRow.count,\n total: totalRow.count,\n }\n }\n}\n",
35
38
  "import type { Database } from \"bun:sqlite\"\nimport type {\n AuthSessionStore,\n CreateAuthSessionInput,\n ListAuthSessionsInput,\n ListAuthSessionsResult,\n RotateSessionRefreshTokenResult,\n SessionRecord,\n} from \"@sixb/core/storage\"\nimport { AuthStorageError } from \"@sixb/core/storage\"\nimport { runImmediateTransaction } from \"../transactions\"\nimport type { SqliteAuthSessionRow } from \"./rows\"\nimport { rowToSessionRecord } from \"./rows\"\nimport {\n createSession,\n getSessionById,\n getSessionRowById,\n requireSessionById,\n revokeActiveSessionsForUser,\n toIso,\n} from \"./shared\"\n\nexport class SqliteAuthSessionStore implements AuthSessionStore {\n constructor(private readonly db: Database) {}\n\n async create(input: CreateAuthSessionInput): Promise<SessionRecord> {\n return runImmediateTransaction(this.db, () => createSession(this.db, input))\n }\n\n async getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<SessionRecord | null> {\n return getSessionById(this.db, params)\n }\n\n async listActiveByUserId(params: {\n readonly projectId: string\n readonly userId: string\n readonly now: Date\n }): Promise<readonly SessionRecord[]> {\n const rows = this.db\n .query(\n `\n SELECT *\n FROM auth_sessions\n WHERE project_id = ?\n AND user_id = ?\n AND revoked_at IS NULL\n AND expires_at > ?\n AND (absolute_expires_at IS NULL OR absolute_expires_at > ?)\n ORDER BY COALESCE(last_seen_at, created_at) DESC, created_at DESC, id DESC\n `\n )\n .all(\n params.projectId,\n params.userId,\n toIso(params.now),\n toIso(params.now)\n ) as SqliteAuthSessionRow[]\n\n return rows.map(rowToSessionRecord)\n }\n\n async listByUserId(params: ListAuthSessionsInput): Promise<ListAuthSessionsResult> {\n const rows = this.db\n .query(\n `\n SELECT *\n FROM auth_sessions\n WHERE project_id = ? AND user_id = ? AND created_at <= ?\n ORDER BY created_at DESC, id DESC\n LIMIT ? OFFSET ?\n `\n )\n .all(\n params.projectId,\n params.userId,\n params.before ? toIso(params.before.createdAt) : \"9999-12-31T23:59:59.999Z\",\n params.limit + 1,\n params.before?.skip ?? 0\n ) as SqliteAuthSessionRow[]\n\n return {\n sessions: rows.slice(0, params.limit).map(rowToSessionRecord),\n hasMore: rows.length > params.limit,\n }\n }\n\n async findValidByTokenHash(params: {\n readonly projectId: string\n readonly id: string\n readonly tokenHash: string\n readonly now: Date\n }): Promise<SessionRecord | null> {\n const row = getSessionRowById(this.db, params)\n\n if (\n !row ||\n row.refresh_token_hash !== null ||\n row.token_hash !== params.tokenHash ||\n !isLiveSessionRow(row, params.now)\n ) {\n return null\n }\n\n return rowToSessionRecord(row)\n }\n\n async findValidByAccessTokenHash(params: {\n readonly projectId: string\n readonly id: string\n readonly tokenHash: string\n readonly now: Date\n }): Promise<SessionRecord | null> {\n const row = getSessionRowById(this.db, params)\n if (\n !row ||\n row.access_expires_at === null ||\n row.token_hash !== params.tokenHash ||\n new Date(row.access_expires_at) <= params.now ||\n !isLiveSessionRow(row, params.now)\n ) {\n return null\n }\n\n return rowToSessionRecord(row)\n }\n\n async rotateRefreshToken(\n params: Parameters<AuthSessionStore[\"rotateRefreshToken\"]>[0]\n ): Promise<RotateSessionRefreshTokenResult> {\n return runImmediateTransaction(this.db, (): RotateSessionRefreshTokenResult => {\n const row = getSessionRowById(this.db, params)\n if (!row?.refresh_token_hash || !isLiveSessionRow(row, params.now)) {\n return { status: \"invalid\" }\n }\n\n const replacedRecently =\n row.previous_refresh_token_hash === params.refreshTokenHash &&\n row.refreshed_at !== null &&\n params.now.getTime() - new Date(row.refreshed_at).getTime() <= params.reuseGraceMs\n if (row.refresh_token_hash !== params.refreshTokenHash && !replacedRecently) {\n if (row.previous_refresh_token_hash !== params.refreshTokenHash) {\n return { status: \"invalid\" }\n }\n this.db\n .query(\"UPDATE auth_sessions SET revoked_at = ? WHERE project_id = ? AND id = ?\")\n .run(toIso(params.now), params.projectId, params.id)\n return { status: \"reused\" }\n }\n\n const expiresAt = toIso(params.next.expiresAt)\n this.db\n .query(`\n UPDATE auth_sessions\n SET token_hash = ?,\n access_expires_at = ?,\n previous_refresh_token_hash = refresh_token_hash,\n refresh_token_hash = ?,\n refreshed_at = ?,\n last_seen_at = ?,\n expires_at = MAX(expires_at, MIN(?, COALESCE(absolute_expires_at, ?)))\n WHERE project_id = ? AND id = ?\n `)\n .run(\n params.next.tokenHash,\n toIso(params.next.accessExpiresAt),\n params.next.refreshTokenHash,\n toIso(params.now),\n toIso(params.now),\n expiresAt,\n expiresAt,\n params.projectId,\n params.id\n )\n const session = getSessionById(this.db, params)\n return session ? { status: \"rotated\", session } : { status: \"invalid\" }\n })\n }\n\n async renewIfValid(params: {\n readonly projectId: string\n readonly id: string\n readonly tokenHash: string\n readonly now: Date\n readonly expiresAt: Date\n }): Promise<SessionRecord | null> {\n return runImmediateTransaction(this.db, () => {\n const now = toIso(params.now)\n const expiresAt = toIso(params.expiresAt)\n const result = this.db\n .query(\n `\n UPDATE auth_sessions\n SET expires_at = MAX(\n expires_at,\n MIN(?, COALESCE(absolute_expires_at, ?))\n ),\n last_seen_at = ?\n WHERE project_id = ?\n AND id = ?\n AND token_hash = ?\n AND refresh_token_hash IS NULL\n AND revoked_at IS NULL\n AND expires_at > ?\n AND (absolute_expires_at IS NULL OR absolute_expires_at > ?)\n `\n )\n .run(expiresAt, expiresAt, now, params.projectId, params.id, params.tokenHash, now, now)\n\n return result.changes === 0 ? null : getSessionById(this.db, params)\n })\n }\n\n async revoke(params: {\n readonly projectId: string\n readonly id: string\n readonly revokedAt: Date\n }): Promise<SessionRecord> {\n return runImmediateTransaction(this.db, () => {\n const existing = getSessionRowById(this.db, params)\n\n if (!existing) {\n throw new AuthStorageError(\n \"missing_session\",\n `[Sixb] Session '${params.id}' not found for project '${params.projectId}'.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE auth_sessions\n SET revoked_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(toIso(params.revokedAt), params.projectId, params.id)\n\n return rowToSessionRecord({\n ...existing,\n revoked_at: toIso(params.revokedAt),\n })\n })\n }\n\n async revokeActiveForUser(params: {\n readonly projectId: string\n readonly userId: string\n readonly revokedAt: Date\n }): Promise<readonly SessionRecord[]> {\n return runImmediateTransaction(this.db, () => revokeActiveSessionsForUser(this.db, params))\n }\n\n async touch(params: {\n readonly projectId: string\n readonly id: string\n readonly lastSeenAt: Date\n }): Promise<SessionRecord> {\n return runImmediateTransaction(this.db, () => {\n requireSessionById(this.db, params)\n\n this.db\n .query(\n `\n UPDATE auth_sessions\n SET last_seen_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(toIso(params.lastSeenAt), params.projectId, params.id)\n\n const updated = getSessionById(this.db, params)\n if (!updated) {\n throw new AuthStorageError(\n \"missing_session\",\n `[Sixb] Session '${params.id}' not found for project '${params.projectId}'.`\n )\n }\n return updated\n })\n }\n}\n\nfunction isLiveSessionRow(row: SqliteAuthSessionRow, now: Date): boolean {\n return (\n row.revoked_at === null &&\n new Date(row.expires_at) > now &&\n (row.absolute_expires_at === null || new Date(row.absolute_expires_at) > now)\n )\n}\n",
36
- "import type { Database } from \"bun:sqlite\"\nimport type {\n AuthUserStore,\n CreateAuthUserInput,\n ListAuthUsersInput,\n ListAuthUsersResult,\n UpdateAuthUserProfileInput,\n UpdateAuthUserStatusInput,\n UserRecord,\n} from \"@sixb/core/storage\"\nimport { AuthStorageError } from \"@sixb/core/storage\"\nimport type { SqliteAuthUserRow } from \"./rows\"\nimport { rowToUserRecord } from \"./rows\"\nimport {\n appendPagination,\n assertNonEmpty,\n dateOrNow,\n getUserRowByEmail,\n getUserRowById,\n hasEmptyFilter,\n mapUniqueConstraintError,\n normalizeEmail,\n type SqliteValue,\n toIso,\n} from \"./shared\"\n\nexport class SqliteAuthUserStore implements AuthUserStore {\n constructor(private readonly db: Database) {}\n\n async create(input: CreateAuthUserInput): Promise<UserRecord> {\n const id = assertNonEmpty(input.id, \"User id\")\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const email = normalizeEmail(input.email)\n\n if (getUserRowById(this.db, { projectId, id })) {\n throw new AuthStorageError(\n \"duplicate_user\",\n `[Sixb] User '${id}' already exists for project '${projectId}'.`\n )\n }\n\n if (getUserRowByEmail(this.db, { projectId, email })) {\n throw new AuthStorageError(\n \"duplicate_user\",\n `[Sixb] User email '${email}' already exists for project '${projectId}'.`\n )\n }\n\n const createdAt = dateOrNow(input.createdAt)\n const updatedAt = input.updatedAt ? new Date(input.updatedAt) : createdAt\n\n try {\n this.db\n .query(\n `\n INSERT INTO auth_users (\n project_id,\n id,\n email,\n display_name,\n avatar_url,\n status,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n projectId,\n id,\n email,\n input.displayName ?? null,\n input.avatarUrl ?? null,\n input.status ?? \"active\",\n toIso(createdAt),\n toIso(updatedAt)\n )\n } catch (error) {\n mapUniqueConstraintError(\n error,\n \"duplicate_user\",\n `[Sixb] User '${id}' already exists for project '${projectId}'.`\n )\n }\n\n return {\n id,\n projectId,\n email,\n displayName: input.displayName,\n avatarUrl: input.avatarUrl,\n status: input.status ?? \"active\",\n createdAt,\n updatedAt,\n }\n }\n\n async getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<UserRecord | null> {\n const row = getUserRowById(this.db, params)\n return row ? rowToUserRecord(row) : null\n }\n\n async getByEmail(params: {\n readonly projectId: string\n readonly email: string\n }): Promise<UserRecord | null> {\n const row = getUserRowByEmail(this.db, params)\n return row ? rowToUserRecord(row) : null\n }\n\n async updateProfile(input: UpdateAuthUserProfileInput): Promise<UserRecord> {\n const existing = getUserRowById(this.db, {\n projectId: input.projectId,\n id: input.id,\n })\n\n if (!existing) {\n throw new AuthStorageError(\n \"missing_user\",\n `[Sixb] User '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n const updatedAt = dateOrNow(input.updatedAt)\n this.db\n .query(\n `\n UPDATE auth_users\n SET display_name = ?,\n avatar_url = ?,\n updated_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(\n input.displayName ?? null,\n input.avatarUrl ?? null,\n toIso(updatedAt),\n input.projectId,\n input.id\n )\n\n return rowToUserRecord({\n ...existing,\n display_name: input.displayName ?? null,\n avatar_url: input.avatarUrl ?? null,\n updated_at: toIso(updatedAt),\n })\n }\n\n async updateStatus(input: UpdateAuthUserStatusInput): Promise<UserRecord> {\n const existing = getUserRowById(this.db, {\n projectId: input.projectId,\n id: input.id,\n })\n\n if (!existing) {\n throw new AuthStorageError(\n \"missing_user\",\n `[Sixb] User '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n const updatedAt = dateOrNow(input.updatedAt)\n this.db\n .query(\n `\n UPDATE auth_users\n SET status = ?,\n updated_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(input.status, toIso(updatedAt), input.projectId, input.id)\n\n return rowToUserRecord({\n ...existing,\n status: input.status,\n updated_at: toIso(updatedAt),\n })\n }\n\n async list(input: ListAuthUsersInput): Promise<ListAuthUsersResult> {\n if (hasEmptyFilter(input.statuses)) {\n return { users: [], hasMore: false, total: 0 }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n\n if (input.statuses) {\n whereClauses.push(`status IN (${input.statuses.map(() => \"?\").join(\", \")})`)\n args.push(...input.statuses)\n }\n\n const where = `WHERE ${whereClauses.join(\" AND \")}`\n const order = input.order === \"asc\" ? \"ASC\" : \"DESC\"\n const totalRow = this.db\n .query(`SELECT COUNT(*) AS count FROM auth_users ${where}`)\n .get(...args) as { readonly count: number }\n\n const queryArgs = [...args]\n const query = appendPagination(\n `\n SELECT *\n FROM auth_users\n ${where}\n ORDER BY created_at ${order}, id ${order}\n `,\n queryArgs,\n input\n )\n const rows = this.db.query(query).all(...queryArgs) as SqliteAuthUserRow[]\n\n return {\n users: rows.map(rowToUserRecord),\n hasMore: (input.offset ?? 0) + rows.length < totalRow.count,\n total: totalRow.count,\n }\n }\n}\n",
39
+ "import type { Database } from \"bun:sqlite\"\nimport type {\n AuthUserStore,\n CreateAuthUserInput,\n ListAuthUsersInput,\n ListAuthUsersResult,\n UpdateAuthUserProfileInput,\n UpdateAuthUserResult,\n UpdateAuthUserStatusInput,\n UserRecord,\n} from \"@sixb/core/storage\"\nimport { AuthStorageError } from \"@sixb/core/storage\"\nimport { runImmediateTransaction } from \"../transactions\"\nimport type { SqliteAuthUserRow } from \"./rows\"\nimport { rowToUserRecord } from \"./rows\"\nimport {\n appendPagination,\n assertNonEmpty,\n dateOrNow,\n getUserRowByEmail,\n getUserRowById,\n hasEmptyFilter,\n mapUniqueConstraintError,\n normalizeEmail,\n type SqliteValue,\n toIso,\n} from \"./shared\"\n\nexport class SqliteAuthUserStore implements AuthUserStore {\n constructor(private readonly db: Database) {}\n\n async create(input: CreateAuthUserInput): Promise<UserRecord> {\n const id = assertNonEmpty(input.id, \"User id\")\n const projectId = assertNonEmpty(input.projectId, \"Project id\")\n const email = normalizeEmail(input.email)\n\n if (getUserRowById(this.db, { projectId, id })) {\n throw new AuthStorageError(\n \"duplicate_user\",\n `[Sixb] User '${id}' already exists for project '${projectId}'.`\n )\n }\n\n if (getUserRowByEmail(this.db, { projectId, email })) {\n throw new AuthStorageError(\n \"duplicate_user\",\n `[Sixb] User email '${email}' already exists for project '${projectId}'.`\n )\n }\n\n const createdAt = dateOrNow(input.createdAt)\n const updatedAt = input.updatedAt ? new Date(input.updatedAt) : createdAt\n\n try {\n this.db\n .query(\n `\n INSERT INTO auth_users (\n project_id,\n id,\n email,\n display_name,\n avatar_url,\n status,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n projectId,\n id,\n email,\n input.displayName ?? null,\n input.avatarUrl ?? null,\n input.status ?? \"active\",\n toIso(createdAt),\n toIso(updatedAt)\n )\n } catch (error) {\n mapUniqueConstraintError(\n error,\n \"duplicate_user\",\n `[Sixb] User '${id}' already exists for project '${projectId}'.`\n )\n }\n\n return {\n id,\n projectId,\n email,\n displayName: input.displayName,\n avatarUrl: input.avatarUrl,\n status: input.status ?? \"active\",\n createdAt,\n updatedAt,\n }\n }\n\n async getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<UserRecord | null> {\n const row = getUserRowById(this.db, params)\n return row ? rowToUserRecord(row) : null\n }\n\n async getByIds(params: {\n readonly projectId: string\n readonly ids: readonly string[]\n }): Promise<readonly UserRecord[]> {\n const ids = [...new Set(params.ids)]\n if (ids.length === 0) return []\n\n const rows = this.db\n .query(\n `SELECT * FROM auth_users WHERE project_id = ? AND id IN (${ids.map(() => \"?\").join(\", \")})`\n )\n .all(params.projectId, ...ids) as SqliteAuthUserRow[]\n\n return rows.map(rowToUserRecord)\n }\n\n async getByEmail(params: {\n readonly projectId: string\n readonly email: string\n }): Promise<UserRecord | null> {\n const row = getUserRowByEmail(this.db, params)\n return row ? rowToUserRecord(row) : null\n }\n\n async updateProfile(input: UpdateAuthUserProfileInput): Promise<UpdateAuthUserResult> {\n // One transaction, so the user it returns as previous is the one it changed.\n return runImmediateTransaction(this.db, () => {\n const existing = getUserRowById(this.db, {\n projectId: input.projectId,\n id: input.id,\n })\n\n if (!existing) {\n throw new AuthStorageError(\n \"missing_user\",\n `[Sixb] User '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n const previousUser = rowToUserRecord(existing)\n if (!changesProfile(previousUser, input)) {\n return { user: previousUser, previousUser }\n }\n\n const updatedAt = dateOrNow(input.updatedAt)\n const row = this.db\n .query(\n `\n UPDATE auth_users\n SET display_name = CASE WHEN ? THEN ? ELSE display_name END,\n avatar_url = CASE WHEN ? THEN ? ELSE avatar_url END,\n updated_at = ?\n WHERE project_id = ?\n AND id = ?\n RETURNING *\n `\n )\n .get(\n input.displayName === undefined ? 0 : 1,\n input.displayName ?? null,\n input.avatarUrl === undefined ? 0 : 1,\n input.avatarUrl ?? null,\n toIso(updatedAt),\n input.projectId,\n input.id\n ) as SqliteAuthUserRow\n\n return { user: rowToUserRecord(row), previousUser }\n })\n }\n\n async updateStatus(input: UpdateAuthUserStatusInput): Promise<UpdateAuthUserResult> {\n // One transaction, so two status changes cannot both report the same previous one.\n return runImmediateTransaction(this.db, () => {\n const existing = getUserRowById(this.db, {\n projectId: input.projectId,\n id: input.id,\n })\n\n if (!existing) {\n throw new AuthStorageError(\n \"missing_user\",\n `[Sixb] User '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n const updatedAt = dateOrNow(input.updatedAt)\n this.db\n .query(\n `\n UPDATE auth_users\n SET status = ?,\n updated_at = ?\n WHERE project_id = ?\n AND id = ?\n `\n )\n .run(input.status, toIso(updatedAt), input.projectId, input.id)\n\n const user = rowToUserRecord({\n ...existing,\n status: input.status,\n updated_at: toIso(updatedAt),\n })\n return { user, previousUser: rowToUserRecord(existing) }\n })\n }\n\n async list(input: ListAuthUsersInput): Promise<ListAuthUsersResult> {\n if (hasEmptyFilter(input.statuses)) {\n return { users: [], hasMore: false, total: 0 }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n\n if (input.statuses) {\n whereClauses.push(`status IN (${input.statuses.map(() => \"?\").join(\", \")})`)\n args.push(...input.statuses)\n }\n\n // `instr` matches literally, so `%` and `_` need no escaping. Both sides fold through the same\n // `lower()`, which ignores case for ASCII letters only: \"émilie\" does not find \"Émilie\" here.\n if (input.search !== undefined) {\n whereClauses.push(\n \"(instr(lower(coalesce(display_name, '')), lower(?)) > 0 OR instr(lower(email), lower(?)) > 0)\"\n )\n args.push(input.search, input.search)\n }\n\n const where = `WHERE ${whereClauses.join(\" AND \")}`\n const order = input.order === \"asc\" ? \"ASC\" : \"DESC\"\n const totalRow = this.db\n .query(`SELECT COUNT(*) AS count FROM auth_users ${where}`)\n .get(...args) as { readonly count: number }\n\n const queryArgs = [...args]\n const query = appendPagination(\n `\n SELECT *\n FROM auth_users\n ${where}\n ORDER BY created_at ${order}, id ${order}\n `,\n queryArgs,\n input\n )\n const rows = this.db.query(query).all(...queryArgs) as SqliteAuthUserRow[]\n\n return {\n users: rows.map(rowToUserRecord),\n hasMore: (input.offset ?? 0) + rows.length < totalRow.count,\n total: totalRow.count,\n }\n }\n}\n\n// Omitted keeps the stored value, and `null` clears it.\nfunction changesProfile(user: UserRecord, input: UpdateAuthUserProfileInput): boolean {\n const displayName =\n input.displayName === undefined ? user.displayName : (input.displayName ?? undefined)\n const avatarUrl = input.avatarUrl === undefined ? user.avatarUrl : (input.avatarUrl ?? undefined)\n\n return displayName !== user.displayName || avatarUrl !== user.avatarUrl\n}\n",
37
40
  "import type { Database, SQLQueryBindings } from \"bun:sqlite\"\nimport {\n type ConnectorConnectionPersistence,\n type ConnectorConnectionPersistenceBackend,\n type ConnectorConnectionPersistenceScope,\n DurableConnectorConnectionStorage,\n} from \"@sixb/core/internal/connector-connection-storage-provider\"\nimport type {\n ConnectorAuthorizationAttemptRecord,\n ConnectorAuthorizationRecord,\n ConnectorConnectionRecord,\n ConnectorConnectionRunRecord,\n ConnectorCredentialMutation,\n} from \"@sixb/core/storage\"\nimport { isUniqueConstraintError } from \"./storage-errors\"\nimport { runImmediateTransactionAsync, type SqliteStoreConnection } from \"./transactions\"\n\nexport class SqliteConnectorConnectionStorage extends DurableConnectorConnectionStorage {\n private readonly clock: ConnectorConnectionTestClock\n\n constructor(connection: SqliteStoreConnection) {\n const clock = { offsetMs: 0 }\n super(new SqliteConnectorConnectionPersistenceBackend(connection.db, clock))\n this.clock = clock\n }\n\n /** Internal deterministic clock control used only by the provider contract suite. */\n advanceTimeForTesting(durationMs: number): void {\n this.clock.offsetMs += durationMs\n }\n}\n\nclass SqliteConnectorConnectionPersistenceBackend implements ConnectorConnectionPersistenceBackend {\n constructor(\n private readonly db: Database,\n private readonly clock: ConnectorConnectionTestClock\n ) {}\n\n read<T>(\n scope: ConnectorConnectionPersistenceScope,\n run: (persistence: ConnectorConnectionPersistence) => Promise<T>\n ): Promise<T> {\n return run(new SqliteConnectorConnectionPersistence(this.db, scope, this.clock))\n }\n\n transaction<T>(\n scope: ConnectorConnectionPersistenceScope,\n run: (persistence: ConnectorConnectionPersistence) => Promise<T>\n ): Promise<T> {\n return runImmediateTransactionAsync(this.db, () =>\n run(new SqliteConnectorConnectionPersistence(this.db, scope, this.clock))\n )\n }\n}\n\nclass SqliteConnectorConnectionPersistence implements ConnectorConnectionPersistence {\n constructor(\n private readonly db: Database,\n private readonly scope: ConnectorConnectionPersistenceScope,\n private readonly clock: ConnectorConnectionTestClock\n ) {}\n\n async now(): Promise<Date> {\n const row = this.db.query(\"SELECT strftime('%Y-%m-%dT%H:%M:%fZ', 'now') AS now\").get() as {\n readonly now: string\n }\n return new Date(new Date(row.now).getTime() + this.clock.offsetMs)\n }\n\n async insertAuthorizationAttempt(record: ConnectorAuthorizationAttemptRecord): Promise<boolean> {\n try {\n this.db\n .query(\n `\n INSERT INTO connector_authorization_attempts (\n project_id, connector_id, id, slot, initiated_by_execution_id,\n state_hash, code_verifier, redirect_uri, connection_run_id, return_to,\n callback_binding_hash, reauthorization_id, reauthorization_revision,\n reauthorization_connection_ids, created_at, expires_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n record.projectId,\n record.connectorId,\n record.id,\n record.slot,\n record.initiatedByExecutionId,\n record.stateHash,\n record.codeVerifier === undefined ? null : json(record.codeVerifier),\n record.redirectUri,\n record.connectionRunId ?? null,\n record.returnTo ?? null,\n record.callbackBindingHash ?? null,\n record.reauthorizationId ?? null,\n record.reauthorizationRevision ?? null,\n record.reauthorizationConnectionIds ? json(record.reauthorizationConnectionIds) : null,\n iso(record.createdAt),\n iso(record.expiresAt)\n )\n return true\n } catch (error) {\n if (isUniqueConstraintError(error)) return false\n throw error\n }\n }\n\n async getAuthorizationAttempt(id: string): Promise<ConnectorAuthorizationAttemptRecord | null> {\n const row = this.getById<SqliteAuthorizationAttemptRow>(\"connector_authorization_attempts\", id)\n return row ? authorizationAttemptFromRow(row) : null\n }\n\n async getAuthorizationAttemptByConnectionRunId(\n connectionRunId: string\n ): Promise<ConnectorAuthorizationAttemptRecord | null> {\n if (!this.scope.connectorId) return null\n const row = this.db\n .query(\n `\n SELECT * FROM connector_authorization_attempts\n WHERE project_id = ? AND connector_id = ? AND connection_run_id = ?\n `\n )\n .get(\n this.scope.projectId,\n this.scope.connectorId,\n connectionRunId\n ) as SqliteAuthorizationAttemptRow | null\n return row ? authorizationAttemptFromRow(row) : null\n }\n\n async deleteAuthorizationAttempt(id: string): Promise<boolean> {\n return this.deleteById(\"connector_authorization_attempts\", id)\n }\n\n async insertConnectionRun(record: ConnectorConnectionRunRecord): Promise<boolean> {\n try {\n this.insertRun(record)\n return true\n } catch (error) {\n if (isUniqueConstraintError(error)) return false\n throw error\n }\n }\n\n async listPendingConnectionRuns(): Promise<readonly ConnectorConnectionRunRecord[]> {\n if (!this.scope.connectorId) return []\n const rows = this.db\n .query(`SELECT * FROM connector_connection_runs\n WHERE project_id = ? AND connector_id = ?\n AND (status = 'running' OR (status = 'waiting' AND waiting_for = 'account_selection'))`)\n .all(this.scope.projectId, this.scope.connectorId) as SqliteConnectionRunRow[]\n return rows.map(connectionRunFromRow)\n }\n\n async getConnectionRun(id: string): Promise<ConnectorConnectionRunRecord | null> {\n const row = this.getById<SqliteConnectionRunRow>(\"connector_connection_runs\", id)\n return row ? connectionRunFromRow(row) : null\n }\n\n async updateConnectionRun(record: ConnectorConnectionRunRecord): Promise<void> {\n const values = runValues(record)\n const result = this.db\n .query(\n `\n UPDATE connector_connection_runs\n SET kind = ?, slot = ?, initiated_by_execution_id = ?, status = ?,\n waiting_for = ?, processing_id = ?,\n callback_started_at = ?, expires_at = ?, authorization_id = ?,\n cleanup_authorization_id = ?, connections = ?, error = ?, updated_at = ?, finished_at = ?\n WHERE project_id = ? AND connector_id = ? AND id = ?\n `\n )\n .run(...values, record.projectId, record.connectorId, record.id)\n assertChanged(result.changes, \"connector connection run\", record.id)\n }\n\n async insertAuthorization(record: ConnectorAuthorizationRecord): Promise<boolean> {\n try {\n this.insertAuthorizationRow(record)\n return true\n } catch (error) {\n if (isUniqueConstraintError(error)) return false\n throw error\n }\n }\n\n async getAuthorization(id: string): Promise<ConnectorAuthorizationRecord | null> {\n const row = this.getById<SqliteAuthorizationRow>(\"connector_authorizations\", id)\n return row ? authorizationFromRow(row) : null\n }\n\n async updateAuthorization(record: ConnectorAuthorizationRecord): Promise<void> {\n const result = this.db\n .query(\n `\n UPDATE connector_authorizations\n SET authorized_by = ?, credentials = ?, credential_expires_at = ?, scopes = ?, accounts = ?,\n status = ?, selection_expires_at = ?, revision = ?, mutation_id = ?, mutation_kind = ?,\n mutation_phase = ?, mutation_holder_id = ?, mutation_expires_at = ?,\n mutation_deadline_at = ?, mutation_expected_connection_ids = ?, staged_credentials = ?,\n staged_credential_expires_at = ?, staged_scopes = ?, updated_at = ?\n WHERE project_id = ? AND connector_id = ? AND id = ?\n `\n )\n .run(...authorizationValues(record), record.projectId, record.connectorId, record.id)\n assertChanged(result.changes, \"connector authorization\", record.id)\n }\n\n async insertConnection(record: ConnectorConnectionRecord): Promise<boolean> {\n try {\n this.db\n .query(\n `\n INSERT INTO connector_connections (\n project_id, connector_id, id, authorization_id, slot, account,\n account_id, status, disconnected_at, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n record.projectId,\n record.connectorId,\n record.id,\n record.authorizationId,\n record.slot,\n json(record.account),\n record.account.id,\n record.status,\n optionalIso(record.disconnectedAt),\n iso(record.createdAt),\n iso(record.updatedAt)\n )\n return true\n } catch (error) {\n if (isUniqueConstraintError(error)) return false\n throw error\n }\n }\n\n async getConnectionById(id: string): Promise<ConnectorConnectionRecord | null> {\n const row = this.getById<SqliteConnectionRow>(\"connector_connections\", id)\n return row ? connectionFromRow(row) : null\n }\n\n async getConnectionBySelector(input: {\n readonly owner: { readonly type: \"project\" }\n readonly slot: string\n }): Promise<ConnectorConnectionRecord | null> {\n if (!this.scope.connectorId) return null\n const row = this.db\n .query(\n `\n SELECT * FROM connector_connections\n WHERE project_id = ? AND connector_id = ? AND slot = ?\n `\n )\n .get(this.scope.projectId, this.scope.connectorId, input.slot) as SqliteConnectionRow | null\n return row ? connectionFromRow(row) : null\n }\n\n async listConnections(): Promise<readonly ConnectorConnectionRecord[]> {\n if (!this.scope.connectorId) return []\n const rows = this.db\n .query(\n `\n SELECT * FROM connector_connections\n WHERE project_id = ? AND connector_id = ?\n ORDER BY id\n `\n )\n .all(this.scope.projectId, this.scope.connectorId) as SqliteConnectionRow[]\n return rows.map(connectionFromRow)\n }\n\n async listConnectionsByAuthorization(\n authorizationId: string,\n options: { readonly connectedOnly?: boolean } = {}\n ): Promise<readonly ConnectorConnectionRecord[]> {\n if (!this.scope.connectorId) return []\n const rows = options.connectedOnly\n ? (this.db\n .query(\n `\n SELECT * FROM connector_connections\n WHERE project_id = ? AND connector_id = ? AND authorization_id = ?\n AND status = 'connected'\n ORDER BY id\n `\n )\n .all(\n this.scope.projectId,\n this.scope.connectorId,\n authorizationId\n ) as SqliteConnectionRow[])\n : (this.db\n .query(\n `\n SELECT * FROM connector_connections\n WHERE project_id = ? AND connector_id = ? AND authorization_id = ?\n ORDER BY id\n `\n )\n .all(\n this.scope.projectId,\n this.scope.connectorId,\n authorizationId\n ) as SqliteConnectionRow[])\n return rows.map(connectionFromRow)\n }\n\n async updateConnection(record: ConnectorConnectionRecord): Promise<void> {\n const result = this.db\n .query(\n `\n UPDATE connector_connections\n SET authorization_id = ?, slot = ?, account = ?, account_id = ?,\n status = ?, disconnected_at = ?, updated_at = ?\n WHERE project_id = ? AND connector_id = ? AND id = ?\n `\n )\n .run(\n record.authorizationId,\n record.slot,\n json(record.account),\n record.account.id,\n record.status,\n optionalIso(record.disconnectedAt),\n iso(record.updatedAt),\n record.projectId,\n record.connectorId,\n record.id\n )\n assertChanged(result.changes, \"connector connection\", record.id)\n }\n\n private insertRun(record: ConnectorConnectionRunRecord): void {\n const values = runValues(record)\n this.db\n .query(\n `\n INSERT INTO connector_connection_runs (\n project_id, connector_id, id, kind, slot, initiated_by_execution_id,\n status, waiting_for, processing_id, callback_started_at,\n expires_at, authorization_id, cleanup_authorization_id, connections, error,\n created_at, updated_at, finished_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n record.projectId,\n record.connectorId,\n record.id,\n ...values.slice(0, -2),\n iso(record.createdAt),\n ...values.slice(-2)\n )\n }\n\n private insertAuthorizationRow(record: ConnectorAuthorizationRecord): void {\n const values = authorizationValues(record)\n this.db\n .query(\n `\n INSERT INTO connector_authorizations (\n project_id, connector_id, id, authorized_by, credentials, credential_expires_at,\n scopes, accounts, status, selection_expires_at, revision, mutation_id, mutation_kind,\n mutation_phase, mutation_holder_id, mutation_expires_at, mutation_deadline_at,\n mutation_expected_connection_ids, staged_credentials, staged_credential_expires_at,\n staged_scopes, created_at, updated_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n record.projectId,\n record.connectorId,\n record.id,\n ...values.slice(0, -1),\n iso(record.createdAt),\n ...values.slice(-1)\n )\n }\n\n private getById<TRow>(table: ConnectorTable, id: string): TRow | null {\n if (this.scope.connectorId) {\n return this.db\n .query(`SELECT * FROM ${table} WHERE project_id = ? AND connector_id = ? AND id = ?`)\n .get(this.scope.projectId, this.scope.connectorId, id) as TRow | null\n }\n return this.db\n .query(`SELECT * FROM ${table} WHERE project_id = ? AND id = ?`)\n .get(this.scope.projectId, id) as TRow | null\n }\n\n private deleteById(table: ConnectorTable, id: string): boolean {\n const result = this.scope.connectorId\n ? this.db\n .query(`DELETE FROM ${table} WHERE project_id = ? AND connector_id = ? AND id = ?`)\n .run(this.scope.projectId, this.scope.connectorId, id)\n : this.db\n .query(`DELETE FROM ${table} WHERE project_id = ? AND id = ?`)\n .run(this.scope.projectId, id)\n return result.changes === 1\n }\n}\n\ntype ConnectorTable =\n | \"connector_authorization_attempts\"\n | \"connector_connection_runs\"\n | \"connector_authorizations\"\n | \"connector_connections\"\n\nfunction authorizationAttemptFromRow(\n row: SqliteAuthorizationAttemptRow\n): ConnectorAuthorizationAttemptRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n connectorId: row.connector_id,\n owner: { type: \"project\" },\n slot: row.slot,\n initiatedByExecutionId: row.initiated_by_execution_id,\n stateHash: row.state_hash,\n ...(row.code_verifier === null ? {} : { codeVerifier: parseJson(row.code_verifier) }),\n redirectUri: row.redirect_uri,\n ...(row.connection_run_id === null ? {} : { connectionRunId: row.connection_run_id }),\n ...(row.return_to === null ? {} : { returnTo: row.return_to }),\n ...(row.callback_binding_hash === null\n ? {}\n : { callbackBindingHash: row.callback_binding_hash }),\n ...(row.reauthorization_id === null ? {} : { reauthorizationId: row.reauthorization_id }),\n ...(row.reauthorization_revision === null\n ? {}\n : { reauthorizationRevision: row.reauthorization_revision }),\n ...(row.reauthorization_connection_ids === null\n ? {}\n : { reauthorizationConnectionIds: parseJson(row.reauthorization_connection_ids) }),\n createdAt: new Date(row.created_at),\n expiresAt: new Date(row.expires_at),\n }\n}\n\nfunction runValues(record: ConnectorConnectionRunRecord): readonly SQLQueryBindings[] {\n const waitingFor = record.status === \"waiting\" ? record.waitingFor : null\n const processingId = record.status === \"running\" ? record.processingId : null\n const callbackStartedAt = record.status === \"running\" ? iso(record.callbackStartedAt) : null\n const expiresAt =\n record.status === \"waiting\" || record.status === \"running\" ? iso(record.expiresAt) : null\n const authorizationId = \"authorizationId\" in record ? (record.authorizationId ?? null) : null\n const cleanupAuthorizationId =\n record.status === \"succeeded\" ? (record.cleanupAuthorizationId ?? null) : null\n const connections = record.status === \"succeeded\" ? json(record.connections) : null\n const error = record.status === \"failed\" ? json(record.error) : null\n const finishedAt =\n record.status === \"succeeded\" ||\n record.status === \"failed\" ||\n record.status === \"cancelled\" ||\n record.status === \"expired\"\n ? iso(record.finishedAt)\n : null\n return [\n record.kind,\n record.slot,\n record.initiatedByExecutionId,\n record.status,\n waitingFor,\n processingId,\n callbackStartedAt,\n expiresAt,\n authorizationId,\n cleanupAuthorizationId,\n connections,\n error,\n iso(record.updatedAt),\n finishedAt,\n ]\n}\n\nfunction connectionRunFromRow(row: SqliteConnectionRunRow): ConnectorConnectionRunRecord {\n const base = {\n id: row.id,\n projectId: row.project_id,\n connectorId: row.connector_id,\n kind: row.kind,\n owner: { type: \"project\" as const },\n slot: row.slot,\n initiatedByExecutionId: row.initiated_by_execution_id,\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n }\n if (row.status === \"waiting\" && row.waiting_for === \"provider_authorization\") {\n return {\n ...base,\n status: \"waiting\",\n waitingFor: \"provider_authorization\",\n expiresAt: new Date(required(row.expires_at, \"run expiry\")),\n }\n }\n if (row.status === \"waiting\" && row.waiting_for === \"account_selection\") {\n return {\n ...base,\n status: \"waiting\",\n waitingFor: \"account_selection\",\n authorizationId: required(row.authorization_id, \"authorization id\"),\n expiresAt: new Date(required(row.expires_at, \"run expiry\")),\n }\n }\n if (row.status === \"running\") {\n return {\n ...base,\n status: \"running\",\n processingId: required(row.processing_id, \"processing id\"),\n callbackStartedAt: new Date(required(row.callback_started_at, \"callback start\")),\n expiresAt: new Date(required(row.expires_at, \"run expiry\")),\n ...(row.authorization_id === null ? {} : { authorizationId: row.authorization_id }),\n }\n }\n const finishedAt = new Date(required(row.finished_at, \"run finish\"))\n if (row.status === \"succeeded\") {\n return {\n ...base,\n status: \"succeeded\",\n authorizationId: required(row.authorization_id, \"authorization id\"),\n ...(row.cleanup_authorization_id === null\n ? {}\n : { cleanupAuthorizationId: row.cleanup_authorization_id }),\n connections: parseJson<readonly SerializedConnectorConnection[]>(\n required(row.connections, \"connections\")\n ).map(connectionFromSerialized),\n finishedAt,\n }\n }\n if (row.status === \"failed\") {\n return {\n ...base,\n status: \"failed\",\n error: parseJson(required(row.error, \"run error\")),\n ...(row.authorization_id === null ? {} : { authorizationId: row.authorization_id }),\n finishedAt,\n }\n }\n if (row.status === \"cancelled\") {\n return {\n ...base,\n status: \"cancelled\",\n ...(row.authorization_id === null ? {} : { authorizationId: row.authorization_id }),\n finishedAt,\n }\n }\n if (row.status === \"expired\") {\n return {\n ...base,\n status: \"expired\",\n ...(row.authorization_id === null ? {} : { authorizationId: row.authorization_id }),\n finishedAt,\n }\n }\n throw invalidStoredValue(\"connector connection run status\", row.status)\n}\n\nfunction authorizationValues(record: ConnectorAuthorizationRecord): readonly SQLQueryBindings[] {\n const mutation = record.credentialMutation\n const staged = mutation?.stagedCredentials\n return [\n json(record.authorizedBy),\n record.credentials ? json(record.credentials) : null,\n optionalIso(record.credentialExpiresAt),\n json(record.scopes),\n json(record.accounts),\n record.status,\n optionalIso(record.selectionExpiresAt),\n record.revision,\n mutation?.id ?? null,\n mutation?.kind ?? null,\n mutation?.phase ?? null,\n mutation?.holderId ?? null,\n optionalIso(mutation?.expiresAt),\n optionalIso(mutation?.deadlineAt),\n mutation?.expectedConnectionIds ? json(mutation.expectedConnectionIds) : null,\n staged ? json(staged.credentials) : null,\n optionalIso(staged?.credentialExpiresAt),\n staged ? json(staged.scopes) : null,\n iso(record.updatedAt),\n ]\n}\n\nfunction authorizationFromRow(row: SqliteAuthorizationRow): ConnectorAuthorizationRecord {\n const mutation = mutationFromRow(row)\n return {\n id: row.id,\n projectId: row.project_id,\n connectorId: row.connector_id,\n authorizedBy: parseJson(row.authorized_by),\n ...(row.credentials === null ? {} : { credentials: parseJson(row.credentials) }),\n ...(row.credential_expires_at === null\n ? {}\n : { credentialExpiresAt: new Date(row.credential_expires_at) }),\n scopes: parseJson(row.scopes),\n accounts: parseJson(row.accounts),\n status: row.status,\n ...(row.selection_expires_at === null\n ? {}\n : { selectionExpiresAt: new Date(row.selection_expires_at) }),\n revision: row.revision,\n ...(mutation === undefined ? {} : { credentialMutation: mutation }),\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n }\n}\n\nfunction mutationFromRow(row: SqliteAuthorizationRow): ConnectorCredentialMutation | undefined {\n if (row.mutation_id === null) return undefined\n const kind = required(row.mutation_kind, \"credential mutation kind\")\n const phase = required(row.mutation_phase, \"credential mutation phase\")\n const stagedCredentials: ConnectorCredentialMutation[\"stagedCredentials\"] =\n row.staged_credentials === null\n ? undefined\n : {\n credentials: parseJson<\n NonNullable<ConnectorCredentialMutation[\"stagedCredentials\"]>[\"credentials\"]\n >(row.staged_credentials),\n ...(row.staged_credential_expires_at === null\n ? {}\n : { credentialExpiresAt: new Date(row.staged_credential_expires_at) }),\n scopes: parseJson<readonly string[]>(\n required(row.staged_scopes, \"staged credential scopes\")\n ),\n }\n return {\n id: row.mutation_id,\n kind,\n phase,\n holderId: required(row.mutation_holder_id, \"credential mutation holder\"),\n expiresAt: new Date(required(row.mutation_expires_at, \"credential mutation expiry\")),\n deadlineAt: new Date(required(row.mutation_deadline_at, \"credential mutation deadline\")),\n ...(row.mutation_expected_connection_ids === null\n ? {}\n : {\n expectedConnectionIds: parseJson<readonly string[]>(row.mutation_expected_connection_ids),\n }),\n ...(stagedCredentials === undefined ? {} : { stagedCredentials }),\n }\n}\n\nfunction connectionFromRow(row: SqliteConnectionRow): ConnectorConnectionRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n connectorId: row.connector_id,\n authorizationId: row.authorization_id,\n owner: { type: \"project\" },\n slot: row.slot,\n account: parseJson(row.account),\n status: row.status,\n ...(row.disconnected_at === null ? {} : { disconnectedAt: new Date(row.disconnected_at) }),\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n }\n}\n\ntype SerializedConnectorConnection = Omit<\n ConnectorConnectionRecord,\n \"createdAt\" | \"updatedAt\" | \"disconnectedAt\"\n> & {\n readonly createdAt: string\n readonly updatedAt: string\n readonly disconnectedAt?: string\n}\n\nfunction connectionFromSerialized(\n record: SerializedConnectorConnection\n): ConnectorConnectionRecord {\n const { createdAt, updatedAt, disconnectedAt, ...connection } = record\n return {\n ...connection,\n createdAt: new Date(createdAt),\n updatedAt: new Date(updatedAt),\n ...(disconnectedAt === undefined ? {} : { disconnectedAt: new Date(disconnectedAt) }),\n }\n}\n\nfunction json(value: unknown): string {\n return JSON.stringify(value)\n}\n\nfunction parseJson<T>(value: string): T {\n return JSON.parse(value) as T\n}\n\nfunction iso(value: Date): string {\n return value.toISOString()\n}\n\nfunction optionalIso(value: Date | undefined): string | null {\n return value?.toISOString() ?? null\n}\n\nfunction required<T>(value: T | null, label: string): T {\n if (value !== null) return value\n throw new Error(`[SixbSqlite] Stored ${label} is missing.`)\n}\n\nfunction invalidStoredValue(label: string, value: unknown): Error {\n return new Error(`[SixbSqlite] Stored ${label} '${String(value)}' is invalid.`)\n}\n\nfunction assertChanged(changes: number, label: string, id: string): void {\n if (changes === 1) return\n throw new Error(`[SixbSqlite] Stored ${label} '${id}' is unavailable.`)\n}\n\ninterface SqliteAuthorizationAttemptRow {\n readonly project_id: string\n readonly connector_id: string\n readonly id: string\n readonly slot: string\n readonly initiated_by_execution_id: string\n readonly state_hash: string\n readonly code_verifier: string | null\n readonly redirect_uri: string\n readonly connection_run_id: string | null\n readonly return_to: string | null\n readonly callback_binding_hash: string | null\n readonly reauthorization_id: string | null\n readonly reauthorization_revision: number | null\n readonly reauthorization_connection_ids: string | null\n readonly created_at: string\n readonly expires_at: string\n}\n\ninterface SqliteConnectionRunRow {\n readonly project_id: string\n readonly connector_id: string\n readonly id: string\n readonly kind: ConnectorConnectionRunRecord[\"kind\"]\n readonly slot: string\n readonly initiated_by_execution_id: string\n readonly status: ConnectorConnectionRunRecord[\"status\"]\n readonly waiting_for: \"provider_authorization\" | \"account_selection\" | null\n readonly processing_id: string | null\n readonly callback_started_at: string | null\n readonly expires_at: string | null\n readonly authorization_id: string | null\n readonly cleanup_authorization_id: string | null\n readonly connections: string | null\n readonly error: string | null\n readonly created_at: string\n readonly updated_at: string\n readonly finished_at: string | null\n}\n\ninterface SqliteAuthorizationRow {\n readonly project_id: string\n readonly connector_id: string\n readonly id: string\n readonly authorized_by: string\n readonly credentials: string | null\n readonly credential_expires_at: string | null\n readonly scopes: string\n readonly accounts: string\n readonly status: ConnectorAuthorizationRecord[\"status\"]\n readonly selection_expires_at: string | null\n readonly revision: number\n readonly mutation_id: string | null\n readonly mutation_kind: ConnectorCredentialMutation[\"kind\"] | null\n readonly mutation_phase: ConnectorCredentialMutation[\"phase\"] | null\n readonly mutation_holder_id: string | null\n readonly mutation_expires_at: string | null\n readonly mutation_deadline_at: string | null\n readonly mutation_expected_connection_ids: string | null\n readonly staged_credentials: string | null\n readonly staged_credential_expires_at: string | null\n readonly staged_scopes: string | null\n readonly created_at: string\n readonly updated_at: string\n}\n\ninterface SqliteConnectionRow {\n readonly project_id: string\n readonly connector_id: string\n readonly id: string\n readonly authorization_id: string\n readonly slot: string\n readonly account: string\n readonly account_id: string\n readonly status: ConnectorConnectionRecord[\"status\"]\n readonly disconnected_at: string | null\n readonly created_at: string\n readonly updated_at: string\n}\n\ninterface ConnectorConnectionTestClock {\n offsetMs: number\n}\n",
38
- "import type { Database } from \"bun:sqlite\"\nimport {\n compareExecutionCreation,\n type ExecutionStorageRow,\n executionRecordFromStorageRow,\n executionRecordToStorageRow,\n prepareExecutionRecord,\n} from \"@sixb/core/internal/execution-storage\"\nimport type {\n CreateExecutionInput,\n ExecutionRecord,\n ExecutionStorage,\n ListSessionExecutionsInput,\n SessionExecutions,\n ShareSessionStorage,\n} from \"@sixb/core/storage\"\nimport { ExecutionStorageError } from \"@sixb/core/storage\"\nimport type { SqliteAuthStorage } from \"./auth-storage\"\n\nexport class SqliteExecutionStorage implements ExecutionStorage {\n constructor(\n private readonly db: Database,\n private readonly auth: SqliteAuthStorage,\n private readonly shareSessions: Pick<ShareSessionStorage, \"getById\">\n ) {}\n\n async create(input: CreateExecutionInput): Promise<ExecutionRecord> {\n const record = await prepareExecutionRecord(input, {\n auth: this.auth,\n getExecution: (params) => this.getById(params),\n getShareSession: (params) => this.shareSessions.getById(params),\n })\n const row = executionRecordToStorageRow(record)\n\n try {\n this.db\n .query(\n `\n INSERT INTO executions (\n project_id,\n id,\n executor_kind,\n executor_id,\n source_kind,\n source_id,\n requested_by_user_id,\n requested_by_service_account_id,\n requester_group_ids,\n correlation_id,\n parent_execution_id,\n authority_kind,\n authority_user_id,\n authority_service_account_id,\n authority_session_id,\n authority_access_token_id,\n authority_primitive_kind,\n authority_primitive_id,\n authority_kernel_operation,\n authority_delegation_kind,\n authority_delegation_id,\n authority_delegation_session_id,\n created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n row.projectId,\n row.id,\n row.executorKind,\n row.executorId,\n row.sourceKind,\n row.sourceId,\n row.requestedByUserId,\n row.requestedByServiceAccountId,\n JSON.stringify(row.requesterGroupIds),\n row.correlationId,\n row.parentExecutionId,\n row.authorityKind,\n row.authorityUserId,\n row.authorityServiceAccountId,\n row.authoritySessionId,\n row.authorityAccessTokenId,\n row.authorityPrimitiveKind,\n row.authorityPrimitiveId,\n row.authorityKernelOperation,\n row.authorityDelegationKind,\n row.authorityDelegationId,\n row.authorityDelegationSessionId,\n row.createdAt.toISOString()\n )\n } catch (error) {\n if (isDuplicateExecutionError(error)) {\n throw new ExecutionStorageError(\n \"duplicate_execution\",\n `[SixbSqlite] Execution '${record.id}' already exists in project '${record.projectId}'.`,\n { cause: error }\n )\n }\n throw error\n }\n\n return executionRecordFromStorageRow(row)\n }\n\n async getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<ExecutionRecord | null> {\n const row = this.db\n .query(\n `\n SELECT *\n FROM executions\n WHERE project_id = ? AND id = ?\n `\n )\n .get(params.projectId, params.id) as SqliteExecutionRow | null\n\n return row ? sqliteExecutionRecord(row) : null\n }\n\n async listBySession(input: ListSessionExecutionsInput): Promise<SessionExecutions> {\n const sessionColumn =\n input.session.type === \"user\" ? \"authority_session_id\" : \"authority_delegation_session_id\"\n\n // The queue is ordered by depth, so the walk takes roots, then their children level by level,\n // the earliest first, and the limit stops it: a large tree costs no more than the rows\n // returned. CROSS JOIN keeps the walk driven by the rows found: statistics taken on a small\n // ledger choose to scan every child.\n const rows = this.db\n .query(\n `\n WITH RECURSIVE tree AS (\n SELECT roots.*, 0 AS depth\n FROM (\n SELECT *\n FROM executions\n WHERE project_id = ?\n AND ${sessionColumn} = ?\n AND parent_execution_id IS NULL\n AND created_at >= ?\n AND created_at < ?\n ORDER BY created_at, id\n LIMIT ?\n ) roots\n UNION ALL\n SELECT child.*, tree.depth + 1\n FROM tree\n CROSS JOIN executions child\n ON child.project_id = tree.project_id\n AND child.parent_execution_id = tree.id\n ORDER BY depth, created_at, id\n LIMIT ?\n )\n SELECT * FROM tree\n `\n )\n .all(\n input.projectId,\n input.session.id,\n input.from.toISOString(),\n input.to.toISOString(),\n input.limit + 1,\n input.limit + 1\n ) as SqliteExecutionRow[]\n\n // Rows come out in walk order, so the first `limit` are the ones the contract keeps.\n const kept = rows.slice(0, input.limit).map(sqliteExecutionRecord)\n return {\n executions: kept.sort(compareExecutionCreation),\n truncated: rows.length > input.limit,\n }\n }\n}\n\n/** An `executions` row as its record, for any store that reads executions alongside its own rows. */\nexport function sqliteExecutionRecord(row: SqliteExecutionRow): ExecutionRecord {\n return executionRecordFromStorageRow(toStorageRow(row))\n}\n\nfunction toStorageRow(row: SqliteExecutionRow): ExecutionStorageRow {\n return {\n projectId: row.project_id,\n id: row.id,\n executorKind: row.executor_kind,\n executorId: row.executor_id,\n sourceKind: row.source_kind,\n sourceId: row.source_id,\n requestedByUserId: row.requested_by_user_id,\n requestedByServiceAccountId: row.requested_by_service_account_id,\n requesterGroupIds: JSON.parse(row.requester_group_ids),\n correlationId: row.correlation_id,\n parentExecutionId: row.parent_execution_id,\n authorityKind: row.authority_kind,\n authorityUserId: row.authority_user_id,\n authorityServiceAccountId: row.authority_service_account_id,\n authoritySessionId: row.authority_session_id,\n authorityAccessTokenId: row.authority_access_token_id,\n authorityPrimitiveKind: row.authority_primitive_kind,\n authorityPrimitiveId: row.authority_primitive_id,\n authorityKernelOperation: row.authority_kernel_operation,\n authorityDelegationKind: row.authority_delegation_kind,\n authorityDelegationId: row.authority_delegation_id,\n authorityDelegationSessionId: row.authority_delegation_session_id,\n createdAt: new Date(row.created_at),\n }\n}\n\nfunction isDuplicateExecutionError(error: unknown): boolean {\n return (\n error instanceof Error &&\n error.message.includes(\"UNIQUE constraint failed: executions.project_id, executions.id\")\n )\n}\n\nexport interface SqliteExecutionRow {\n readonly project_id: string\n readonly id: string\n readonly executor_kind: ExecutionStorageRow[\"executorKind\"]\n readonly executor_id: string\n readonly source_kind: ExecutionStorageRow[\"sourceKind\"]\n readonly source_id: string\n readonly requested_by_user_id: string | null\n readonly requested_by_service_account_id: string | null\n readonly requester_group_ids: string\n readonly correlation_id: string\n readonly parent_execution_id: string | null\n readonly authority_kind: ExecutionStorageRow[\"authorityKind\"]\n readonly authority_user_id: string | null\n readonly authority_service_account_id: string | null\n readonly authority_session_id: string | null\n readonly authority_access_token_id: string | null\n readonly authority_primitive_kind: ExecutionStorageRow[\"authorityPrimitiveKind\"]\n readonly authority_primitive_id: string | null\n readonly authority_kernel_operation: ExecutionStorageRow[\"authorityKernelOperation\"]\n readonly authority_delegation_kind: ExecutionStorageRow[\"authorityDelegationKind\"]\n readonly authority_delegation_id: string | null\n readonly authority_delegation_session_id: string | null\n readonly created_at: string\n}\n",
41
+ "import type { Database } from \"bun:sqlite\"\nimport {\n compareExecutionCreation,\n type ExecutionStorageRow,\n executionRecordFromStorageRow,\n executionRecordToStorageRow,\n prepareExecutionRecord,\n} from \"@sixb/core/internal/execution-storage\"\nimport type {\n CreateExecutionInput,\n ExecutionDescendant,\n ExecutionRecord,\n ExecutionStorage,\n ListExecutionDescendantsInput,\n ListSessionExecutionsInput,\n SessionExecutions,\n ShareSessionStorage,\n} from \"@sixb/core/storage\"\nimport { ExecutionStorageError } from \"@sixb/core/storage\"\nimport type { SqliteAuthStorage } from \"./auth-storage\"\n\nexport class SqliteExecutionStorage implements ExecutionStorage {\n constructor(\n private readonly db: Database,\n private readonly auth: SqliteAuthStorage,\n private readonly shareSessions: Pick<ShareSessionStorage, \"getById\">\n ) {}\n\n async create(input: CreateExecutionInput): Promise<ExecutionRecord> {\n const record = await prepareExecutionRecord(input, {\n auth: this.auth,\n getExecution: (params) => this.getById(params),\n getShareSession: (params) => this.shareSessions.getById(params),\n })\n const row = executionRecordToStorageRow(record)\n\n try {\n this.db\n .query(\n `\n INSERT INTO executions (\n project_id,\n id,\n executor_kind,\n executor_id,\n source_kind,\n source_id,\n requested_by_user_id,\n requested_by_service_account_id,\n requester_group_ids,\n correlation_id,\n parent_execution_id,\n authority_kind,\n authority_user_id,\n authority_service_account_id,\n authority_session_id,\n authority_access_token_id,\n authority_primitive_kind,\n authority_primitive_id,\n authority_kernel_operation,\n authority_delegation_kind,\n authority_delegation_id,\n authority_delegation_session_id,\n created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n row.projectId,\n row.id,\n row.executorKind,\n row.executorId,\n row.sourceKind,\n row.sourceId,\n row.requestedByUserId,\n row.requestedByServiceAccountId,\n JSON.stringify(row.requesterGroupIds),\n row.correlationId,\n row.parentExecutionId,\n row.authorityKind,\n row.authorityUserId,\n row.authorityServiceAccountId,\n row.authoritySessionId,\n row.authorityAccessTokenId,\n row.authorityPrimitiveKind,\n row.authorityPrimitiveId,\n row.authorityKernelOperation,\n row.authorityDelegationKind,\n row.authorityDelegationId,\n row.authorityDelegationSessionId,\n row.createdAt.toISOString()\n )\n } catch (error) {\n if (isDuplicateExecutionError(error)) {\n throw new ExecutionStorageError(\n \"duplicate_execution\",\n `[SixbSqlite] Execution '${record.id}' already exists in project '${record.projectId}'.`,\n { cause: error }\n )\n }\n throw error\n }\n\n return executionRecordFromStorageRow(row)\n }\n\n async getById(params: {\n readonly projectId: string\n readonly id: string\n }): Promise<ExecutionRecord | null> {\n const row = this.db\n .query(\n `\n SELECT *\n FROM executions\n WHERE project_id = ? AND id = ?\n `\n )\n .get(params.projectId, params.id) as SqliteExecutionRow | null\n\n return row ? sqliteExecutionRecord(row) : null\n }\n\n async listBySession(input: ListSessionExecutionsInput): Promise<SessionExecutions> {\n const sessionColumn =\n input.session.type === \"user\" ? \"authority_session_id\" : \"authority_delegation_session_id\"\n\n // The queue is ordered by depth, so the walk takes roots, then their children level by level,\n // the earliest first, and the limit stops it: a large tree costs no more than the rows\n // returned. CROSS JOIN keeps the walk driven by the rows found: statistics taken on a small\n // ledger choose to scan every child.\n const rows = this.db\n .query(\n `\n WITH RECURSIVE tree AS (\n SELECT roots.*, 0 AS depth\n FROM (\n SELECT *\n FROM executions\n WHERE project_id = ?\n AND ${sessionColumn} = ?\n AND parent_execution_id IS NULL\n AND created_at >= ?\n AND created_at < ?\n ORDER BY created_at, id\n LIMIT ?\n ) roots\n UNION ALL\n SELECT child.*, tree.depth + 1\n FROM tree\n CROSS JOIN executions child\n ON child.project_id = tree.project_id\n AND child.parent_execution_id = tree.id\n ORDER BY depth, created_at, id\n LIMIT ?\n )\n SELECT * FROM tree\n `\n )\n .all(\n input.projectId,\n input.session.id,\n input.from.toISOString(),\n input.to.toISOString(),\n input.limit + 1,\n input.limit + 1\n ) as SqliteExecutionRow[]\n\n // Rows come out in walk order, so the first `limit` are the ones the contract keeps.\n const kept = rows.slice(0, input.limit).map(sqliteExecutionRecord)\n return {\n executions: kept.sort(compareExecutionCreation),\n truncated: rows.length > input.limit,\n }\n }\n\n async listDescendants(\n input: ListExecutionDescendantsInput\n ): Promise<readonly ExecutionDescendant[]> {\n if (input.executionIds.length === 0) return []\n const ids = [...new Set(input.executionIds)]\n\n // UNION, not UNION ALL: an execution asked about may sit below another one asked about, and\n // the walk would otherwise reach what it caused twice.\n const rows = this.db\n .query(\n `\n WITH RECURSIVE tree(id, parent_id) AS (\n SELECT child.id, child.parent_execution_id\n FROM executions child\n WHERE child.project_id = ?\n AND child.parent_execution_id IN (SELECT value FROM json_each(?))\n UNION\n SELECT child.id, child.parent_execution_id\n FROM tree\n CROSS JOIN executions child\n ON child.project_id = ?\n AND child.parent_execution_id = tree.id\n )\n SELECT id, parent_id\n FROM tree\n WHERE id NOT IN (SELECT value FROM json_each(?))\n ORDER BY id\n `\n )\n .all(input.projectId, JSON.stringify(ids), input.projectId, JSON.stringify(ids)) as {\n id: string\n parent_id: string\n }[]\n\n return rows.map((row) => ({ id: row.id, parentId: row.parent_id }))\n }\n}\n\n/** An `executions` row as its record, for any store that reads executions alongside its own rows. */\nexport function sqliteExecutionRecord(row: SqliteExecutionRow): ExecutionRecord {\n return executionRecordFromStorageRow(toStorageRow(row))\n}\n\nfunction toStorageRow(row: SqliteExecutionRow): ExecutionStorageRow {\n return {\n projectId: row.project_id,\n id: row.id,\n executorKind: row.executor_kind,\n executorId: row.executor_id,\n sourceKind: row.source_kind,\n sourceId: row.source_id,\n requestedByUserId: row.requested_by_user_id,\n requestedByServiceAccountId: row.requested_by_service_account_id,\n requesterGroupIds: JSON.parse(row.requester_group_ids),\n correlationId: row.correlation_id,\n parentExecutionId: row.parent_execution_id,\n authorityKind: row.authority_kind,\n authorityUserId: row.authority_user_id,\n authorityServiceAccountId: row.authority_service_account_id,\n authoritySessionId: row.authority_session_id,\n authorityAccessTokenId: row.authority_access_token_id,\n authorityPrimitiveKind: row.authority_primitive_kind,\n authorityPrimitiveId: row.authority_primitive_id,\n authorityKernelOperation: row.authority_kernel_operation,\n authorityDelegationKind: row.authority_delegation_kind,\n authorityDelegationId: row.authority_delegation_id,\n authorityDelegationSessionId: row.authority_delegation_session_id,\n createdAt: new Date(row.created_at),\n }\n}\n\nfunction isDuplicateExecutionError(error: unknown): boolean {\n return (\n error instanceof Error &&\n error.message.includes(\"UNIQUE constraint failed: executions.project_id, executions.id\")\n )\n}\n\nexport interface SqliteExecutionRow {\n readonly project_id: string\n readonly id: string\n readonly executor_kind: ExecutionStorageRow[\"executorKind\"]\n readonly executor_id: string\n readonly source_kind: ExecutionStorageRow[\"sourceKind\"]\n readonly source_id: string\n readonly requested_by_user_id: string | null\n readonly requested_by_service_account_id: string | null\n readonly requester_group_ids: string\n readonly correlation_id: string\n readonly parent_execution_id: string | null\n readonly authority_kind: ExecutionStorageRow[\"authorityKind\"]\n readonly authority_user_id: string | null\n readonly authority_service_account_id: string | null\n readonly authority_session_id: string | null\n readonly authority_access_token_id: string | null\n readonly authority_primitive_kind: ExecutionStorageRow[\"authorityPrimitiveKind\"]\n readonly authority_primitive_id: string | null\n readonly authority_kernel_operation: ExecutionStorageRow[\"authorityKernelOperation\"]\n readonly authority_delegation_kind: ExecutionStorageRow[\"authorityDelegationKind\"]\n readonly authority_delegation_id: string | null\n readonly authority_delegation_session_id: string | null\n readonly created_at: string\n}\n",
39
42
  "import type { Database } from \"bun:sqlite\"\nimport { parseFileDownloadGrantRow } from \"@sixb/core/internal/storage\"\nimport type {\n DeleteExpiredFileDownloadGrantsInput,\n FileDownloadGrantRecord,\n FileDownloadGrantStorage,\n FindFileDownloadGrantInput,\n RevokeFileDownloadGrantInput,\n} from \"@sixb/core/storage\"\nimport type { SqliteStoreConnection } from \"./transactions\"\n\nconst GRANT_COLUMNS = `\n project_id AS projectId, id, token_hash AS tokenHash, file, execution_id AS executionId,\n created_at AS createdAt, expires_at AS expiresAt, revoked_at AS revokedAt\n`\n\nexport class SqliteFileDownloadGrantStorage implements FileDownloadGrantStorage {\n private readonly db: Database\n\n constructor(connection: SqliteStoreConnection) {\n this.db = connection.db\n }\n\n async create(record: FileDownloadGrantRecord): Promise<void> {\n this.db\n .query(\n `INSERT INTO file_download_grants (\n project_id, id, token_hash, file, execution_id, created_at, expires_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?)`\n )\n .run(\n record.projectId,\n record.id,\n record.tokenHash,\n JSON.stringify(record.file),\n record.executionId,\n record.createdAt.toISOString(),\n record.expiresAt.toISOString()\n )\n }\n\n async findByTokenHash(\n input: FindFileDownloadGrantInput\n ): Promise<FileDownloadGrantRecord | null> {\n const row = this.db\n .query(\n `SELECT ${GRANT_COLUMNS} FROM file_download_grants WHERE project_id = ? AND token_hash = ?`\n )\n .get(input.projectId, input.tokenHash)\n return row ? parseFileDownloadGrantRow(row as Record<string, unknown>) : null\n }\n\n async revoke(input: RevokeFileDownloadGrantInput): Promise<FileDownloadGrantRecord | null> {\n const row = this.db\n .query(\n `UPDATE file_download_grants SET revoked_at = COALESCE(revoked_at, ?)\n WHERE project_id = ? AND id = ?\n RETURNING ${GRANT_COLUMNS}`\n )\n .get(input.revokedAt.toISOString(), input.projectId, input.id)\n return row ? parseFileDownloadGrantRow(row as Record<string, unknown>) : null\n }\n\n async deleteExpired(input: DeleteExpiredFileDownloadGrantsInput): Promise<number> {\n return this.db\n .query(\n `DELETE FROM file_download_grants WHERE rowid IN (\n SELECT rowid FROM file_download_grants\n WHERE project_id = ? AND expires_at < ?\n ORDER BY expires_at\n LIMIT ?\n )`\n )\n .run(input.projectId, input.expiredBefore.toISOString(), input.limit).changes\n }\n}\n",
40
43
  "import type { Database } from \"bun:sqlite\"\nimport {\n DurableFileUploadSessions,\n type FileUploadSessionPersistence,\n type FileUploadSessionPersistenceBackend,\n fileUploadSessionReapAt,\n parseFileUploadSessionRow,\n} from \"@sixb/core/internal/file-upload-session-storage-provider\"\nimport type { FileUploadSession, ListAbandonedFileUploadSessionsInput } from \"@sixb/core/storage\"\nimport { isUniqueConstraintError } from \"./storage-errors\"\nimport { runImmediateTransactionAsync, type SqliteStoreConnection } from \"./transactions\"\n\nexport class SqliteFileUploadSessionStorage extends DurableFileUploadSessions {\n constructor(connection: SqliteStoreConnection) {\n super(new SqliteFileUploadSessionBackend(connection.db))\n }\n}\n\nclass SqliteFileUploadSessionBackend implements FileUploadSessionPersistenceBackend {\n private readonly persistence: FileUploadSessionPersistence\n\n constructor(private readonly db: Database) {\n this.persistence = new SqliteFileUploadSessionPersistence(db)\n }\n\n read<T>(run: (persistence: FileUploadSessionPersistence) => Promise<T>): Promise<T> {\n return run(this.persistence)\n }\n\n transaction<T>(run: (persistence: FileUploadSessionPersistence) => Promise<T>): Promise<T> {\n return runImmediateTransactionAsync(this.db, () => run(this.persistence))\n }\n}\n\nclass SqliteFileUploadSessionPersistence implements FileUploadSessionPersistence {\n constructor(private readonly db: Database) {}\n\n async now(): Promise<Date> {\n const row = this.db.query(\"SELECT strftime('%Y-%m-%dT%H:%M:%fZ', 'now') AS now\").get() as {\n readonly now: string\n }\n return new Date(row.now)\n }\n\n async insert(session: FileUploadSession): Promise<boolean> {\n try {\n this.db\n .query(\n `INSERT INTO file_upload_sessions (\n id, project_id, owner_principal_type, owner_principal_id, strategy, status, file_name,\n media_type, logical_path, expected_size_bytes, expected_digest, provider_upload, signed_parts, file_ref,\n created_at, expires_at, completed_at, aborted_at, reap_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`\n )\n .run(\n session.id,\n session.projectId,\n session.principal.type,\n session.principal.id,\n session.strategy,\n session.status,\n session.fileName ?? null,\n session.mediaType ?? null,\n session.logicalPath ?? null,\n session.expectedSizeBytes ?? null,\n session.expectedDigest ?? null,\n ...mutableColumns(session)\n )\n return true\n } catch (error) {\n if (isUniqueConstraintError(error)) return false\n throw error\n }\n }\n\n async get(uploadId: string): Promise<FileUploadSession | null> {\n const row = this.db.query(`${SELECT_SESSION} WHERE id = ?`).get(uploadId)\n return row ? parseFileUploadSessionRow(row as Record<string, unknown>) : null\n }\n\n async update(session: FileUploadSession): Promise<void> {\n this.db\n .query(\n `UPDATE file_upload_sessions\n SET status = ?, provider_upload = ?, signed_parts = ?, file_ref = ?, created_at = ?,\n expires_at = ?, completed_at = ?, aborted_at = ?, reap_at = ?\n WHERE id = ?`\n )\n .run(session.status, ...mutableColumns(session), session.id)\n }\n\n async listAbandoned(\n input: ListAbandonedFileUploadSessionsInput\n ): Promise<readonly FileUploadSession[]> {\n const rows = this.db\n .query(\n `${SELECT_SESSION}\n WHERE project_id = ? AND status = 'pending' AND provider_upload IS NOT NULL\n AND expires_at <= ?\n ORDER BY expires_at, id\n LIMIT ?`\n )\n .all(input.projectId, input.now.toISOString(), input.limit)\n return rows.map((row) => parseFileUploadSessionRow(row as Record<string, unknown>))\n }\n\n async deleteReapable(now: Date): Promise<number> {\n return this.db\n .query(\"DELETE FROM file_upload_sessions WHERE reap_at IS NOT NULL AND reap_at <= ?\")\n .run(now.toISOString()).changes\n }\n}\n\nconst SELECT_SESSION = `\n SELECT id, project_id AS projectId, owner_principal_type AS ownerPrincipalType,\n owner_principal_id AS ownerPrincipalId, strategy, status,\n file_name AS fileName, media_type AS mediaType, logical_path AS logicalPath,\n expected_size_bytes AS expectedSizeBytes, expected_digest AS expectedDigest,\n provider_upload AS providerUpload, signed_parts AS signedParts, file_ref AS fileRef,\n created_at AS createdAt, expires_at AS expiresAt, completed_at AS completedAt,\n aborted_at AS abortedAt\n FROM file_upload_sessions`\n\n/** Columns a transition may change, in insert/update order after `expected_digest`/`status`. */\nfunction mutableColumns(session: FileUploadSession) {\n return [\n session.providerUpload === undefined ? null : JSON.stringify(session.providerUpload),\n JSON.stringify(session.signedParts),\n session.fileRef === undefined ? null : JSON.stringify(session.fileRef),\n session.createdAt.toISOString(),\n session.expiresAt.toISOString(),\n session.completedAt?.toISOString() ?? null,\n session.abortedAt?.toISOString() ?? null,\n fileUploadSessionReapAt(session)?.toISOString() ?? null,\n ] as const\n}\n",
41
- "import type { Database } from \"bun:sqlite\"\nimport { hasVectorProfile } from \"@sixb/core/internal/query\"\nimport type {\n CompiledSelectedObjectReadScope,\n CountObjectsInput,\n CountObjectsResult,\n ExistsObjectsInput,\n ExistsObjectsResult,\n FacetObjectsInput,\n FacetObjectsResult,\n LinkBatchKey,\n LinkDirection,\n ObjectBatchKey,\n ObjectLinkRow,\n ObjectQueryCapabilities,\n ObjectReadExecutionLimits,\n ObjectReadStorage,\n ObjectRow,\n ObjectStorage,\n QueryObjectLinksInput,\n QueryObjectLinksResult,\n QueryObjectsInput,\n QueryObjectsResult,\n} from \"@sixb/core/storage\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n runDeferredReadTransaction,\n type SqliteStoreConnection,\n} from \"../transactions\"\nimport { DEFAULT_OBJECT_QUERY_SOURCE } from \"./query-compiler\"\nimport { assertLinkQueryLimit, SqliteObjectReader } from \"./reader\"\nimport { type DatabaseRow, type LinkDatabaseRow, rowToLink, rowToObject } from \"./rows\"\nimport { createSqliteSelectedReader } from \"./selected-reader\"\n\nexport interface SqliteObjectStorageOptions {\n /** Path to SQLite database file. Defaults to ':memory:' for in-memory database. */\n path?: string\n /** Internal shared connection used by bundled SqliteStorage. */\n connection?: SqliteStoreConnection\n}\n\nconst SQLITE_OBJECT_QUERY_CAPABILITIES: ObjectQueryCapabilities = {\n queryObjects: true,\n countObjects: true,\n existsObjects: true,\n facetObjects: true,\n nodes: {\n start: true,\n refs: true,\n filter: true,\n text: true,\n vector: true,\n sort: true,\n limit: true,\n page: true,\n traverse: true,\n set: true,\n project: true,\n expand: true,\n },\n predicateOps: {\n and: true,\n or: true,\n not: true,\n eq: true,\n neq: true,\n lt: true,\n lte: true,\n gt: true,\n gte: true,\n in: true,\n exists: true,\n contains: true,\n },\n sortKinds: {\n property: true,\n },\n traversalDirections: {\n outgoing: true,\n incoming: true,\n },\n setOps: {\n union: true,\n intersect: true,\n subtract: true,\n },\n scalarOperations: {\n string: { equality: true, ordering: true },\n uuid: { equality: true, ordering: true },\n boolean: { equality: true },\n integer: { equality: true, ordering: true },\n double: { equality: true, ordering: true },\n decimal: { equality: true },\n date: { equality: true, ordering: true },\n timestamp: { equality: true, ordering: true },\n userRef: { equality: true },\n },\n limits: {\n totalCount: true,\n stablePageTokens: true,\n },\n notes: [\n \"SQLite object query pushdown supports start/refs/filter/text/sort/limit/page/traverse/set/project/expand over JSON properties and object links.\",\n \"expand hydrates linked objects in-database (top-N per parent via row_number() + json_group_array); core resolves each expansion's cardinality before pushdown, and a mixed/unresolved one stays on the fallback.\",\n \"Ordered decimal predicates and sorting use the bounded core fallback because SQLite has no native exact decimal type; canonical decimal equality remains pushdown-safe.\",\n \"Relevance sorting and unresolved start.includeSubtypes remain planner fallback or rejection cases.\",\n ],\n}\n\n/**\n * SQLite-based ObjectStorage implementation.\n *\n * Stores object projections and links. V1 object-query IR pushdown covers the\n * scalar JSON-property and link-traversal subset declared by queryCapabilities().\n */\nexport class SqliteObjectStorage implements ObjectStorage {\n private readonly connection: SqliteStoreConnection\n private readonly db: Database\n private readonly reader: SqliteObjectReader\n\n constructor(options: SqliteObjectStorageOptions = {}) {\n this.connection = openSqliteStoreConnection(options)\n this.db = this.connection.db\n this.reader = new SqliteObjectReader(this.db, DEFAULT_OBJECT_QUERY_SOURCE)\n }\n\n queryCapabilities(): ObjectQueryCapabilities {\n return SQLITE_OBJECT_QUERY_CAPABILITIES\n }\n\n createSelectedReadScope(params: {\n projectId: string\n scope: CompiledSelectedObjectReadScope\n limits: ObjectReadExecutionLimits\n }): ObjectReadStorage {\n return createSqliteSelectedReader(this.db, params, () => this.queryCapabilities())\n }\n\n async queryObjects(params: QueryObjectsInput): Promise<QueryObjectsResult> {\n if (hasVectorProfile(params.query))\n return runDeferredReadTransaction(this.db, () => this.reader.queryObjects(params))\n return this.reader.queryObjects(params)\n }\n\n async countObjects(params: CountObjectsInput): Promise<CountObjectsResult> {\n if (hasVectorProfile(params.query))\n return runDeferredReadTransaction(this.db, () => this.reader.countObjects(params))\n return this.reader.countObjects(params)\n }\n\n async existsObjects(params: ExistsObjectsInput): Promise<ExistsObjectsResult> {\n if (hasVectorProfile(params.query))\n return runDeferredReadTransaction(this.db, () => this.reader.existsObjects(params))\n return this.reader.existsObjects(params)\n }\n\n async facetObjects(params: FacetObjectsInput): Promise<FacetObjectsResult> {\n return runDeferredReadTransaction(this.db, () => this.reader.facetObjects(params))\n }\n\n async getByPrimaryId(params: {\n projectId: string\n objectTypeId: string\n primaryId: string\n }): Promise<ObjectRow | null> {\n return this.reader.getByPrimaryId(params)\n }\n\n async selectsObjectProperties(\n params: Parameters<ObjectReadStorage[\"selectsObjectProperties\"]>[0]\n ): Promise<readonly boolean[]> {\n return this.reader.selectsObjectProperties(params)\n }\n\n async listLinks(params: {\n projectId: string\n objectTypeId: string\n objectId: string\n linkId?: string\n direction?: LinkDirection\n }): Promise<readonly ObjectLinkRow[]> {\n return this.reader.listLinks(params)\n }\n\n async getByPrimaryIdBatch(params: {\n projectId: string\n items: readonly { objectTypeId: string; primaryId: string }[]\n }): Promise<Map<ObjectBatchKey, ObjectRow>> {\n return this.reader.getByPrimaryIdBatch(params)\n }\n\n async listLinksBatch(params: {\n projectId: string\n direction?: LinkDirection\n items: readonly { objectTypeId: string; objectId: string; linkId: string }[]\n }): Promise<Map<LinkBatchKey, ObjectLinkRow[]>> {\n return this.reader.listLinksBatch(params)\n }\n\n async queryLinks(params: QueryObjectLinksInput): Promise<QueryObjectLinksResult> {\n assertLinkQueryLimit(params.limit)\n return this.reader.queryLinks(params)\n }\n\n async listIncidentLinksBatch(params: {\n projectId: string\n items: readonly { objectTypeId: string; objectId: string }[]\n }): Promise<readonly ObjectLinkRow[]> {\n if (params.items.length === 0) return []\n\n const rows = this.db\n .query(\n `\n WITH requested AS (\n SELECT\n json_extract(value, '$.objectTypeId') AS object_type_id,\n json_extract(value, '$.objectId') AS object_id\n FROM json_each(?)\n )\n SELECT link.*\n FROM links AS link\n JOIN requested\n ON requested.object_type_id = link.source_type_id\n AND requested.object_id = link.source_id\n WHERE link.project_id = ?\n UNION\n SELECT link.*\n FROM links AS link\n JOIN requested\n ON requested.object_type_id = link.target_type_id\n AND requested.object_id = link.target_id\n WHERE link.project_id = ?\n `\n )\n .all(JSON.stringify(params.items), params.projectId, params.projectId) as LinkDatabaseRow[]\n\n return rows.map((row) => rowToLink(row))\n }\n\n async listByPrimaryIdPage(params: {\n projectId: string\n objectTypeId: string\n afterPrimaryId?: string\n limit: number\n }): Promise<{ objects: readonly ObjectRow[]; nextPrimaryId?: string }> {\n assertReconciliationPageLimit(params.limit)\n // A cursor written as `? IS NULL OR …` cannot seek, so every page would rescan from the start.\n const cursor = params.afterPrimaryId === undefined ? [] : [params.afterPrimaryId]\n const rows = this.db\n .query(\n `\n SELECT * FROM objects\n WHERE project_id = ? AND object_type_id = ?\n ${cursor.length > 0 ? \"AND primary_id > ?\" : \"\"}\n ORDER BY primary_id ASC\n LIMIT ?\n `\n )\n .all(params.projectId, params.objectTypeId, ...cursor, params.limit + 1) as DatabaseRow[]\n const hasMore = rows.length > params.limit\n const objects = rows.slice(0, params.limit).map((row) => rowToObject(row))\n const last = objects.at(-1)\n return {\n objects,\n ...(hasMore && last ? { nextPrimaryId: last.primaryId } : {}),\n }\n }\n\n async list(params: {\n projectId: string\n objectTypeId?: string | readonly string[]\n primaryIdPrefix?: string\n primaryIdSuffix?: string\n updatedAfter?: Date\n updatedBefore?: Date\n createdAfter?: Date\n createdBefore?: Date\n limit?: number\n offset?: number\n orderBy?: \"createdAt\" | \"updatedAt\" | \"primaryId\"\n order?: \"asc\" | \"desc\"\n }): Promise<{ objects: readonly ObjectRow[]; hasMore: boolean; total: number }> {\n return this.reader.list(params)\n }\n\n /** Close the connection only when this provider owns it. */\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n}\n\nfunction assertReconciliationPageLimit(limit: number): void {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error(\"Object reconciliation page limit must be a positive safe integer.\")\n }\n}\n",
42
- "import {\n type ObjectExpansion,\n type ObjectQuery,\n ObjectQueryExecutionError,\n type ObjectQueryPredicate,\n type ObjectQuerySetOperation,\n type ObjectQuerySortField,\n} from \"@sixb/core\"\nimport {\n hasVectorProfile,\n isVectorProfileQuery,\n normalizeVector,\n vectorSearchCandidateLimit,\n} from \"@sixb/core/internal/query\"\nimport { encodeSqliteVector } from \"../vector-encoding\"\n\nexport type SqliteValue = string | number | bigint | boolean | null | Uint8Array\n\nexport interface SqliteObjectQueryPageRow {\n object_type_id: string\n primary_id: string\n properties: string\n _cursor_properties?: string\n}\n\nexport interface CompiledObjectQuery {\n vectorProbe?: {\n sql: string\n args: SqliteValue[]\n limit: number\n /** Maximum returned rows and total before the outermost limit, respectively. */\n rowLimit: number\n totalLimit: number\n }\n sql: string\n args: SqliteValue[]\n totalSql: string\n totalArgs: SqliteValue[]\n order: CompiledOrder\n hasMoreProbe?: CompiledHasMoreProbe\n hasMore(rowCount: number, total?: number): boolean\n trimRows<T>(rows: readonly T[]): readonly T[]\n nextPageToken(rows: readonly SqliteObjectQueryPageRow[], rowCount: number): string | undefined\n}\n\ninterface CompiledHasMoreProbe {\n sql: string\n args: SqliteValue[]\n hasMore(rowCount: number): boolean\n}\n\ninterface CompileContext {\n probeLimit: boolean\n source: SqliteObjectQuerySource\n}\n\ninterface CompiledPredicate {\n sql: string\n args: SqliteValue[]\n}\n\ninterface CompiledOrder {\n sql: string\n args: SqliteValue[]\n fields: readonly CompiledOrderField[]\n propertyColumn: string\n}\n\ntype CompiledOrderField =\n | {\n kind: \"property\"\n propertyId: string\n direction: \"asc\" | \"desc\"\n }\n | {\n kind: \"column\"\n column: \"object_type_id\" | \"primary_id\" | \"_vector_score\"\n binary?: boolean\n direction: \"asc\" | \"desc\"\n }\n\ninterface EncodedPageToken {\n version: 1\n order: readonly string[]\n values: readonly EncodedCursorValue[]\n}\n\ninterface EncodedCursorValue {\n nullish: boolean\n value?: unknown\n}\n\nconst PAGE_TOKEN_PREFIX = \"keyset:\"\n\n// Fallback fanout cap for a \"many\" expansion that arrives without an explicit\n// limit. The core executor normally bakes a limit in before pushdown; this only\n// bounds the degenerate uncapped case. Mirrors the PostgreSQL compiler.\nconst DEFAULT_EXPANSION_FANOUT = 1_000\n\nexport function compileObjectQuery(\n projectId: string,\n query: ObjectQuery,\n options: { includeTotal?: boolean; source?: SqliteObjectQuerySource } = {}\n): CompiledObjectQuery {\n if (hasVectorProfile(query) && !isVectorProfileQuery(query)) {\n throw new ObjectQueryExecutionError(\n \"unsupported_vector_composition\",\n \"Vector search supports one profile with filters, traversals or sets before ranking and limit/project after.\"\n )\n }\n const source = options.source ?? DEFAULT_OBJECT_QUERY_SOURCE\n const ctx: CompileContext = { probeLimit: options.includeTotal === false, source }\n return source.wrapQuery(compileObjectQueryInternal(projectId, query, ctx))\n}\n\n/** Physical relations used by the object-query compiler. */\nexport interface SqliteObjectQuerySource {\n readonly objectsTable: string\n readonly linksTable: string\n readonly objectPropertyPermissionsTable?: string\n /** Wrap a terminal SELECT without its own WITH clause; the selected source owns the only WITH. */\n wrapStatement(\n sql: string,\n args?: readonly SqliteValue[]\n ): {\n readonly sql: string\n readonly args: readonly SqliteValue[]\n }\n wrapQuery(query: CompiledObjectQuery): CompiledObjectQuery\n}\n\nexport const DEFAULT_OBJECT_QUERY_SOURCE: SqliteObjectQuerySource = {\n objectsTable: \"objects\",\n linksTable: \"links\",\n wrapStatement: (sql, args = []) => ({ sql, args: [...args] }),\n wrapQuery: (query) => query,\n}\n\nfunction exactContext(ctx: CompileContext): CompileContext {\n return ctx.probeLimit ? { ...ctx, probeLimit: false } : ctx\n}\n\nfunction compileObjectQueryInternal(\n projectId: string,\n query: ObjectQuery,\n ctx: CompileContext\n): CompiledObjectQuery {\n switch (query.kind) {\n case \"rerank\":\n throw new ObjectQueryExecutionError(\n \"reranking_requires_runtime\",\n \"Reranking must execute in the model runtime, not storage.\"\n )\n case \"start\":\n return compileStart(projectId, query, ctx)\n case \"refs\":\n return compileRefs(projectId, query, ctx)\n case \"filter\":\n return compileFilter(projectId, query.input, query.predicate, ctx)\n case \"sort\":\n return compileSort(projectId, query.input, query.fields, ctx)\n case \"limit\":\n return compileLimit(projectId, query.input, query.limit, ctx)\n case \"page\":\n return compilePage(projectId, query.input, query.pageSize, query.pageToken, ctx)\n case \"traverse\":\n return compileTraversal(\n projectId,\n query.input,\n query.linkId,\n query.direction,\n query.sourceObjectTypeId,\n ctx\n )\n case \"set\":\n return compileSet(projectId, query.op, query.inputs, ctx)\n case \"project\":\n return compileProject(projectId, query.input, query.properties, ctx)\n case \"text\":\n return compileText(\n projectId,\n query.input,\n query.query,\n query.fields,\n query.fieldsByObjectType,\n ctx\n )\n case \"expand\":\n return compileExpand(projectId, query.input, query.expansions, ctx)\n case \"vector\":\n return compileVector(projectId, query, ctx)\n }\n}\n\nfunction compileVector(\n projectId: string,\n query: Extract<ObjectQuery, { kind: \"vector\" }>,\n ctx: CompileContext\n): CompiledObjectQuery {\n if (\n typeof query.vector === \"string\" ||\n !isVectorProfileQuery(query) ||\n !query.configuration ||\n !Number.isSafeInteger(query.k) ||\n query.k < 1 ||\n query.k > 1000 ||\n query.vector.length < 1 ||\n query.vector.length > 16000\n ) {\n throw new ObjectQueryExecutionError(\n \"invalid_vector_query\",\n \"A validated named vector profile is required.\"\n )\n }\n const input = compileObjectQueryInternal(projectId, query.input, exactContext(ctx))\n const permissions = ctx.source.objectPropertyPermissionsTable\n const permissionJoin = permissions\n ? `CROSS JOIN (\n SELECT project_id, object_type_id, primary_id, json_group_array(property_id) AS property_ids\n FROM ${permissions}\n GROUP BY project_id, object_type_id, primary_id\n ) AS vector_permissions ON vector_permissions.project_id = vectors.project_id\n AND vector_permissions.object_type_id = vectors.object_type_id\n AND vector_permissions.primary_id = vectors.primary_id`\n : \"\"\n const authorized = permissions\n ? `AND NOT EXISTS (\n SELECT 1 FROM json_each(vectors.source) AS required\n WHERE required.value NOT IN (SELECT value FROM json_each(vector_permissions.property_ids))\n )`\n : \"\"\n const candidates = `FROM (${input.sql}) AS input\n CROSS JOIN object_vectors AS vectors ON vectors.project_id = input.project_id\n AND vectors.object_type_id = input.object_type_id AND vectors.primary_id = input.primary_id\n ${permissionJoin}\n WHERE vectors.profile = ? AND vectors.configuration = ?\n AND length(vectors.embedding) / 4 = ? ${authorized}`\n const candidateArgs = [...input.args, query.profile!, query.configuration, query.vector.length]\n // Bound distance work, not just returned rows. Exceeding the envelope fails before ranking.\n const limit = vectorSearchCandidateLimit(query.vector.length)\n const values = normalizeVector(query.vector, query.vector.length)\n const order = compileOrder([\n { kind: \"column\", column: \"_vector_score\", direction: \"desc\" },\n ...identityOrderFields().map((field) => ({ ...field, binary: true })),\n ])\n const rankedOrder = compileOrder(order.fields, \"ranked\")\n // Materialize only bounded, authorized candidates once. CASE prevents distance evaluation\n // above the envelope; the reader rejects the count before exposing any rows or scores.\n const sql = `SELECT stored.project_id, stored.object_type_id, stored.primary_id,\n stored.properties, stored.properties AS _cursor_properties,\n stored.created_at, stored.updated_at, stored.version, stored.last_commit_id,\n ranked._vector_candidate_count, ranked._vector_score\n FROM (\n WITH _sixb_vector_candidates AS MATERIALIZED (\n SELECT input.project_id, input.object_type_id, input.primary_id,\n vectors.embedding AS _vector_embedding ${candidates} LIMIT ?\n ), _sixb_vector_budget AS (\n SELECT COUNT(*) AS _vector_candidate_count FROM _sixb_vector_candidates\n )\n SELECT input.project_id, input.object_type_id, input.primary_id, budget._vector_candidate_count,\n CASE WHEN budget._vector_candidate_count <= ?\n THEN max(-1, min(1, 1 - vec_distance_cosine(input._vector_embedding, ?)))\n END AS _vector_score\n FROM _sixb_vector_candidates AS input CROSS JOIN _sixb_vector_budget AS budget\n ORDER BY ${order.sql} LIMIT ?\n ) AS ranked CROSS JOIN ${ctx.source.objectsTable} AS stored\n ON stored.project_id = ranked.project_id AND stored.object_type_id = ranked.object_type_id\n AND stored.primary_id = ranked.primary_id\n ORDER BY ${rankedOrder.sql}`\n const args = [...candidateArgs, limit + 1, limit, encodeSqliteVector(values), query.k]\n return {\n sql,\n args,\n // Top-k cardinality depends on eligibility, not distances or ranking.\n totalSql: `SELECT COUNT(*) AS total FROM (SELECT 1 ${candidates} LIMIT ?) AS eligible`,\n totalArgs: [...candidateArgs, query.k],\n order,\n vectorProbe: {\n sql: `SELECT COUNT(*) AS total FROM (SELECT 1 ${candidates} LIMIT ?) AS candidates`,\n args: [...candidateArgs, limit + 1],\n limit,\n rowLimit: query.k,\n totalLimit: query.k,\n },\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compileStart(\n projectId: string,\n query: Extract<ObjectQuery, { kind: \"start\" }>,\n ctx: CompileContext\n): CompiledObjectQuery {\n if (query.includeSubtypes === true) {\n throw new Error(\"[Sixb] SQLite object storage does not support start.includeSubtypes\")\n }\n\n const order = compileOrder(identityOrderFields())\n const sql = `\n SELECT *, properties AS _cursor_properties\n FROM ${ctx.source.objectsTable}\n WHERE project_id = ? AND object_type_id = ?\n ORDER BY ${order.sql}\n `\n const args = [projectId, query.objectTypeId, ...order.args]\n\n return {\n sql,\n args,\n totalSql: `SELECT COUNT(*) as total FROM ${ctx.source.objectsTable} WHERE project_id = ? AND object_type_id = ?`,\n totalArgs: [projectId, query.objectTypeId],\n order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compileRefs(\n projectId: string,\n query: Extract<ObjectQuery, { kind: \"refs\" }>,\n ctx: CompileContext\n): CompiledObjectQuery {\n if (query.refs.length === 0) {\n throw new Error(\"[Sixb] SQLite object storage requires at least one ref\")\n }\n\n const order = compileOrder(identityOrderFields())\n const selectedOrder = compileOrder(identityOrderFields(), \"selected\")\n const refsJson = JSON.stringify(query.refs)\n const requested = `\n SELECT DISTINCT\n json_extract(ref.value, '$.objectTypeId') AS object_type_id,\n json_extract(ref.value, '$.primaryId') AS primary_id\n FROM json_each(?) AS ref\n `\n const sql = `\n SELECT selected.*, selected.properties AS _cursor_properties\n FROM (${requested}) AS requested\n JOIN ${ctx.source.objectsTable} AS selected\n ON selected.project_id = ?\n AND selected.object_type_id = requested.object_type_id\n AND selected.primary_id = requested.primary_id\n ORDER BY ${selectedOrder.sql}\n `\n\n return {\n sql,\n args: [refsJson, projectId, ...selectedOrder.args],\n totalSql: `\n SELECT COUNT(*) AS total\n FROM (${requested}) AS requested\n JOIN ${ctx.source.objectsTable} AS selected\n ON selected.project_id = ?\n AND selected.object_type_id = requested.object_type_id\n AND selected.primary_id = requested.primary_id\n `,\n totalArgs: [refsJson, projectId],\n order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compileFilter(\n projectId: string,\n inputQuery: ObjectQuery,\n predicateNode: ObjectQueryPredicate,\n ctx: CompileContext\n): CompiledObjectQuery {\n const predicate = compilePredicate(predicateNode)\n return compileWhere(projectId, inputQuery, predicate, ctx)\n}\n\nfunction compileWhere(\n projectId: string,\n inputQuery: ObjectQuery,\n predicate: CompiledPredicate,\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const sql = `\n SELECT *\n FROM (${input.sql}) AS input\n WHERE ${predicate.sql}\n ORDER BY ${input.order.sql}\n `\n\n return {\n sql,\n args: [...input.args, ...predicate.args, ...input.order.args],\n totalSql: `\n SELECT COUNT(*) as total\n FROM (${input.sql}) AS input\n WHERE ${predicate.sql}\n `,\n totalArgs: [...input.args, ...predicate.args],\n vectorProbe: input.vectorProbe,\n order: input.order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compileText(\n projectId: string,\n inputQuery: ObjectQuery,\n query: string,\n fields: readonly string[] | undefined,\n fieldsByObjectType: Readonly<Record<string, readonly string[]>> | undefined,\n ctx: CompileContext\n): CompiledObjectQuery {\n const predicate =\n fields && fields.length > 0\n ? compileTextPredicate(query, fields)\n : compileScopedTextPredicate(query, fieldsByObjectType)\n\n if (!predicate) {\n throw new Error(\"[Sixb] SQLite object text search requires fields or resolved text defaults\")\n }\n return compileWhere(projectId, inputQuery, predicate, ctx)\n}\n\nfunction compileSort(\n projectId: string,\n inputQuery: ObjectQuery,\n fields: readonly ObjectQuerySortField[],\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const probeInput =\n ctx.probeLimit && needsLimitProbe(inputQuery)\n ? compileObjectQueryInternal(projectId, inputQuery, ctx)\n : undefined\n const order = compileOrder(sortOrderFields(fields))\n\n return {\n sql: `\n SELECT\n input.project_id,\n input.object_type_id,\n input.primary_id,\n input.properties,\n input.properties AS _cursor_properties,\n input.created_at,\n input.updated_at,\n input.version,\n input.last_commit_id${input.vectorProbe ? \", input._vector_score\" : \"\"}\n FROM (${input.sql}) AS input\n ORDER BY ${order.sql}\n `,\n args: [...input.args, ...order.args],\n totalSql: input.totalSql,\n totalArgs: input.totalArgs,\n order,\n hasMoreProbe: probeInput ? hasMoreProbeFor(probeInput) : input.hasMoreProbe,\n hasMore: input.hasMore,\n trimRows: input.trimRows,\n nextPageToken: input.nextPageToken,\n }\n}\n\nfunction compileLimit(\n projectId: string,\n inputQuery: ObjectQuery,\n rawLimit: number,\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const limit = Math.max(0, rawLimit)\n const rowLimit = ctx.probeLimit ? limit + 1 : limit\n\n return {\n sql: `\n SELECT *\n FROM (${input.sql}) AS input\n ORDER BY ${input.order.sql}\n LIMIT ?\n `,\n args: [...input.args, ...input.order.args, rowLimit],\n totalSql: `\n SELECT COUNT(*) as total\n FROM (${input.sql}) AS input\n `,\n totalArgs: input.args,\n vectorProbe: input.vectorProbe\n ? {\n ...input.vectorProbe,\n rowLimit: Math.min(input.vectorProbe.rowLimit, rowLimit),\n totalLimit: input.vectorProbe.rowLimit,\n }\n : undefined,\n order: input.order,\n hasMore: (rowCount, total) =>\n total === undefined ? ctx.probeLimit && rowCount > limit : limit < total,\n trimRows: ctx.probeLimit ? (rows) => rows.slice(0, limit) : identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compilePage(\n projectId: string,\n inputQuery: ObjectQuery,\n rawPageSize: number,\n pageToken: string | undefined,\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const pageSize = Math.max(0, rawPageSize)\n const cursor = pageToken ? decodePageToken(pageToken, input.order.fields) : undefined\n const cursorPredicate = cursor\n ? compileKeysetPredicate(input.order.fields, cursor, input.order.propertyColumn)\n : undefined\n const whereSql = cursorPredicate ? `WHERE ${cursorPredicate.sql}` : \"\"\n\n return {\n sql: `\n SELECT *\n FROM (${input.sql}) AS input\n ${whereSql}\n ORDER BY ${input.order.sql}\n LIMIT ?\n `,\n args: [...input.args, ...(cursorPredicate?.args ?? []), ...input.order.args, pageSize + 1],\n totalSql: `\n SELECT COUNT(*) as total\n FROM (${input.sql}) AS input\n `,\n totalArgs: input.args,\n vectorProbe: input.vectorProbe,\n order: input.order,\n hasMore: (rowCount) => rowCount > pageSize,\n trimRows: (rows) => rows.slice(0, pageSize),\n nextPageToken: (rows, rowCount) => {\n if (rowCount <= pageSize || rows.length === 0) return undefined\n return encodePageToken(rows[rows.length - 1], input.order.fields)\n },\n }\n}\n\nfunction compileTraversal(\n projectId: string,\n inputQuery: ObjectQuery,\n linkId: string,\n direction: \"outgoing\" | \"incoming\",\n sourceObjectTypeId: string | undefined,\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const outputAlias = direction === \"outgoing\" ? \"target_object\" : \"source_object\"\n const joinSql =\n direction === \"outgoing\"\n ? `\n JOIN ${ctx.source.linksTable} AS edge\n ON edge.project_id = input.project_id\n AND edge.source_type_id = input.object_type_id\n AND edge.source_id = input.primary_id\n AND edge.link_id = ?\n JOIN ${ctx.source.objectsTable} AS target_object\n ON target_object.project_id = edge.project_id\n AND target_object.object_type_id = edge.target_type_id\n AND target_object.primary_id = edge.target_id\n `\n : `\n JOIN ${ctx.source.linksTable} AS edge\n ON edge.project_id = input.project_id\n AND edge.target_type_id = input.object_type_id\n AND edge.target_id = input.primary_id\n AND edge.link_id = ?${sourceObjectTypeId === undefined ? \"\" : \"\\n AND edge.source_type_id = ?\"}\n JOIN ${ctx.source.objectsTable} AS source_object\n ON source_object.project_id = edge.project_id\n AND source_object.object_type_id = edge.source_type_id\n AND source_object.primary_id = edge.source_id\n `\n const order = compileOrder(identityOrderFields())\n const qualifiedOrder = compileOrder(identityOrderFields(), outputAlias)\n const sql = `\n SELECT DISTINCT ${outputAlias}.*, ${outputAlias}.properties AS _cursor_properties\n FROM (${input.sql}) AS input\n ${joinSql}\n ORDER BY ${qualifiedOrder.sql}\n `\n const args = [\n ...input.args,\n linkId,\n ...(sourceObjectTypeId === undefined ? [] : [sourceObjectTypeId]),\n ...qualifiedOrder.args,\n ]\n\n return {\n sql,\n args,\n totalSql: `SELECT COUNT(*) as total FROM (${sql}) AS traversed`,\n totalArgs: args,\n order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\n/** Correlation handle for an expansion: the parent row's identity columns. */\ninterface ExpansionParent {\n project: string\n type: string\n id: string\n}\n\n// `expand` attaches linked objects to each result row without changing which\n// objects match (unlike `traverse`, which pivots to the targets). Each expansion\n// becomes a correlated subquery that hydrates its links into a JSON value, and\n// all expansions are folded into one `_expand` object column the row mapper reads\n// back. The input set is otherwise untouched, so pagination/order pass through.\nfunction compileExpand(\n projectId: string,\n inputQuery: ObjectQuery,\n expansions: readonly ObjectExpansion[],\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const expand = compileExpansionsObject(\n expansions,\n { project: \"input.project_id\", type: \"input.object_type_id\", id: \"input.primary_id\" },\n \"\",\n ctx\n )\n const inputOrder = compileOrder(input.order.fields, \"input\", \"input._cursor_properties\")\n const sql = `\n SELECT input.*, ${expand.sql} AS _expand\n FROM (${input.sql}) AS input\n ORDER BY ${inputOrder.sql}\n `\n\n return {\n sql,\n args: [...expand.args, ...input.args, ...inputOrder.args],\n totalSql: input.totalSql,\n totalArgs: input.totalArgs,\n vectorProbe: input.vectorProbe,\n order: input.order,\n hasMoreProbe: input.hasMoreProbe,\n hasMore: input.hasMore,\n trimRows: input.trimRows,\n nextPageToken: input.nextPageToken,\n }\n}\n\n// `json_object(linkId, value, ...)` over a set of expansions sharing one parent.\n// Link ids are user data, so they ride as parameters. Each value is a correlated\n// subquery whose JSON subtype is lost crossing the subquery boundary, so it is\n// re-parsed with `json(...)` to embed as nested JSON rather than a quoted string.\n// Used both for the outer `_expand` column and for each child's nested `links`.\nfunction compileExpansionsObject(\n expansions: readonly ObjectExpansion[],\n parent: ExpansionParent,\n pathPrefix: string,\n ctx: CompileContext\n): CompiledPredicate {\n const parts: string[] = []\n const args: SqliteValue[] = []\n expansions.forEach((expansion, index) => {\n const path = pathPrefix === \"\" ? `${index}` : `${pathPrefix}_${index}`\n const value = compileExpansionValue(expansion, parent, path, ctx)\n parts.push(\"?\", `json(${value.sql})`)\n args.push(expansion.linkId, ...value.args)\n })\n return { sql: `json_object(${parts.join(\", \")})`, args }\n}\n\n// One expansion's hydrated value. `row_number()` numbers a parent's links by the\n// order from `compileExpansionOrder` (the expansion's `orderBy` against the target\n// object's properties, then an identity tiebreak); `WHERE _ord <= N` keeps the\n// top-N per parent in-DB; each retained neighbour becomes a JSON object; and the\n// value is an ordered array (\"many\") or the first element or null (\"one\"). The\n// cardinality is core-resolved before pushdown.\nfunction compileExpansionValue(\n expansion: ObjectExpansion,\n parent: ExpansionParent,\n path: string,\n ctx: CompileContext\n): CompiledPredicate {\n const edge = `edge_${path}`\n const target = `tgt_${path}`\n const ranked = `ranked_${path}`\n const incoming = expansion.direction === \"incoming\"\n // The hydrated neighbour is the link target (outgoing) or source (incoming);\n // the parent sits on the opposite end, mirroring `compileTraversal`.\n const neighborType = incoming ? `${edge}.source_type_id` : `${edge}.target_type_id`\n const neighborId = incoming ? `${edge}.source_id` : `${edge}.target_id`\n const parentType = incoming ? `${edge}.target_type_id` : `${edge}.source_type_id`\n const parentId = incoming ? `${edge}.target_id` : `${edge}.source_id`\n\n const child = compileExpansionChildJson(expansion, edge, target, path, ctx)\n const order = compileExpansionOrder(expansion, target, neighborType, neighborId)\n\n const whereParts = [\n `${edge}.project_id = ${parent.project}`,\n `${parentType} = ${parent.type}`,\n `${parentId} = ${parent.id}`,\n `${edge}.link_id = ?`,\n ]\n const whereArgs: SqliteValue[] = [expansion.linkId]\n if (incoming && expansion.sourceObjectTypeId !== undefined) {\n whereParts.push(`${edge}.source_type_id = ?`)\n whereArgs.push(expansion.sourceObjectTypeId)\n }\n\n const inner = `\n SELECT ${child.sql} AS elem, row_number() OVER (ORDER BY ${order.sql}) AS _ord\n FROM ${ctx.source.linksTable} AS ${edge}\n JOIN ${ctx.source.objectsTable} AS ${target}\n ON ${target}.project_id = ${edge}.project_id\n AND ${target}.object_type_id = ${neighborType}\n AND ${target}.primary_id = ${neighborId}\n WHERE ${whereParts.join(\" AND \")}\n `\n const innerArgs = [...child.args, ...order.args, ...whereArgs]\n\n if (expansion.cardinality === \"one\") {\n return {\n sql: `(SELECT ${ranked}.elem FROM (${inner}) AS ${ranked} WHERE ${ranked}._ord = 1)`,\n args: innerArgs,\n }\n }\n\n // The fanout cap is baked into `limit` by the core executor before pushdown.\n // Each element is re-parsed with `json(...)` so the aggregate embeds objects\n // rather than the quoted JSON text the subquery column hands back.\n const limit = expansion.limit ?? DEFAULT_EXPANSION_FANOUT\n return {\n sql: `COALESCE((SELECT json_group_array(json(${ranked}.elem) ORDER BY ${ranked}._ord) FROM (${inner}) AS ${ranked} WHERE ${ranked}._ord <= ?), '[]')`,\n args: [...innerArgs, limit],\n }\n}\n\n// Build one hydrated neighbour as an `ExpandedObjectRow`-shaped JSON object. The\n// JSON-valued columns (`properties`, the edge's `linkProperties`) are re-parsed\n// with `json(...)` so they embed as JSON rather than strings; `linkProperties`\n// always rides along (the mapper drops it when null/empty), and nested expansions\n// recurse under `links`, correlated on this neighbour.\nfunction compileExpansionChildJson(\n expansion: ObjectExpansion,\n edge: string,\n target: string,\n path: string,\n ctx: CompileContext\n): CompiledPredicate {\n const fields = [\n `'projectId', ${target}.project_id`,\n `'objectTypeId', ${target}.object_type_id`,\n `'primaryId', ${target}.primary_id`,\n `'properties', json(${target}.properties)`,\n `'createdAt', ${target}.created_at`,\n `'updatedAt', ${target}.updated_at`,\n `'version', ${target}.version`,\n `'lastCommitId', ${target}.last_commit_id`,\n `'linkProperties', json(${edge}.properties)`,\n ]\n const args: SqliteValue[] = []\n\n if (expansion.expand && expansion.expand.length > 0) {\n const nested = compileExpansionsObject(\n expansion.expand,\n {\n project: `${target}.project_id`,\n type: `${target}.object_type_id`,\n id: `${target}.primary_id`,\n },\n path,\n ctx\n )\n fields.push(`'links', ${nested.sql}`)\n args.push(...nested.args)\n }\n\n return { sql: `json_object(${fields.join(\", \")})`, args }\n}\n\n// Order a parent's links the way the fallback's per-parent trim does: each\n// property sorts nulls last with the requested direction (against the neighbour's\n// JSON properties), then a deterministic identity tiebreak on the neighbour.\nfunction compileExpansionOrder(\n expansion: ObjectExpansion,\n target: string,\n neighborType: string,\n neighborId: string\n): CompiledPredicate {\n const propertyColumn = `${target}.properties`\n const clauses: string[] = []\n const args: SqliteValue[] = []\n\n for (const field of expansion.orderBy ?? []) {\n // Relevance is a no-op in the fallback comparator; mirror that by skipping it.\n if (field.kind !== \"property\") continue\n if (field.scalarKind === \"decimal\") {\n throw new ObjectQueryExecutionError(\n \"exact_decimal_not_supported\",\n \"SQLite object storage cannot push down exact decimal expansion sorting\",\n \"$.expand.orderBy\"\n )\n }\n const direction = field.direction === \"desc\" ? \"DESC\" : \"ASC\"\n const path = jsonPath(field.propertyId)\n clauses.push(\n `CASE WHEN ${jsonTypeExpression(propertyColumn)} IS NULL OR ${jsonTypeExpression(propertyColumn)} = 'null' THEN 1 ELSE 0 END ASC`,\n `${jsonValueExpression(propertyColumn)} ${direction}`\n )\n args.push(path, path, path)\n }\n\n clauses.push(`${neighborType} ASC`, `${neighborId} ASC`)\n return { sql: clauses.join(\", \"), args }\n}\n\nfunction compileSet(\n projectId: string,\n op: ObjectQuerySetOperation,\n inputs: readonly ObjectQuery[],\n ctx: CompileContext\n): CompiledObjectQuery {\n if (inputs.length === 0) {\n const order = compileOrder(identityOrderFields())\n return {\n sql: `\n SELECT *\n FROM ${ctx.source.objectsTable}\n WHERE 1 = 0\n ORDER BY ${order.sql}\n `,\n args: order.args,\n totalSql: \"SELECT 0 as total\",\n totalArgs: [],\n order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n }\n\n const compiledInputs = inputs.map((input) =>\n compileObjectQueryInternal(projectId, input, exactContext(ctx))\n )\n const identities = compileSetIdentities(op, compiledInputs)\n const order = compileOrder(identityOrderFields())\n const selectedOrder = compileOrder(identityOrderFields(), \"selected\")\n const sql = `\n SELECT selected.*, selected.properties AS _cursor_properties\n FROM (${identities.sql}) AS ids\n JOIN ${ctx.source.objectsTable} AS selected\n ON selected.project_id = ?\n AND selected.object_type_id = ids.object_type_id\n AND selected.primary_id = ids.primary_id\n ORDER BY ${selectedOrder.sql}\n `\n const args = [...identities.args, projectId, ...selectedOrder.args]\n\n return {\n sql,\n args,\n totalSql: `SELECT COUNT(*) as total FROM (${identities.sql}) AS ids`,\n totalArgs: identities.args,\n order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compileProject(\n projectId: string,\n inputQuery: ObjectQuery,\n properties: readonly string[] | undefined,\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, ctx)\n if (!properties) return input\n\n const projection = compileProjectionExpression(properties)\n const inputOrder = compileOrder(input.order.fields, \"input\", \"input._cursor_properties\")\n const outputOrder = compileOrder(input.order.fields, undefined, \"_cursor_properties\")\n\n return {\n sql: `\n SELECT\n input.project_id,\n input.object_type_id,\n input.primary_id,\n ${projection.sql} AS properties,\n input._cursor_properties AS _cursor_properties,\n input.created_at,\n input.updated_at,\n input.version,\n input.last_commit_id${input.vectorProbe ? \", input._vector_score, input._vector_candidate_count\" : \"\"}\n FROM (${input.sql}) AS input\n ORDER BY ${inputOrder.sql}\n `,\n args: [...projection.args, ...input.args, ...inputOrder.args],\n totalSql: input.totalSql,\n totalArgs: input.totalArgs,\n vectorProbe: input.vectorProbe,\n order: outputOrder,\n hasMoreProbe: input.hasMoreProbe,\n hasMore: input.hasMore,\n trimRows: input.trimRows,\n nextPageToken: input.nextPageToken,\n }\n}\n\nfunction needsLimitProbe(query: ObjectQuery): boolean {\n switch (query.kind) {\n case \"limit\":\n return true\n case \"project\":\n case \"sort\":\n return needsLimitProbe(query.input)\n default:\n return false\n }\n}\n\nfunction hasMoreProbeFor(compiled: CompiledObjectQuery): CompiledHasMoreProbe {\n return (\n compiled.hasMoreProbe ?? {\n sql: compiled.sql,\n args: compiled.args,\n hasMore: (rowCount) => compiled.hasMore(rowCount, undefined),\n }\n )\n}\n\nfunction compileSetIdentities(\n op: ObjectQuerySetOperation,\n inputs: readonly CompiledObjectQuery[]\n): CompiledPredicate {\n const operator = op === \"union\" ? \"UNION\" : op === \"intersect\" ? \"INTERSECT\" : \"EXCEPT\"\n const identitySqls = inputs.map(\n (input) => `SELECT object_type_id, primary_id FROM (${input.sql}) AS input`\n )\n\n return {\n sql: identitySqls.join(` ${operator} `),\n args: inputs.flatMap((input) => input.args),\n }\n}\n\nfunction compileProjectionExpression(properties: readonly string[]): CompiledPredicate {\n if (properties.length === 0) return { sql: \"json('{}')\", args: [] }\n\n return {\n sql: `\n COALESCE(\n (\n SELECT json_group_object(projected.key, ${sqliteJsonEachValue(\"projected\")})\n FROM json_each(input.properties) AS projected\n WHERE projected.key IN (${properties.map(() => \"?\").join(\", \")})\n ),\n json('{}')\n )\n `,\n args: [...properties],\n }\n}\n\n/** json_each exposes JSON booleans as integer SQL values; restore their JSON representation. */\nexport function sqliteJsonEachValue(alias: string): string {\n return `CASE ${alias}.type\n WHEN 'true' THEN json('true')\n WHEN 'false' THEN json('false')\n ELSE ${alias}.value\n END`\n}\n\nfunction compilePredicate(predicate: ObjectQueryPredicate): CompiledPredicate {\n if (\n \"scalarKind\" in predicate &&\n predicate.scalarKind === \"decimal\" &&\n (predicate.op === \"lt\" ||\n predicate.op === \"lte\" ||\n predicate.op === \"gt\" ||\n predicate.op === \"gte\")\n ) {\n throw new ObjectQueryExecutionError(\n \"exact_decimal_not_supported\",\n \"SQLite object storage cannot push down exact decimal predicates\",\n \"$.predicate\"\n )\n }\n\n switch (predicate.op) {\n case \"and\":\n case \"or\": {\n const items = predicate.items.map(compilePredicate)\n const joiner = predicate.op === \"and\" ? \" AND \" : \" OR \"\n return {\n sql: `(${items.map((item) => item.sql).join(joiner)})`,\n args: items.flatMap((item) => item.args),\n }\n }\n case \"not\": {\n const item = compilePredicate(predicate.item)\n return negatePredicate(item)\n }\n case \"eq\":\n return predicate.scalarKind === \"userRef\"\n ? compileUserRefInPredicate(predicate.propertyId, [predicate.value])\n : compileEqualityPredicate(predicate.propertyId, \"eq\", predicate.value)\n case \"neq\":\n return predicate.scalarKind === \"userRef\"\n ? negatePredicate(compileUserRefInPredicate(predicate.propertyId, [predicate.value]))\n : compileEqualityPredicate(predicate.propertyId, \"neq\", predicate.value)\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\": {\n const op = sqlComparisonOperator(predicate.op)\n return {\n sql: `${jsonValueExpression()} ${op} ?`,\n args: [jsonPath(predicate.propertyId), sqlValue(predicate.value)],\n }\n }\n case \"in\":\n return predicate.scalarKind === \"userRef\"\n ? compileUserRefInPredicate(predicate.propertyId, predicate.values)\n : compileInPredicate(predicate.propertyId, predicate.values)\n case \"exists\": {\n const sql = `${jsonTypeExpression()} IS NOT NULL`\n const item: CompiledPredicate = { sql, args: [jsonPath(predicate.propertyId)] }\n return predicate.value ? item : negatePredicate(item)\n }\n case \"contains\":\n return predicate.scalarKind === \"userRef\"\n ? compileUserRefContainsPredicate(predicate.propertyId, predicate.value)\n : compileContainsPredicate(predicate.propertyId, predicate.value)\n }\n}\n\n/**\n * User references are JSON objects, so they match on both fields rather than on serialized text,\n * which would depend on key order.\n */\nfunction compileUserRefInPredicate(\n propertyId: string,\n values: readonly unknown[]\n): CompiledPredicate {\n const path = jsonPath(propertyId)\n const ids = values.flatMap((value) => {\n const id = userRefId(value)\n return id === undefined ? [] : [id]\n })\n const clauses: string[] = []\n const args: SqliteValue[] = []\n\n if (values.includes(null)) {\n clauses.push(`${jsonTypeExpression()} = 'null'`)\n args.push(path)\n }\n if (ids.length > 0) {\n clauses.push(\n `(${jsonValueExpression()} = 'user' AND ${jsonValueExpression()} IN (${ids.map(() => \"?\").join(\", \")}))`\n )\n args.push(`${path}.type`, `${path}.id`, ...ids)\n }\n if (clauses.length === 0) return { sql: \"0 = 1\", args: [] }\n\n return { sql: `(${clauses.join(\" OR \")})`, args }\n}\n\nfunction compileUserRefContainsPredicate(propertyId: string, value: unknown): CompiledPredicate {\n const id = userRefId(value)\n if (id === undefined) return { sql: \"0 = 1\", args: [] }\n const path = jsonPath(propertyId)\n return {\n sql: `(${jsonTypeExpression()} = 'array' AND EXISTS (SELECT 1 FROM json_each(properties, ?) AS item WHERE item.type = 'object' AND json_extract(item.value, '$.type') = 'user' AND json_extract(item.value, '$.id') = ?))`,\n args: [path, path, id],\n }\n}\n\nfunction userRefId(value: unknown): string | undefined {\n if (typeof value !== \"object\" || value === null) return undefined\n const { type, id } = value as { type?: unknown; id?: unknown }\n return type === \"user\" && typeof id === \"string\" ? id : undefined\n}\n\nfunction negatePredicate(predicate: CompiledPredicate): CompiledPredicate {\n return {\n sql: `(NOT COALESCE((${predicate.sql}), 0))`,\n args: predicate.args,\n }\n}\n\nfunction compileEqualityPredicate(\n propertyId: string,\n op: \"eq\" | \"neq\",\n value: unknown\n): CompiledPredicate {\n const path = jsonPath(propertyId)\n if (value === null) {\n const sql = `${jsonTypeExpression()} = 'null'`\n const item: CompiledPredicate = { sql, args: [path] }\n return op === \"eq\" ? item : negatePredicate(item)\n }\n\n if (op === \"eq\") {\n return {\n sql: `${jsonValueExpression()} = ?`,\n args: [path, sqlValue(value)],\n }\n }\n\n // JS predicate semantics treat missing/null properties as not equal to any\n // non-null scalar. SQL three-valued null logic needs those cases explicit.\n return {\n sql: `(${jsonTypeExpression()} IS NULL OR ${jsonTypeExpression()} = 'null' OR ${jsonValueExpression()} != ?)`,\n args: [path, path, path, sqlValue(value)],\n }\n}\n\nfunction compileInPredicate(propertyId: string, values: readonly unknown[]): CompiledPredicate {\n if (values.length === 0) return { sql: \"0 = 1\", args: [] }\n\n const path = jsonPath(propertyId)\n const nonNullValues = values.filter((value) => value !== null)\n const clauses: string[] = []\n const args: SqliteValue[] = []\n\n if (values.length !== nonNullValues.length) {\n clauses.push(`${jsonTypeExpression()} = 'null'`)\n args.push(path)\n }\n\n if (nonNullValues.length > 0) {\n clauses.push(`${jsonValueExpression()} IN (${nonNullValues.map(() => \"?\").join(\", \")})`)\n args.push(path, ...nonNullValues.map(sqlValue))\n }\n\n return {\n sql: `(${clauses.join(\" OR \")})`,\n args,\n }\n}\n\nfunction compileContainsPredicate(propertyId: string, value: unknown): CompiledPredicate {\n const path = jsonPath(propertyId)\n const clauses: string[] = []\n const args: SqliteValue[] = []\n\n if (typeof value === \"string\") {\n clauses.push(`(${jsonTypeExpression()} = 'text' AND instr(${jsonValueExpression()}, ?) > 0)`)\n args.push(path, path, value)\n }\n\n clauses.push(\n `(${jsonTypeExpression()} = 'array' AND EXISTS (SELECT 1 FROM json_each(properties, ?) AS item WHERE item.value IS ?))`\n )\n args.push(path, path, sqlValue(value))\n\n if (typeof value === \"string\") {\n clauses.push(\n `(${jsonTypeExpression()} = 'object' AND EXISTS (SELECT 1 FROM json_each(properties, ?) AS item WHERE item.key = ?))`\n )\n args.push(path, path, value)\n }\n\n return { sql: `(${clauses.join(\" OR \")})`, args }\n}\n\nfunction compileTextPredicate(query: string, fields: readonly string[]): CompiledPredicate {\n const terms = tokenize(query)\n if (terms.length === 0) return { sql: \"0 = 1\", args: [] }\n\n const clauses = terms.map(() => {\n const fieldClauses = fields.map(\n () => `instr(lower(COALESCE(CAST(${jsonValueExpression()} AS TEXT), '')), ?) > 0`\n )\n return `(${fieldClauses.join(\" OR \")})`\n })\n const args = terms.flatMap((term) => fields.flatMap((field) => [jsonPath(field), term]))\n\n return { sql: `(${clauses.join(\" AND \")})`, args }\n}\n\nfunction compileScopedTextPredicate(\n query: string,\n fieldsByObjectType: Readonly<Record<string, readonly string[]>> | undefined\n): CompiledPredicate | null {\n const scopedPredicates: CompiledPredicate[] = []\n\n for (const [objectTypeId, fields] of Object.entries(fieldsByObjectType ?? {})) {\n if (fields.length === 0) continue\n const predicate = compileTextPredicate(query, fields)\n scopedPredicates.push({\n sql: `(object_type_id = ? AND ${predicate.sql})`,\n args: [objectTypeId, ...predicate.args],\n })\n }\n\n if (scopedPredicates.length === 0) return null\n\n return {\n sql: `(${scopedPredicates.map((predicate) => predicate.sql).join(\" OR \")})`,\n args: scopedPredicates.flatMap((predicate) => predicate.args),\n }\n}\n\nfunction compileOrder(\n fields: readonly CompiledOrderField[],\n qualifier?: string,\n propertyColumn = \"properties\"\n): CompiledOrder {\n const clauses: string[] = []\n const args: SqliteValue[] = []\n\n for (const field of fields) {\n if (field.kind === \"column\") {\n clauses.push(\n `${columnExpression(field.column, qualifier)}${field.binary ? \" COLLATE BINARY\" : \"\"} ${field.direction.toUpperCase()}`\n )\n continue\n }\n\n const direction = field.direction === \"desc\" ? \"DESC\" : \"ASC\"\n const path = jsonPath(field.propertyId)\n clauses.push(\n `CASE WHEN ${jsonTypeExpression(propertyColumn)} IS NULL OR ${jsonTypeExpression(propertyColumn)} = 'null' THEN 1 ELSE 0 END ASC`,\n `${jsonValueExpression(propertyColumn)} ${direction}`\n )\n args.push(path, path, path)\n }\n\n return { sql: clauses.join(\", \"), args, fields, propertyColumn }\n}\n\nfunction sortOrderFields(fields: readonly ObjectQuerySortField[]): readonly CompiledOrderField[] {\n const orderFields: CompiledOrderField[] = []\n for (const field of fields) {\n if (field.kind !== \"property\") {\n throw new Error(\"[Sixb] SQLite object storage does not support relevance sorting\")\n }\n if (field.scalarKind === \"decimal\") {\n throw new ObjectQueryExecutionError(\n \"exact_decimal_not_supported\",\n \"SQLite object storage cannot push down exact decimal sorting\",\n \"$.sort\"\n )\n }\n\n orderFields.push({\n kind: \"property\",\n propertyId: field.propertyId,\n direction: field.direction === \"desc\" ? \"desc\" : \"asc\",\n })\n }\n orderFields.push(...identityOrderFields())\n return orderFields\n}\n\nfunction identityOrderFields(): readonly CompiledOrderField[] {\n return [\n { kind: \"column\", column: \"object_type_id\", direction: \"asc\" },\n { kind: \"column\", column: \"primary_id\", direction: \"asc\" },\n ]\n}\n\nfunction compileKeysetPredicate(\n fields: readonly CompiledOrderField[],\n cursor: readonly EncodedCursorValue[],\n propertyColumn = \"properties\"\n): CompiledPredicate {\n const disjuncts: CompiledPredicate[] = []\n\n for (let index = 0; index < fields.length; index += 1) {\n const equalityPredicates = fields\n .slice(0, index)\n .map((field, equalityIndex) =>\n compileFieldEquality(field, cursor[equalityIndex], propertyColumn)\n )\n const advancePredicate = compileFieldAfter(fields[index], cursor[index], propertyColumn)\n if (!advancePredicate) continue\n\n const parts = [...equalityPredicates, advancePredicate]\n disjuncts.push({\n sql: `(${parts.map((part) => part.sql).join(\" AND \")})`,\n args: parts.flatMap((part) => part.args),\n })\n }\n\n if (disjuncts.length === 0) return { sql: \"0 = 1\", args: [] }\n\n return {\n sql: `(${disjuncts.map((part) => part.sql).join(\" OR \")})`,\n args: disjuncts.flatMap((part) => part.args),\n }\n}\n\nfunction compileFieldEquality(\n field: CompiledOrderField,\n cursor: EncodedCursorValue,\n propertyColumn = \"properties\"\n): CompiledPredicate {\n if (field.kind === \"column\") {\n return {\n sql: `${columnExpression(field.column)} = ?`,\n args: [sqlValue(cursor.value)],\n }\n }\n\n const path = jsonPath(field.propertyId)\n if (cursor.nullish) {\n return {\n sql: `(${jsonTypeExpression(propertyColumn)} IS NULL OR ${jsonTypeExpression(propertyColumn)} = 'null')`,\n args: [path, path],\n }\n }\n\n return {\n sql: `(${jsonTypeExpression(propertyColumn)} IS NOT NULL AND ${jsonTypeExpression(propertyColumn)} != 'null' AND ${jsonValueExpression(propertyColumn)} = ?)`,\n args: [path, path, path, sqlValue(cursor.value)],\n }\n}\n\nfunction compileFieldAfter(\n field: CompiledOrderField,\n cursor: EncodedCursorValue,\n propertyColumn = \"properties\"\n): CompiledPredicate | null {\n if (field.kind === \"column\") {\n return {\n sql: `${columnExpression(field.column)} ${field.direction === \"desc\" ? \"<\" : \">\"} ?`,\n args: [sqlValue(cursor.value)],\n }\n }\n\n if (cursor.nullish) return null\n\n const path = jsonPath(field.propertyId)\n const rankSql = `CASE WHEN ${jsonTypeExpression(propertyColumn)} IS NULL OR ${jsonTypeExpression(propertyColumn)} = 'null' THEN 1 ELSE 0 END`\n const valueOperator = field.direction === \"desc\" ? \"<\" : \">\"\n\n return {\n sql: `(${rankSql} > 0 OR (${rankSql} = 0 AND ${jsonValueExpression(propertyColumn)} ${valueOperator} ?))`,\n args: [path, path, path, path, path, sqlValue(cursor.value)],\n }\n}\n\nfunction encodePageToken(\n row: SqliteObjectQueryPageRow,\n fields: readonly CompiledOrderField[]\n): string {\n const properties = JSON.parse(row._cursor_properties ?? row.properties) as Record<string, unknown>\n const token: EncodedPageToken = {\n version: 1,\n order: fields.map(orderFieldKey),\n values: fields.map((field) => cursorValueForField(row, properties, field)),\n }\n return `${PAGE_TOKEN_PREFIX}${Buffer.from(JSON.stringify(token)).toString(\"base64url\")}`\n}\n\nfunction decodePageToken(\n token: string,\n fields: readonly CompiledOrderField[]\n): readonly EncodedCursorValue[] {\n if (!token.startsWith(PAGE_TOKEN_PREFIX)) {\n throwInvalidPageToken(\"Invalid SQLite object query page token\")\n }\n\n const raw = token.slice(PAGE_TOKEN_PREFIX.length)\n let decoded: unknown\n try {\n decoded = JSON.parse(Buffer.from(raw, \"base64url\").toString(\"utf8\"))\n } catch {\n throwInvalidPageToken(\"Invalid SQLite object query page token\")\n }\n\n if (!isEncodedPageToken(decoded)) {\n throwInvalidPageToken(\"Invalid SQLite object query page token\")\n }\n\n const expectedOrder = fields.map(orderFieldKey)\n if (\n decoded.order.length !== expectedOrder.length ||\n decoded.order.some((field, index) => field !== expectedOrder[index])\n ) {\n throwInvalidPageToken(\"SQLite object query page token does not match query order\")\n }\n\n return decoded.values\n}\n\nfunction throwInvalidPageToken(message: string): never {\n throw new ObjectQueryExecutionError(\"invalid_page_token\", message, \"$.pageToken\")\n}\n\nfunction isEncodedPageToken(value: unknown): value is EncodedPageToken {\n if (!isPlainObject(value)) return false\n if (value.version !== 1) return false\n if (!Array.isArray(value.order) || value.order.some((item) => typeof item !== \"string\")) {\n return false\n }\n if (!Array.isArray(value.values)) return false\n return value.values.every(\n (item) =>\n isPlainObject(item) &&\n typeof item.nullish === \"boolean\" &&\n (item.nullish || Object.hasOwn(item, \"value\"))\n )\n}\n\nfunction cursorValueForField(\n row: SqliteObjectQueryPageRow,\n properties: Record<string, unknown>,\n field: CompiledOrderField\n): EncodedCursorValue {\n const value =\n field.kind === \"column\"\n ? field.column === \"object_type_id\"\n ? row.object_type_id\n : row.primary_id\n : properties[field.propertyId]\n\n return value === null || value === undefined ? { nullish: true } : { nullish: false, value }\n}\n\nfunction orderFieldKey(field: CompiledOrderField): string {\n return field.kind === \"column\"\n ? `column:${field.column}:${field.direction}`\n : `property:${field.propertyId}:${field.direction}`\n}\n\nfunction columnExpression(\n column: \"object_type_id\" | \"primary_id\" | \"_vector_score\",\n qualifier?: string\n): string {\n return qualifier ? `${qualifier}.${column}` : column\n}\n\nfunction jsonValueExpression(column = \"properties\"): string {\n return `json_extract(${column}, ?)`\n}\n\nfunction jsonTypeExpression(column = \"properties\"): string {\n return `json_type(${column}, ?)`\n}\n\nfunction jsonPath(propertyId: string): string {\n return `$.\"${propertyId.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`\n}\n\nfunction sqlValue(value: unknown): SqliteValue {\n if (value instanceof Date) return value.toISOString()\n if (typeof value === \"boolean\") return value ? 1 : 0\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n value === null\n ) {\n return value\n }\n return JSON.stringify(value)\n}\n\nfunction tokenize(query: string): string[] {\n return query\n .trim()\n .toLowerCase()\n .split(/\\s+/)\n .filter((term) => term.length > 0)\n}\n\nfunction sqlComparisonOperator(op: \"lt\" | \"lte\" | \"gt\" | \"gte\"): \"<\" | \"<=\" | \">\" | \">=\" {\n switch (op) {\n case \"lt\":\n return \"<\"\n case \"lte\":\n return \"<=\"\n case \"gt\":\n return \">\"\n case \"gte\":\n return \">=\"\n }\n}\n\nfunction identityRows<T>(rows: readonly T[]): readonly T[] {\n return rows\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n",
44
+ "import type { Database } from \"bun:sqlite\"\nimport { hasVectorProfile } from \"@sixb/core/internal/query\"\nimport type {\n CompiledConditionalObjectReadScope,\n CompiledSelectedObjectReadScope,\n CountObjectsInput,\n CountObjectsResult,\n ExistsObjectsInput,\n ExistsObjectsResult,\n FacetObjectsInput,\n FacetObjectsResult,\n LinkBatchKey,\n LinkDirection,\n ObjectBatchKey,\n ObjectLinkRow,\n ObjectQueryCapabilities,\n ObjectReadExecutionLimits,\n ObjectReadStorage,\n ObjectRow,\n ObjectStorage,\n QueryObjectLinksInput,\n QueryObjectLinksResult,\n QueryObjectsInput,\n QueryObjectsResult,\n} from \"@sixb/core/storage\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n runDeferredReadTransaction,\n type SqliteStoreConnection,\n} from \"../transactions\"\nimport { createSqliteConditionalReader } from \"./conditional-reader\"\nimport { DEFAULT_OBJECT_QUERY_SOURCE } from \"./query-compiler\"\nimport { assertLinkQueryLimit, SqliteObjectReader } from \"./reader\"\nimport { type DatabaseRow, type LinkDatabaseRow, rowToLink, rowToObject } from \"./rows\"\nimport { createSqliteSelectedReader } from \"./selected-reader\"\n\nexport interface SqliteObjectStorageOptions {\n /** Path to SQLite database file. Defaults to ':memory:' for in-memory database. */\n path?: string\n /** Internal shared connection used by bundled SqliteStorage. */\n connection?: SqliteStoreConnection\n}\n\nconst SQLITE_OBJECT_QUERY_CAPABILITIES: ObjectQueryCapabilities = {\n queryObjects: true,\n countObjects: true,\n existsObjects: true,\n facetObjects: true,\n nodes: {\n start: true,\n refs: true,\n filter: true,\n text: true,\n vector: true,\n sort: true,\n limit: true,\n page: true,\n traverse: true,\n set: true,\n project: true,\n expand: true,\n },\n predicateOps: {\n and: true,\n or: true,\n not: true,\n eq: true,\n neq: true,\n lt: true,\n lte: true,\n gt: true,\n gte: true,\n in: true,\n exists: true,\n contains: true,\n constant: true,\n },\n sortKinds: {\n property: true,\n },\n traversalDirections: {\n outgoing: true,\n incoming: true,\n },\n setOps: {\n union: true,\n intersect: true,\n subtract: true,\n },\n scalarOperations: {\n string: { equality: true, ordering: true },\n uuid: { equality: true, ordering: true },\n boolean: { equality: true },\n integer: { equality: true, ordering: true },\n double: { equality: true, ordering: true },\n decimal: { equality: true },\n date: { equality: true, ordering: true },\n timestamp: { equality: true, ordering: true },\n userRef: { equality: true },\n },\n limits: {\n totalCount: true,\n stablePageTokens: true,\n },\n notes: [\n \"SQLite object query pushdown supports start/refs/filter/text/sort/limit/page/traverse/set/project/expand over JSON properties and object links.\",\n \"expand hydrates linked objects in-database (top-N per parent via row_number() + json_group_array); core resolves each expansion's cardinality before pushdown, and a mixed/unresolved one stays on the fallback.\",\n \"Ordered decimal predicates and sorting use the bounded core fallback because SQLite has no native exact decimal type; canonical decimal equality remains pushdown-safe.\",\n \"Relevance sorting and unresolved start.includeSubtypes remain planner fallback or rejection cases.\",\n ],\n}\n\n/**\n * SQLite-based ObjectStorage implementation.\n *\n * Stores object projections and links. V1 object-query IR pushdown covers the\n * scalar JSON-property and link-traversal subset declared by queryCapabilities().\n */\nexport class SqliteObjectStorage implements ObjectStorage {\n private readonly connection: SqliteStoreConnection\n private readonly db: Database\n private readonly reader: SqliteObjectReader\n\n constructor(options: SqliteObjectStorageOptions = {}) {\n this.connection = openSqliteStoreConnection(options)\n this.db = this.connection.db\n this.reader = new SqliteObjectReader(this.db, DEFAULT_OBJECT_QUERY_SOURCE)\n }\n\n queryCapabilities(): ObjectQueryCapabilities {\n return SQLITE_OBJECT_QUERY_CAPABILITIES\n }\n\n createSelectedReadScope(params: {\n projectId: string\n scope: CompiledSelectedObjectReadScope\n limits: ObjectReadExecutionLimits\n }): ObjectReadStorage {\n return createSqliteSelectedReader(this.db, params, () => this.queryCapabilities())\n }\n\n createConditionalReadScope(params: {\n projectId: string\n scope: CompiledConditionalObjectReadScope\n }): ObjectReadStorage {\n return createSqliteConditionalReader(this.db, params, () => this.queryCapabilities())\n }\n\n async queryObjects(params: QueryObjectsInput): Promise<QueryObjectsResult> {\n if (hasVectorProfile(params.query))\n return runDeferredReadTransaction(this.db, () => this.reader.queryObjects(params))\n return this.reader.queryObjects(params)\n }\n\n async countObjects(params: CountObjectsInput): Promise<CountObjectsResult> {\n if (hasVectorProfile(params.query))\n return runDeferredReadTransaction(this.db, () => this.reader.countObjects(params))\n return this.reader.countObjects(params)\n }\n\n async existsObjects(params: ExistsObjectsInput): Promise<ExistsObjectsResult> {\n if (hasVectorProfile(params.query))\n return runDeferredReadTransaction(this.db, () => this.reader.existsObjects(params))\n return this.reader.existsObjects(params)\n }\n\n async facetObjects(params: FacetObjectsInput): Promise<FacetObjectsResult> {\n return runDeferredReadTransaction(this.db, () => this.reader.facetObjects(params))\n }\n\n async getByPrimaryId(params: {\n projectId: string\n objectTypeId: string\n primaryId: string\n }): Promise<ObjectRow | null> {\n return this.reader.getByPrimaryId(params)\n }\n\n async getByUniqueValue(\n params: Parameters<ObjectReadStorage[\"getByUniqueValue\"]>[0]\n ): Promise<ObjectRow | null> {\n return this.reader.getByUniqueValue(params)\n }\n\n async selectsObjectProperties(\n params: Parameters<ObjectReadStorage[\"selectsObjectProperties\"]>[0]\n ): Promise<readonly boolean[]> {\n return this.reader.selectsObjectProperties(params)\n }\n\n async listLinks(params: {\n projectId: string\n objectTypeId: string\n objectId: string\n linkId?: string\n direction?: LinkDirection\n }): Promise<readonly ObjectLinkRow[]> {\n return this.reader.listLinks(params)\n }\n\n async getByPrimaryIdBatch(params: {\n projectId: string\n items: readonly { objectTypeId: string; primaryId: string }[]\n }): Promise<Map<ObjectBatchKey, ObjectRow>> {\n return this.reader.getByPrimaryIdBatch(params)\n }\n\n async listLinksBatch(params: {\n projectId: string\n direction?: LinkDirection\n items: readonly { objectTypeId: string; objectId: string; linkId: string }[]\n }): Promise<Map<LinkBatchKey, ObjectLinkRow[]>> {\n return this.reader.listLinksBatch(params)\n }\n\n async queryLinks(params: QueryObjectLinksInput): Promise<QueryObjectLinksResult> {\n assertLinkQueryLimit(params.limit)\n return this.reader.queryLinks(params)\n }\n\n async listIncidentLinksBatch(params: {\n projectId: string\n items: readonly { objectTypeId: string; objectId: string }[]\n }): Promise<readonly ObjectLinkRow[]> {\n if (params.items.length === 0) return []\n\n const rows = this.db\n .query(\n `\n WITH requested AS (\n SELECT\n json_extract(value, '$.objectTypeId') AS object_type_id,\n json_extract(value, '$.objectId') AS object_id\n FROM json_each(?)\n )\n SELECT link.*\n FROM links AS link\n JOIN requested\n ON requested.object_type_id = link.source_type_id\n AND requested.object_id = link.source_id\n WHERE link.project_id = ?\n UNION\n SELECT link.*\n FROM links AS link\n JOIN requested\n ON requested.object_type_id = link.target_type_id\n AND requested.object_id = link.target_id\n WHERE link.project_id = ?\n `\n )\n .all(JSON.stringify(params.items), params.projectId, params.projectId) as LinkDatabaseRow[]\n\n return rows.map((row) => rowToLink(row))\n }\n\n async listByPrimaryIdPage(params: {\n projectId: string\n objectTypeId: string\n afterPrimaryId?: string\n limit: number\n }): Promise<{ objects: readonly ObjectRow[]; nextPrimaryId?: string }> {\n assertReconciliationPageLimit(params.limit)\n // A cursor written as `? IS NULL OR …` cannot seek, so every page would rescan from the start.\n const cursor = params.afterPrimaryId === undefined ? [] : [params.afterPrimaryId]\n const rows = this.db\n .query(\n `\n SELECT * FROM objects\n WHERE project_id = ? AND object_type_id = ?\n ${cursor.length > 0 ? \"AND primary_id > ?\" : \"\"}\n ORDER BY primary_id ASC\n LIMIT ?\n `\n )\n .all(params.projectId, params.objectTypeId, ...cursor, params.limit + 1) as DatabaseRow[]\n const hasMore = rows.length > params.limit\n const objects = rows.slice(0, params.limit).map((row) => rowToObject(row))\n const last = objects.at(-1)\n return {\n objects,\n ...(hasMore && last ? { nextPrimaryId: last.primaryId } : {}),\n }\n }\n\n async list(params: {\n projectId: string\n objectTypeId?: string | readonly string[]\n primaryIdPrefix?: string\n primaryIdSuffix?: string\n updatedAfter?: Date\n updatedBefore?: Date\n createdAfter?: Date\n createdBefore?: Date\n limit?: number\n offset?: number\n orderBy?: \"createdAt\" | \"updatedAt\" | \"primaryId\"\n order?: \"asc\" | \"desc\"\n }): Promise<{ objects: readonly ObjectRow[]; hasMore: boolean; total: number }> {\n return this.reader.list(params)\n }\n\n /** Close the connection only when this provider owns it. */\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n}\n\nfunction assertReconciliationPageLimit(limit: number): void {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error(\"Object reconciliation page limit must be a positive safe integer.\")\n }\n}\n",
45
+ "import {\n type ObjectExpansion,\n type ObjectQuery,\n ObjectQueryExecutionError,\n type ObjectQueryPredicate,\n type ObjectQuerySetOperation,\n type ObjectQuerySortField,\n} from \"@sixb/core\"\nimport {\n hasVectorProfile,\n isVectorProfileQuery,\n normalizeVector,\n vectorSearchCandidateLimit,\n} from \"@sixb/core/internal/query\"\nimport { encodeSqliteVector } from \"../vector-encoding\"\n\nexport type SqliteValue = string | number | bigint | boolean | null | Uint8Array\n\nexport interface SqliteObjectQueryPageRow {\n object_type_id: string\n primary_id: string\n properties: string\n _cursor_properties?: string\n}\n\nexport interface CompiledObjectQuery {\n vectorProbe?: {\n sql: string\n args: SqliteValue[]\n limit: number\n /** Maximum returned rows and total before the outermost limit, respectively. */\n rowLimit: number\n totalLimit: number\n }\n sql: string\n args: SqliteValue[]\n totalSql: string\n totalArgs: SqliteValue[]\n order: CompiledOrder\n hasMoreProbe?: CompiledHasMoreProbe\n hasMore(rowCount: number, total?: number): boolean\n trimRows<T>(rows: readonly T[]): readonly T[]\n nextPageToken(rows: readonly SqliteObjectQueryPageRow[], rowCount: number): string | undefined\n}\n\ninterface CompiledHasMoreProbe {\n sql: string\n args: SqliteValue[]\n hasMore(rowCount: number): boolean\n}\n\ninterface CompileContext {\n probeLimit: boolean\n source: SqliteObjectQuerySource\n}\n\ninterface CompiledPredicate {\n sql: string\n args: SqliteValue[]\n}\n\ninterface CompiledOrder {\n sql: string\n args: SqliteValue[]\n fields: readonly CompiledOrderField[]\n propertyColumn: string\n}\n\ntype CompiledOrderField =\n | {\n kind: \"property\"\n propertyId: string\n direction: \"asc\" | \"desc\"\n }\n | {\n kind: \"column\"\n column: \"object_type_id\" | \"primary_id\" | \"_vector_score\"\n binary?: boolean\n direction: \"asc\" | \"desc\"\n }\n\ninterface EncodedPageToken {\n version: 1\n order: readonly string[]\n values: readonly EncodedCursorValue[]\n}\n\ninterface EncodedCursorValue {\n nullish: boolean\n value?: unknown\n}\n\nconst PAGE_TOKEN_PREFIX = \"keyset:\"\n\n// Fallback fanout cap for a \"many\" expansion that arrives without an explicit\n// limit. The core executor normally bakes a limit in before pushdown; this only\n// bounds the degenerate uncapped case. Mirrors the PostgreSQL compiler.\nconst DEFAULT_EXPANSION_FANOUT = 1_000\n\nexport function compileObjectQuery(\n projectId: string,\n query: ObjectQuery,\n options: { includeTotal?: boolean; source?: SqliteObjectQuerySource } = {}\n): CompiledObjectQuery {\n if (hasVectorProfile(query) && !isVectorProfileQuery(query)) {\n throw new ObjectQueryExecutionError(\n \"unsupported_vector_composition\",\n \"Vector search supports one profile with filters, traversals or sets before ranking and limit/project after.\"\n )\n }\n const source = options.source ?? DEFAULT_OBJECT_QUERY_SOURCE\n const ctx: CompileContext = { probeLimit: options.includeTotal === false, source }\n return source.wrapQuery(compileObjectQueryInternal(projectId, query, ctx))\n}\n\n/** Physical relations used by the object-query compiler. */\nexport interface SqliteObjectQuerySource {\n readonly objectsTable: string\n readonly linksTable: string\n readonly objectPropertyPermissionsTable?: string\n /**\n * Where to read one concrete type's objects, when the source can say it more precisely than\n * `objectsTable`: a table and that type's own filter over its `properties`. A statement that\n * reads a single type then holds the filter as a top-level condition, which an index can serve.\n */\n objectsOfType?(objectTypeId: string): SqliteTypedObjects\n /** Wrap a terminal SELECT without its own WITH clause; the selected source owns the only WITH. */\n wrapStatement(\n sql: string,\n args?: readonly SqliteValue[]\n ): {\n readonly sql: string\n readonly args: readonly SqliteValue[]\n }\n wrapQuery(query: CompiledObjectQuery): CompiledObjectQuery\n}\n\nexport interface SqliteTypedObjects {\n readonly table: string\n readonly filter?: { readonly sql: string; readonly args: readonly SqliteValue[] }\n}\n\n/** The table and `AND ...` filter a statement reads one type's objects with. */\nexport function sqliteObjectsOfType(\n source: SqliteObjectQuerySource,\n objectTypeId: string\n): { table: string; filter: string; args: readonly SqliteValue[] } {\n const typed = source.objectsOfType?.(objectTypeId)\n if (!typed) return { table: source.objectsTable, filter: \"\", args: [] }\n\n return {\n table: typed.table,\n filter: typed.filter ? `AND (${typed.filter.sql})` : \"\",\n args: typed.filter?.args ?? [],\n }\n}\n\nexport const DEFAULT_OBJECT_QUERY_SOURCE: SqliteObjectQuerySource = {\n objectsTable: \"objects\",\n linksTable: \"links\",\n wrapStatement: (sql, args = []) => ({ sql, args: [...args] }),\n wrapQuery: (query) => query,\n}\n\nfunction exactContext(ctx: CompileContext): CompileContext {\n return ctx.probeLimit ? { ...ctx, probeLimit: false } : ctx\n}\n\nfunction compileObjectQueryInternal(\n projectId: string,\n query: ObjectQuery,\n ctx: CompileContext\n): CompiledObjectQuery {\n switch (query.kind) {\n case \"rerank\":\n throw new ObjectQueryExecutionError(\n \"reranking_requires_runtime\",\n \"Reranking must execute in the model runtime, not storage.\"\n )\n case \"start\":\n return compileStart(projectId, query, ctx)\n case \"refs\":\n return compileRefs(projectId, query, ctx)\n case \"filter\":\n return compileFilter(projectId, query.input, query.predicate, ctx)\n case \"sort\":\n return compileSort(projectId, query.input, query.fields, ctx)\n case \"limit\":\n return compileLimit(projectId, query.input, query.limit, ctx)\n case \"page\":\n return compilePage(projectId, query.input, query.pageSize, query.pageToken, ctx)\n case \"traverse\":\n return compileTraversal(\n projectId,\n query.input,\n query.linkId,\n query.direction,\n query.sourceObjectTypeId,\n ctx\n )\n case \"set\":\n return compileSet(projectId, query.op, query.inputs, ctx)\n case \"project\":\n return compileProject(projectId, query.input, query.properties, ctx)\n case \"text\":\n return compileText(\n projectId,\n query.input,\n query.query,\n query.fields,\n query.fieldsByObjectType,\n ctx\n )\n case \"expand\":\n return compileExpand(projectId, query.input, query.expansions, ctx)\n case \"vector\":\n return compileVector(projectId, query, ctx)\n }\n}\n\nfunction compileVector(\n projectId: string,\n query: Extract<ObjectQuery, { kind: \"vector\" }>,\n ctx: CompileContext\n): CompiledObjectQuery {\n if (\n typeof query.vector === \"string\" ||\n !isVectorProfileQuery(query) ||\n !query.configuration ||\n !Number.isSafeInteger(query.k) ||\n query.k < 1 ||\n query.k > 1000 ||\n query.vector.length < 1 ||\n query.vector.length > 16000\n ) {\n throw new ObjectQueryExecutionError(\n \"invalid_vector_query\",\n \"A validated named vector profile is required.\"\n )\n }\n const input = compileObjectQueryInternal(projectId, query.input, exactContext(ctx))\n const permissions = ctx.source.objectPropertyPermissionsTable\n const permissionJoin = permissions\n ? `CROSS JOIN (\n SELECT project_id, object_type_id, primary_id, json_group_array(property_id) AS property_ids\n FROM ${permissions}\n GROUP BY project_id, object_type_id, primary_id\n ) AS vector_permissions ON vector_permissions.project_id = vectors.project_id\n AND vector_permissions.object_type_id = vectors.object_type_id\n AND vector_permissions.primary_id = vectors.primary_id`\n : \"\"\n const authorized = permissions\n ? `AND NOT EXISTS (\n SELECT 1 FROM json_each(vectors.source) AS required\n WHERE required.value NOT IN (SELECT value FROM json_each(vector_permissions.property_ids))\n )`\n : \"\"\n const candidates = `FROM (${input.sql}) AS input\n CROSS JOIN object_vectors AS vectors ON vectors.project_id = input.project_id\n AND vectors.object_type_id = input.object_type_id AND vectors.primary_id = input.primary_id\n ${permissionJoin}\n WHERE vectors.profile = ? AND vectors.configuration = ?\n AND length(vectors.embedding) / 4 = ? ${authorized}`\n const candidateArgs = [...input.args, query.profile!, query.configuration, query.vector.length]\n // Bound distance work, not just returned rows. Exceeding the envelope fails before ranking.\n const limit = vectorSearchCandidateLimit(query.vector.length)\n const values = normalizeVector(query.vector, query.vector.length)\n const order = compileOrder([\n { kind: \"column\", column: \"_vector_score\", direction: \"desc\" },\n ...identityOrderFields().map((field) => ({ ...field, binary: true })),\n ])\n const rankedOrder = compileOrder(order.fields, \"ranked\")\n // Materialize only bounded, authorized candidates once. CASE prevents distance evaluation\n // above the envelope; the reader rejects the count before exposing any rows or scores.\n const sql = `SELECT stored.project_id, stored.object_type_id, stored.primary_id,\n stored.properties, stored.properties AS _cursor_properties,\n stored.created_at, stored.updated_at, stored.version, stored.last_commit_id,\n ranked._vector_candidate_count, ranked._vector_score\n FROM (\n WITH _sixb_vector_candidates AS MATERIALIZED (\n SELECT input.project_id, input.object_type_id, input.primary_id,\n vectors.embedding AS _vector_embedding ${candidates} LIMIT ?\n ), _sixb_vector_budget AS (\n SELECT COUNT(*) AS _vector_candidate_count FROM _sixb_vector_candidates\n )\n SELECT input.project_id, input.object_type_id, input.primary_id, budget._vector_candidate_count,\n CASE WHEN budget._vector_candidate_count <= ?\n THEN max(-1, min(1, 1 - vec_distance_cosine(input._vector_embedding, ?)))\n END AS _vector_score\n FROM _sixb_vector_candidates AS input CROSS JOIN _sixb_vector_budget AS budget\n ORDER BY ${order.sql} LIMIT ?\n ) AS ranked CROSS JOIN ${ctx.source.objectsTable} AS stored\n ON stored.project_id = ranked.project_id AND stored.object_type_id = ranked.object_type_id\n AND stored.primary_id = ranked.primary_id\n ORDER BY ${rankedOrder.sql}`\n const args = [...candidateArgs, limit + 1, limit, encodeSqliteVector(values), query.k]\n return {\n sql,\n args,\n // Top-k cardinality depends on eligibility, not distances or ranking.\n totalSql: `SELECT COUNT(*) AS total FROM (SELECT 1 ${candidates} LIMIT ?) AS eligible`,\n totalArgs: [...candidateArgs, query.k],\n order,\n vectorProbe: {\n sql: `SELECT COUNT(*) AS total FROM (SELECT 1 ${candidates} LIMIT ?) AS candidates`,\n args: [...candidateArgs, limit + 1],\n limit,\n rowLimit: query.k,\n totalLimit: query.k,\n },\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compileStart(\n projectId: string,\n query: Extract<ObjectQuery, { kind: \"start\" }>,\n ctx: CompileContext\n): CompiledObjectQuery {\n if (query.includeSubtypes === true) {\n throw new Error(\"[Sixb] SQLite object storage does not support start.includeSubtypes\")\n }\n\n const order = compileOrder(identityOrderFields())\n const objects = sqliteObjectsOfType(ctx.source, query.objectTypeId)\n const sql = `\n SELECT *, properties AS _cursor_properties\n FROM ${objects.table}\n WHERE project_id = ? AND object_type_id = ? ${objects.filter}\n ORDER BY ${order.sql}\n `\n const args = [projectId, query.objectTypeId, ...objects.args, ...order.args]\n\n return {\n sql,\n args,\n totalSql: `SELECT COUNT(*) as total FROM ${objects.table} WHERE project_id = ? AND object_type_id = ? ${objects.filter}`,\n totalArgs: [projectId, query.objectTypeId, ...objects.args],\n order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compileRefs(\n projectId: string,\n query: Extract<ObjectQuery, { kind: \"refs\" }>,\n ctx: CompileContext\n): CompiledObjectQuery {\n if (query.refs.length === 0) {\n throw new Error(\"[Sixb] SQLite object storage requires at least one ref\")\n }\n\n const order = compileOrder(identityOrderFields())\n const selectedOrder = compileOrder(identityOrderFields(), \"selected\")\n const refsJson = JSON.stringify(query.refs)\n const requested = `\n SELECT DISTINCT\n json_extract(ref.value, '$.objectTypeId') AS object_type_id,\n json_extract(ref.value, '$.primaryId') AS primary_id\n FROM json_each(?) AS ref\n `\n const sql = `\n SELECT selected.*, selected.properties AS _cursor_properties\n FROM (${requested}) AS requested\n JOIN ${ctx.source.objectsTable} AS selected\n ON selected.project_id = ?\n AND selected.object_type_id = requested.object_type_id\n AND selected.primary_id = requested.primary_id\n ORDER BY ${selectedOrder.sql}\n `\n\n return {\n sql,\n args: [refsJson, projectId, ...selectedOrder.args],\n totalSql: `\n SELECT COUNT(*) AS total\n FROM (${requested}) AS requested\n JOIN ${ctx.source.objectsTable} AS selected\n ON selected.project_id = ?\n AND selected.object_type_id = requested.object_type_id\n AND selected.primary_id = requested.primary_id\n `,\n totalArgs: [refsJson, projectId],\n order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compileFilter(\n projectId: string,\n inputQuery: ObjectQuery,\n predicateNode: ObjectQueryPredicate,\n ctx: CompileContext\n): CompiledObjectQuery {\n const predicate = compilePredicate(predicateNode)\n return compileWhere(projectId, inputQuery, predicate, ctx)\n}\n\nfunction compileWhere(\n projectId: string,\n inputQuery: ObjectQuery,\n predicate: CompiledPredicate,\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const sql = `\n SELECT *\n FROM (${input.sql}) AS input\n WHERE ${predicate.sql}\n ORDER BY ${input.order.sql}\n `\n\n return {\n sql,\n args: [...input.args, ...predicate.args, ...input.order.args],\n totalSql: `\n SELECT COUNT(*) as total\n FROM (${input.sql}) AS input\n WHERE ${predicate.sql}\n `,\n totalArgs: [...input.args, ...predicate.args],\n vectorProbe: input.vectorProbe,\n order: input.order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compileText(\n projectId: string,\n inputQuery: ObjectQuery,\n query: string,\n fields: readonly string[] | undefined,\n fieldsByObjectType: Readonly<Record<string, readonly string[]>> | undefined,\n ctx: CompileContext\n): CompiledObjectQuery {\n const predicate =\n fields && fields.length > 0\n ? compileTextPredicate(query, fields)\n : compileScopedTextPredicate(query, fieldsByObjectType)\n\n if (!predicate) {\n throw new Error(\"[Sixb] SQLite object text search requires fields or resolved text defaults\")\n }\n return compileWhere(projectId, inputQuery, predicate, ctx)\n}\n\nfunction compileSort(\n projectId: string,\n inputQuery: ObjectQuery,\n fields: readonly ObjectQuerySortField[],\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const probeInput =\n ctx.probeLimit && needsLimitProbe(inputQuery)\n ? compileObjectQueryInternal(projectId, inputQuery, ctx)\n : undefined\n const order = compileOrder(sortOrderFields(fields))\n\n return {\n sql: `\n SELECT\n input.project_id,\n input.object_type_id,\n input.primary_id,\n input.properties,\n input.properties AS _cursor_properties,\n input.created_at,\n input.updated_at,\n input.version,\n input.last_commit_id${input.vectorProbe ? \", input._vector_score\" : \"\"}\n FROM (${input.sql}) AS input\n ORDER BY ${order.sql}\n `,\n args: [...input.args, ...order.args],\n totalSql: input.totalSql,\n totalArgs: input.totalArgs,\n order,\n hasMoreProbe: probeInput ? hasMoreProbeFor(probeInput) : input.hasMoreProbe,\n hasMore: input.hasMore,\n trimRows: input.trimRows,\n nextPageToken: input.nextPageToken,\n }\n}\n\nfunction compileLimit(\n projectId: string,\n inputQuery: ObjectQuery,\n rawLimit: number,\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const limit = Math.max(0, rawLimit)\n const rowLimit = ctx.probeLimit ? limit + 1 : limit\n\n return {\n sql: `\n SELECT *\n FROM (${input.sql}) AS input\n ORDER BY ${input.order.sql}\n LIMIT ?\n `,\n args: [...input.args, ...input.order.args, rowLimit],\n totalSql: `\n SELECT COUNT(*) as total\n FROM (${input.sql}) AS input\n `,\n totalArgs: input.args,\n vectorProbe: input.vectorProbe\n ? {\n ...input.vectorProbe,\n rowLimit: Math.min(input.vectorProbe.rowLimit, rowLimit),\n totalLimit: input.vectorProbe.rowLimit,\n }\n : undefined,\n order: input.order,\n hasMore: (rowCount, total) =>\n total === undefined ? ctx.probeLimit && rowCount > limit : limit < total,\n trimRows: ctx.probeLimit ? (rows) => rows.slice(0, limit) : identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compilePage(\n projectId: string,\n inputQuery: ObjectQuery,\n rawPageSize: number,\n pageToken: string | undefined,\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const pageSize = Math.max(0, rawPageSize)\n const cursor = pageToken ? decodePageToken(pageToken, input.order.fields) : undefined\n const cursorPredicate = cursor\n ? compileKeysetPredicate(input.order.fields, cursor, input.order.propertyColumn)\n : undefined\n const whereSql = cursorPredicate ? `WHERE ${cursorPredicate.sql}` : \"\"\n\n return {\n sql: `\n SELECT *\n FROM (${input.sql}) AS input\n ${whereSql}\n ORDER BY ${input.order.sql}\n LIMIT ?\n `,\n args: [...input.args, ...(cursorPredicate?.args ?? []), ...input.order.args, pageSize + 1],\n totalSql: `\n SELECT COUNT(*) as total\n FROM (${input.sql}) AS input\n `,\n totalArgs: input.args,\n vectorProbe: input.vectorProbe,\n order: input.order,\n hasMore: (rowCount) => rowCount > pageSize,\n trimRows: (rows) => rows.slice(0, pageSize),\n nextPageToken: (rows, rowCount) => {\n if (rowCount <= pageSize || rows.length === 0) return undefined\n return encodePageToken(rows[rows.length - 1], input.order.fields)\n },\n }\n}\n\nfunction compileTraversal(\n projectId: string,\n inputQuery: ObjectQuery,\n linkId: string,\n direction: \"outgoing\" | \"incoming\",\n sourceObjectTypeId: string | undefined,\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const outputAlias = direction === \"outgoing\" ? \"target_object\" : \"source_object\"\n const joinSql =\n direction === \"outgoing\"\n ? `\n JOIN ${ctx.source.linksTable} AS edge\n ON edge.project_id = input.project_id\n AND edge.source_type_id = input.object_type_id\n AND edge.source_id = input.primary_id\n AND edge.link_id = ?\n JOIN ${ctx.source.objectsTable} AS target_object\n ON target_object.project_id = edge.project_id\n AND target_object.object_type_id = edge.target_type_id\n AND target_object.primary_id = edge.target_id\n `\n : `\n JOIN ${ctx.source.linksTable} AS edge\n ON edge.project_id = input.project_id\n AND edge.target_type_id = input.object_type_id\n AND edge.target_id = input.primary_id\n AND edge.link_id = ?${sourceObjectTypeId === undefined ? \"\" : \"\\n AND edge.source_type_id = ?\"}\n JOIN ${ctx.source.objectsTable} AS source_object\n ON source_object.project_id = edge.project_id\n AND source_object.object_type_id = edge.source_type_id\n AND source_object.primary_id = edge.source_id\n `\n const order = compileOrder(identityOrderFields())\n const qualifiedOrder = compileOrder(identityOrderFields(), outputAlias)\n const sql = `\n SELECT DISTINCT ${outputAlias}.*, ${outputAlias}.properties AS _cursor_properties\n FROM (${input.sql}) AS input\n ${joinSql}\n ORDER BY ${qualifiedOrder.sql}\n `\n const args = [\n ...input.args,\n linkId,\n ...(sourceObjectTypeId === undefined ? [] : [sourceObjectTypeId]),\n ...qualifiedOrder.args,\n ]\n\n return {\n sql,\n args,\n totalSql: `SELECT COUNT(*) as total FROM (${sql}) AS traversed`,\n totalArgs: args,\n order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\n/** Correlation handle for an expansion: the parent row's identity columns. */\ninterface ExpansionParent {\n project: string\n type: string\n id: string\n}\n\n// `expand` attaches linked objects to each result row without changing which\n// objects match (unlike `traverse`, which pivots to the targets). Each expansion\n// becomes a correlated subquery that hydrates its links into a JSON value, and\n// all expansions are folded into one `_expand` object column the row mapper reads\n// back. The input set is otherwise untouched, so pagination/order pass through.\nfunction compileExpand(\n projectId: string,\n inputQuery: ObjectQuery,\n expansions: readonly ObjectExpansion[],\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, exactContext(ctx))\n const expand = compileExpansionsObject(\n expansions,\n { project: \"input.project_id\", type: \"input.object_type_id\", id: \"input.primary_id\" },\n \"\",\n ctx\n )\n const inputOrder = compileOrder(input.order.fields, \"input\", \"input._cursor_properties\")\n const sql = `\n SELECT input.*, ${expand.sql} AS _expand\n FROM (${input.sql}) AS input\n ORDER BY ${inputOrder.sql}\n `\n\n return {\n sql,\n args: [...expand.args, ...input.args, ...inputOrder.args],\n totalSql: input.totalSql,\n totalArgs: input.totalArgs,\n vectorProbe: input.vectorProbe,\n order: input.order,\n hasMoreProbe: input.hasMoreProbe,\n hasMore: input.hasMore,\n trimRows: input.trimRows,\n nextPageToken: input.nextPageToken,\n }\n}\n\n// `json_object(linkId, value, ...)` over a set of expansions sharing one parent.\n// Link ids are user data, so they ride as parameters. Each value is a correlated\n// subquery whose JSON subtype is lost crossing the subquery boundary, so it is\n// re-parsed with `json(...)` to embed as nested JSON rather than a quoted string.\n// Used both for the outer `_expand` column and for each child's nested `links`.\nfunction compileExpansionsObject(\n expansions: readonly ObjectExpansion[],\n parent: ExpansionParent,\n pathPrefix: string,\n ctx: CompileContext\n): CompiledPredicate {\n const parts: string[] = []\n const args: SqliteValue[] = []\n expansions.forEach((expansion, index) => {\n const path = pathPrefix === \"\" ? `${index}` : `${pathPrefix}_${index}`\n const value = compileExpansionValue(expansion, parent, path, ctx)\n parts.push(\"?\", `json(${value.sql})`)\n args.push(expansion.linkId, ...value.args)\n })\n return { sql: `json_object(${parts.join(\", \")})`, args }\n}\n\n// One expansion's hydrated value. `row_number()` numbers a parent's links by the\n// order from `compileExpansionOrder` (the expansion's `orderBy` against the target\n// object's properties, then an identity tiebreak); `WHERE _ord <= N` keeps the\n// top-N per parent in-DB; each retained neighbour becomes a JSON object; and the\n// value is an ordered array (\"many\") or the first element or null (\"one\"). The\n// cardinality is core-resolved before pushdown.\nfunction compileExpansionValue(\n expansion: ObjectExpansion,\n parent: ExpansionParent,\n path: string,\n ctx: CompileContext\n): CompiledPredicate {\n const edge = `edge_${path}`\n const target = `tgt_${path}`\n const ranked = `ranked_${path}`\n const incoming = expansion.direction === \"incoming\"\n // The hydrated neighbour is the link target (outgoing) or source (incoming);\n // the parent sits on the opposite end, mirroring `compileTraversal`.\n const neighborType = incoming ? `${edge}.source_type_id` : `${edge}.target_type_id`\n const neighborId = incoming ? `${edge}.source_id` : `${edge}.target_id`\n const parentType = incoming ? `${edge}.target_type_id` : `${edge}.source_type_id`\n const parentId = incoming ? `${edge}.target_id` : `${edge}.source_id`\n\n const child = compileExpansionChildJson(expansion, edge, target, path, ctx)\n const order = compileExpansionOrder(expansion, target, neighborType, neighborId)\n\n const whereParts = [\n `${edge}.project_id = ${parent.project}`,\n `${parentType} = ${parent.type}`,\n `${parentId} = ${parent.id}`,\n `${edge}.link_id = ?`,\n ]\n const whereArgs: SqliteValue[] = [expansion.linkId]\n if (incoming && expansion.sourceObjectTypeId !== undefined) {\n whereParts.push(`${edge}.source_type_id = ?`)\n whereArgs.push(expansion.sourceObjectTypeId)\n }\n\n const inner = `\n SELECT ${child.sql} AS elem, row_number() OVER (ORDER BY ${order.sql}) AS _ord\n FROM ${ctx.source.linksTable} AS ${edge}\n JOIN ${ctx.source.objectsTable} AS ${target}\n ON ${target}.project_id = ${edge}.project_id\n AND ${target}.object_type_id = ${neighborType}\n AND ${target}.primary_id = ${neighborId}\n WHERE ${whereParts.join(\" AND \")}\n `\n const innerArgs = [...child.args, ...order.args, ...whereArgs]\n\n if (expansion.cardinality === \"one\") {\n return {\n sql: `(SELECT ${ranked}.elem FROM (${inner}) AS ${ranked} WHERE ${ranked}._ord = 1)`,\n args: innerArgs,\n }\n }\n\n // The fanout cap is baked into `limit` by the core executor before pushdown.\n // Each element is re-parsed with `json(...)` so the aggregate embeds objects\n // rather than the quoted JSON text the subquery column hands back.\n const limit = expansion.limit ?? DEFAULT_EXPANSION_FANOUT\n return {\n sql: `COALESCE((SELECT json_group_array(json(${ranked}.elem) ORDER BY ${ranked}._ord) FROM (${inner}) AS ${ranked} WHERE ${ranked}._ord <= ?), '[]')`,\n args: [...innerArgs, limit],\n }\n}\n\n// Build one hydrated neighbour as an `ExpandedObjectRow`-shaped JSON object. The\n// JSON-valued columns (`properties`, the edge's `linkProperties`) are re-parsed\n// with `json(...)` so they embed as JSON rather than strings; `linkProperties`\n// always rides along (the mapper drops it when null/empty), and nested expansions\n// recurse under `links`, correlated on this neighbour.\nfunction compileExpansionChildJson(\n expansion: ObjectExpansion,\n edge: string,\n target: string,\n path: string,\n ctx: CompileContext\n): CompiledPredicate {\n const fields = [\n `'projectId', ${target}.project_id`,\n `'objectTypeId', ${target}.object_type_id`,\n `'primaryId', ${target}.primary_id`,\n `'properties', json(${target}.properties)`,\n `'createdAt', ${target}.created_at`,\n `'updatedAt', ${target}.updated_at`,\n `'version', ${target}.version`,\n `'lastCommitId', ${target}.last_commit_id`,\n `'linkProperties', json(${edge}.properties)`,\n ]\n const args: SqliteValue[] = []\n\n if (expansion.expand && expansion.expand.length > 0) {\n const nested = compileExpansionsObject(\n expansion.expand,\n {\n project: `${target}.project_id`,\n type: `${target}.object_type_id`,\n id: `${target}.primary_id`,\n },\n path,\n ctx\n )\n fields.push(`'links', ${nested.sql}`)\n args.push(...nested.args)\n }\n\n return { sql: `json_object(${fields.join(\", \")})`, args }\n}\n\n// Order a parent's links the way the fallback's per-parent trim does: each\n// property sorts nulls last with the requested direction (against the neighbour's\n// JSON properties), then a deterministic identity tiebreak on the neighbour.\nfunction compileExpansionOrder(\n expansion: ObjectExpansion,\n target: string,\n neighborType: string,\n neighborId: string\n): CompiledPredicate {\n const propertyColumn = `${target}.properties`\n const clauses: string[] = []\n const args: SqliteValue[] = []\n\n for (const field of expansion.orderBy ?? []) {\n // Relevance is a no-op in the fallback comparator; mirror that by skipping it.\n if (field.kind !== \"property\") continue\n if (field.scalarKind === \"decimal\") {\n throw new ObjectQueryExecutionError(\n \"exact_decimal_not_supported\",\n \"SQLite object storage cannot push down exact decimal expansion sorting\",\n \"$.expand.orderBy\"\n )\n }\n const direction = field.direction === \"desc\" ? \"DESC\" : \"ASC\"\n const path = jsonPath(field.propertyId)\n clauses.push(\n `CASE WHEN ${jsonTypeExpression(propertyColumn)} IS NULL OR ${jsonTypeExpression(propertyColumn)} = 'null' THEN 1 ELSE 0 END ASC`,\n `${jsonValueExpression(propertyColumn)} ${direction}`\n )\n args.push(path, path, path)\n }\n\n clauses.push(`${neighborType} ASC`, `${neighborId} ASC`)\n return { sql: clauses.join(\", \"), args }\n}\n\nfunction compileSet(\n projectId: string,\n op: ObjectQuerySetOperation,\n inputs: readonly ObjectQuery[],\n ctx: CompileContext\n): CompiledObjectQuery {\n if (inputs.length === 0) {\n const order = compileOrder(identityOrderFields())\n return {\n sql: `\n SELECT *\n FROM ${ctx.source.objectsTable}\n WHERE 1 = 0\n ORDER BY ${order.sql}\n `,\n args: order.args,\n totalSql: \"SELECT 0 as total\",\n totalArgs: [],\n order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n }\n\n const compiledInputs = inputs.map((input) =>\n compileObjectQueryInternal(projectId, input, exactContext(ctx))\n )\n const identities = compileSetIdentities(op, compiledInputs)\n const order = compileOrder(identityOrderFields())\n const selectedOrder = compileOrder(identityOrderFields(), \"selected\")\n const sql = `\n SELECT selected.*, selected.properties AS _cursor_properties\n FROM (${identities.sql}) AS ids\n JOIN ${ctx.source.objectsTable} AS selected\n ON selected.project_id = ?\n AND selected.object_type_id = ids.object_type_id\n AND selected.primary_id = ids.primary_id\n ORDER BY ${selectedOrder.sql}\n `\n const args = [...identities.args, projectId, ...selectedOrder.args]\n\n return {\n sql,\n args,\n totalSql: `SELECT COUNT(*) as total FROM (${identities.sql}) AS ids`,\n totalArgs: identities.args,\n order,\n hasMore: () => false,\n trimRows: identityRows,\n nextPageToken: () => undefined,\n }\n}\n\nfunction compileProject(\n projectId: string,\n inputQuery: ObjectQuery,\n properties: readonly string[] | undefined,\n ctx: CompileContext\n): CompiledObjectQuery {\n const input = compileObjectQueryInternal(projectId, inputQuery, ctx)\n if (!properties) return input\n\n const projection = compileProjectionExpression(properties)\n const inputOrder = compileOrder(input.order.fields, \"input\", \"input._cursor_properties\")\n const outputOrder = compileOrder(input.order.fields, undefined, \"_cursor_properties\")\n\n return {\n sql: `\n SELECT\n input.project_id,\n input.object_type_id,\n input.primary_id,\n ${projection.sql} AS properties,\n input._cursor_properties AS _cursor_properties,\n input.created_at,\n input.updated_at,\n input.version,\n input.last_commit_id${input.vectorProbe ? \", input._vector_score, input._vector_candidate_count\" : \"\"}\n FROM (${input.sql}) AS input\n ORDER BY ${inputOrder.sql}\n `,\n args: [...projection.args, ...input.args, ...inputOrder.args],\n totalSql: input.totalSql,\n totalArgs: input.totalArgs,\n vectorProbe: input.vectorProbe,\n order: outputOrder,\n hasMoreProbe: input.hasMoreProbe,\n hasMore: input.hasMore,\n trimRows: input.trimRows,\n nextPageToken: input.nextPageToken,\n }\n}\n\nfunction needsLimitProbe(query: ObjectQuery): boolean {\n switch (query.kind) {\n case \"limit\":\n return true\n case \"project\":\n case \"sort\":\n return needsLimitProbe(query.input)\n default:\n return false\n }\n}\n\nfunction hasMoreProbeFor(compiled: CompiledObjectQuery): CompiledHasMoreProbe {\n return (\n compiled.hasMoreProbe ?? {\n sql: compiled.sql,\n args: compiled.args,\n hasMore: (rowCount) => compiled.hasMore(rowCount, undefined),\n }\n )\n}\n\nfunction compileSetIdentities(\n op: ObjectQuerySetOperation,\n inputs: readonly CompiledObjectQuery[]\n): CompiledPredicate {\n const operator = op === \"union\" ? \"UNION\" : op === \"intersect\" ? \"INTERSECT\" : \"EXCEPT\"\n const identitySqls = inputs.map(\n (input) => `SELECT object_type_id, primary_id FROM (${input.sql}) AS input`\n )\n\n return {\n sql: identitySqls.join(` ${operator} `),\n args: inputs.flatMap((input) => input.args),\n }\n}\n\nfunction compileProjectionExpression(properties: readonly string[]): CompiledPredicate {\n if (properties.length === 0) return { sql: \"json('{}')\", args: [] }\n\n return {\n sql: `\n COALESCE(\n (\n SELECT json_group_object(projected.key, ${sqliteJsonEachValue(\"projected\")})\n FROM json_each(input.properties) AS projected\n WHERE projected.key IN (${properties.map(() => \"?\").join(\", \")})\n ),\n json('{}')\n )\n `,\n args: [...properties],\n }\n}\n\n/** json_each exposes JSON booleans as integer SQL values; restore their JSON representation. */\nexport function sqliteJsonEachValue(alias: string): string {\n return `CASE ${alias}.type\n WHEN 'true' THEN json('true')\n WHEN 'false' THEN json('false')\n ELSE ${alias}.value\n END`\n}\n\n/** Compile a predicate over the unqualified `properties` column of the relation it filters. */\nexport function compilePredicate(predicate: ObjectQueryPredicate): CompiledPredicate {\n if (\n \"scalarKind\" in predicate &&\n predicate.scalarKind === \"decimal\" &&\n (predicate.op === \"lt\" ||\n predicate.op === \"lte\" ||\n predicate.op === \"gt\" ||\n predicate.op === \"gte\")\n ) {\n throw new ObjectQueryExecutionError(\n \"exact_decimal_not_supported\",\n \"SQLite object storage cannot push down exact decimal predicates\",\n \"$.predicate\"\n )\n }\n\n switch (predicate.op) {\n case \"and\":\n case \"or\": {\n const items = predicate.items.map(compilePredicate)\n const joiner = predicate.op === \"and\" ? \" AND \" : \" OR \"\n return {\n sql: `(${items.map((item) => item.sql).join(joiner)})`,\n args: items.flatMap((item) => item.args),\n }\n }\n case \"not\": {\n const item = compilePredicate(predicate.item)\n return negatePredicate(item)\n }\n case \"constant\":\n return { sql: predicate.value ? \"1\" : \"0\", args: [] }\n case \"eq\":\n return predicate.scalarKind === \"userRef\"\n ? compileUserRefInPredicate(predicate.propertyId, [predicate.value])\n : compileEqualityPredicate(predicate.propertyId, \"eq\", predicate.value)\n case \"neq\":\n return predicate.scalarKind === \"userRef\"\n ? negatePredicate(compileUserRefInPredicate(predicate.propertyId, [predicate.value]))\n : compileEqualityPredicate(predicate.propertyId, \"neq\", predicate.value)\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\": {\n const op = sqlComparisonOperator(predicate.op)\n return {\n sql: `${jsonValueExpression()} ${op} ?`,\n args: [jsonPath(predicate.propertyId), sqlValue(predicate.value)],\n }\n }\n case \"in\":\n return predicate.scalarKind === \"userRef\"\n ? compileUserRefInPredicate(predicate.propertyId, predicate.values)\n : compileInPredicate(predicate.propertyId, predicate.values)\n case \"exists\": {\n const sql = `${jsonTypeExpression()} IS NOT NULL`\n const item: CompiledPredicate = { sql, args: [jsonPath(predicate.propertyId)] }\n return predicate.value ? item : negatePredicate(item)\n }\n case \"contains\":\n return predicate.scalarKind === \"userRef\"\n ? compileUserRefContainsPredicate(predicate.propertyId, predicate.value)\n : compileContainsPredicate(predicate.propertyId, predicate.value)\n }\n}\n\n/**\n * User references are JSON objects, so they match on both fields rather than on serialized text,\n * which would depend on key order.\n */\nfunction compileUserRefInPredicate(\n propertyId: string,\n values: readonly unknown[]\n): CompiledPredicate {\n const path = jsonPath(propertyId)\n const ids = values.flatMap((value) => {\n const id = userRefId(value)\n return id === undefined ? [] : [id]\n })\n const clauses: string[] = []\n const args: SqliteValue[] = []\n\n if (values.includes(null)) {\n clauses.push(`${jsonTypeExpression()} = 'null'`)\n args.push(path)\n }\n if (ids.length > 0) {\n clauses.push(\n `(${jsonValueExpression()} = 'user' AND ${jsonValueExpression()} IN (${ids.map(() => \"?\").join(\", \")}))`\n )\n args.push(`${path}.type`, `${path}.id`, ...ids)\n }\n if (clauses.length === 0) return { sql: \"0 = 1\", args: [] }\n\n return { sql: `(${clauses.join(\" OR \")})`, args }\n}\n\nfunction compileUserRefContainsPredicate(propertyId: string, value: unknown): CompiledPredicate {\n const id = userRefId(value)\n if (id === undefined) return { sql: \"0 = 1\", args: [] }\n const path = jsonPath(propertyId)\n return {\n sql: `(${jsonTypeExpression()} = 'array' AND EXISTS (SELECT 1 FROM json_each(properties, ?) AS item WHERE item.type = 'object' AND json_extract(item.value, '$.type') = 'user' AND json_extract(item.value, '$.id') = ?))`,\n args: [path, path, id],\n }\n}\n\nfunction userRefId(value: unknown): string | undefined {\n if (typeof value !== \"object\" || value === null) return undefined\n const { type, id } = value as { type?: unknown; id?: unknown }\n return type === \"user\" && typeof id === \"string\" ? id : undefined\n}\n\nfunction negatePredicate(predicate: CompiledPredicate): CompiledPredicate {\n return {\n sql: `(NOT COALESCE((${predicate.sql}), 0))`,\n args: predicate.args,\n }\n}\n\nfunction compileEqualityPredicate(\n propertyId: string,\n op: \"eq\" | \"neq\",\n value: unknown\n): CompiledPredicate {\n const path = jsonPath(propertyId)\n if (value === null) {\n const sql = `${jsonTypeExpression()} = 'null'`\n const item: CompiledPredicate = { sql, args: [path] }\n return op === \"eq\" ? item : negatePredicate(item)\n }\n\n if (op === \"eq\") {\n return {\n sql: `${jsonValueExpression()} = ?`,\n args: [path, sqlValue(value)],\n }\n }\n\n // JS predicate semantics treat missing/null properties as not equal to any\n // non-null scalar. SQL three-valued null logic needs those cases explicit.\n return {\n sql: `(${jsonTypeExpression()} IS NULL OR ${jsonTypeExpression()} = 'null' OR ${jsonValueExpression()} != ?)`,\n args: [path, path, path, sqlValue(value)],\n }\n}\n\nfunction compileInPredicate(propertyId: string, values: readonly unknown[]): CompiledPredicate {\n if (values.length === 0) return { sql: \"0 = 1\", args: [] }\n\n const path = jsonPath(propertyId)\n const nonNullValues = values.filter((value) => value !== null)\n const clauses: string[] = []\n const args: SqliteValue[] = []\n\n if (values.length !== nonNullValues.length) {\n clauses.push(`${jsonTypeExpression()} = 'null'`)\n args.push(path)\n }\n\n if (nonNullValues.length > 0) {\n clauses.push(`${jsonValueExpression()} IN (${nonNullValues.map(() => \"?\").join(\", \")})`)\n args.push(path, ...nonNullValues.map(sqlValue))\n }\n\n return {\n sql: `(${clauses.join(\" OR \")})`,\n args,\n }\n}\n\nfunction compileContainsPredicate(propertyId: string, value: unknown): CompiledPredicate {\n const path = jsonPath(propertyId)\n const clauses: string[] = []\n const args: SqliteValue[] = []\n\n if (typeof value === \"string\") {\n clauses.push(`(${jsonTypeExpression()} = 'text' AND instr(${jsonValueExpression()}, ?) > 0)`)\n args.push(path, path, value)\n }\n\n clauses.push(\n `(${jsonTypeExpression()} = 'array' AND EXISTS (SELECT 1 FROM json_each(properties, ?) AS item WHERE item.value IS ?))`\n )\n args.push(path, path, sqlValue(value))\n\n if (typeof value === \"string\") {\n clauses.push(\n `(${jsonTypeExpression()} = 'object' AND EXISTS (SELECT 1 FROM json_each(properties, ?) AS item WHERE item.key = ?))`\n )\n args.push(path, path, value)\n }\n\n return { sql: `(${clauses.join(\" OR \")})`, args }\n}\n\nfunction compileTextPredicate(query: string, fields: readonly string[]): CompiledPredicate {\n const terms = tokenize(query)\n if (terms.length === 0) return { sql: \"0 = 1\", args: [] }\n\n const clauses = terms.map(() => {\n const fieldClauses = fields.map(\n () => `instr(lower(COALESCE(CAST(${jsonValueExpression()} AS TEXT), '')), ?) > 0`\n )\n return `(${fieldClauses.join(\" OR \")})`\n })\n const args = terms.flatMap((term) => fields.flatMap((field) => [jsonPath(field), term]))\n\n return { sql: `(${clauses.join(\" AND \")})`, args }\n}\n\nfunction compileScopedTextPredicate(\n query: string,\n fieldsByObjectType: Readonly<Record<string, readonly string[]>> | undefined\n): CompiledPredicate | null {\n const scopedPredicates: CompiledPredicate[] = []\n\n for (const [objectTypeId, fields] of Object.entries(fieldsByObjectType ?? {})) {\n if (fields.length === 0) continue\n const predicate = compileTextPredicate(query, fields)\n scopedPredicates.push({\n sql: `(object_type_id = ? AND ${predicate.sql})`,\n args: [objectTypeId, ...predicate.args],\n })\n }\n\n if (scopedPredicates.length === 0) return null\n\n return {\n sql: `(${scopedPredicates.map((predicate) => predicate.sql).join(\" OR \")})`,\n args: scopedPredicates.flatMap((predicate) => predicate.args),\n }\n}\n\nfunction compileOrder(\n fields: readonly CompiledOrderField[],\n qualifier?: string,\n propertyColumn = \"properties\"\n): CompiledOrder {\n const clauses: string[] = []\n const args: SqliteValue[] = []\n\n for (const field of fields) {\n if (field.kind === \"column\") {\n clauses.push(\n `${columnExpression(field.column, qualifier)}${field.binary ? \" COLLATE BINARY\" : \"\"} ${field.direction.toUpperCase()}`\n )\n continue\n }\n\n const direction = field.direction === \"desc\" ? \"DESC\" : \"ASC\"\n const path = jsonPath(field.propertyId)\n clauses.push(\n `CASE WHEN ${jsonTypeExpression(propertyColumn)} IS NULL OR ${jsonTypeExpression(propertyColumn)} = 'null' THEN 1 ELSE 0 END ASC`,\n `${jsonValueExpression(propertyColumn)} ${direction}`\n )\n args.push(path, path, path)\n }\n\n return { sql: clauses.join(\", \"), args, fields, propertyColumn }\n}\n\nfunction sortOrderFields(fields: readonly ObjectQuerySortField[]): readonly CompiledOrderField[] {\n const orderFields: CompiledOrderField[] = []\n for (const field of fields) {\n if (field.kind !== \"property\") {\n throw new Error(\"[Sixb] SQLite object storage does not support relevance sorting\")\n }\n if (field.scalarKind === \"decimal\") {\n throw new ObjectQueryExecutionError(\n \"exact_decimal_not_supported\",\n \"SQLite object storage cannot push down exact decimal sorting\",\n \"$.sort\"\n )\n }\n\n orderFields.push({\n kind: \"property\",\n propertyId: field.propertyId,\n direction: field.direction === \"desc\" ? \"desc\" : \"asc\",\n })\n }\n orderFields.push(...identityOrderFields())\n return orderFields\n}\n\nfunction identityOrderFields(): readonly CompiledOrderField[] {\n return [\n { kind: \"column\", column: \"object_type_id\", direction: \"asc\" },\n { kind: \"column\", column: \"primary_id\", direction: \"asc\" },\n ]\n}\n\nfunction compileKeysetPredicate(\n fields: readonly CompiledOrderField[],\n cursor: readonly EncodedCursorValue[],\n propertyColumn = \"properties\"\n): CompiledPredicate {\n const disjuncts: CompiledPredicate[] = []\n\n for (let index = 0; index < fields.length; index += 1) {\n const equalityPredicates = fields\n .slice(0, index)\n .map((field, equalityIndex) =>\n compileFieldEquality(field, cursor[equalityIndex], propertyColumn)\n )\n const advancePredicate = compileFieldAfter(fields[index], cursor[index], propertyColumn)\n if (!advancePredicate) continue\n\n const parts = [...equalityPredicates, advancePredicate]\n disjuncts.push({\n sql: `(${parts.map((part) => part.sql).join(\" AND \")})`,\n args: parts.flatMap((part) => part.args),\n })\n }\n\n if (disjuncts.length === 0) return { sql: \"0 = 1\", args: [] }\n\n return {\n sql: `(${disjuncts.map((part) => part.sql).join(\" OR \")})`,\n args: disjuncts.flatMap((part) => part.args),\n }\n}\n\nfunction compileFieldEquality(\n field: CompiledOrderField,\n cursor: EncodedCursorValue,\n propertyColumn = \"properties\"\n): CompiledPredicate {\n if (field.kind === \"column\") {\n return {\n sql: `${columnExpression(field.column)} = ?`,\n args: [sqlValue(cursor.value)],\n }\n }\n\n const path = jsonPath(field.propertyId)\n if (cursor.nullish) {\n return {\n sql: `(${jsonTypeExpression(propertyColumn)} IS NULL OR ${jsonTypeExpression(propertyColumn)} = 'null')`,\n args: [path, path],\n }\n }\n\n return {\n sql: `(${jsonTypeExpression(propertyColumn)} IS NOT NULL AND ${jsonTypeExpression(propertyColumn)} != 'null' AND ${jsonValueExpression(propertyColumn)} = ?)`,\n args: [path, path, path, sqlValue(cursor.value)],\n }\n}\n\nfunction compileFieldAfter(\n field: CompiledOrderField,\n cursor: EncodedCursorValue,\n propertyColumn = \"properties\"\n): CompiledPredicate | null {\n if (field.kind === \"column\") {\n return {\n sql: `${columnExpression(field.column)} ${field.direction === \"desc\" ? \"<\" : \">\"} ?`,\n args: [sqlValue(cursor.value)],\n }\n }\n\n if (cursor.nullish) return null\n\n const path = jsonPath(field.propertyId)\n const rankSql = `CASE WHEN ${jsonTypeExpression(propertyColumn)} IS NULL OR ${jsonTypeExpression(propertyColumn)} = 'null' THEN 1 ELSE 0 END`\n const valueOperator = field.direction === \"desc\" ? \"<\" : \">\"\n\n return {\n sql: `(${rankSql} > 0 OR (${rankSql} = 0 AND ${jsonValueExpression(propertyColumn)} ${valueOperator} ?))`,\n args: [path, path, path, path, path, sqlValue(cursor.value)],\n }\n}\n\nfunction encodePageToken(\n row: SqliteObjectQueryPageRow,\n fields: readonly CompiledOrderField[]\n): string {\n const properties = JSON.parse(row._cursor_properties ?? row.properties) as Record<string, unknown>\n const token: EncodedPageToken = {\n version: 1,\n order: fields.map(orderFieldKey),\n values: fields.map((field) => cursorValueForField(row, properties, field)),\n }\n return `${PAGE_TOKEN_PREFIX}${Buffer.from(JSON.stringify(token)).toString(\"base64url\")}`\n}\n\nfunction decodePageToken(\n token: string,\n fields: readonly CompiledOrderField[]\n): readonly EncodedCursorValue[] {\n if (!token.startsWith(PAGE_TOKEN_PREFIX)) {\n throwInvalidPageToken(\"Invalid SQLite object query page token\")\n }\n\n const raw = token.slice(PAGE_TOKEN_PREFIX.length)\n let decoded: unknown\n try {\n decoded = JSON.parse(Buffer.from(raw, \"base64url\").toString(\"utf8\"))\n } catch {\n throwInvalidPageToken(\"Invalid SQLite object query page token\")\n }\n\n if (!isEncodedPageToken(decoded)) {\n throwInvalidPageToken(\"Invalid SQLite object query page token\")\n }\n\n const expectedOrder = fields.map(orderFieldKey)\n if (\n decoded.order.length !== expectedOrder.length ||\n decoded.order.some((field, index) => field !== expectedOrder[index])\n ) {\n throwInvalidPageToken(\"SQLite object query page token does not match query order\")\n }\n\n return decoded.values\n}\n\nfunction throwInvalidPageToken(message: string): never {\n throw new ObjectQueryExecutionError(\"invalid_page_token\", message, \"$.pageToken\")\n}\n\nfunction isEncodedPageToken(value: unknown): value is EncodedPageToken {\n if (!isPlainObject(value)) return false\n if (value.version !== 1) return false\n if (!Array.isArray(value.order) || value.order.some((item) => typeof item !== \"string\")) {\n return false\n }\n if (!Array.isArray(value.values)) return false\n return value.values.every(\n (item) =>\n isPlainObject(item) &&\n typeof item.nullish === \"boolean\" &&\n (item.nullish || Object.hasOwn(item, \"value\"))\n )\n}\n\nfunction cursorValueForField(\n row: SqliteObjectQueryPageRow,\n properties: Record<string, unknown>,\n field: CompiledOrderField\n): EncodedCursorValue {\n const value =\n field.kind === \"column\"\n ? field.column === \"object_type_id\"\n ? row.object_type_id\n : row.primary_id\n : properties[field.propertyId]\n\n return value === null || value === undefined ? { nullish: true } : { nullish: false, value }\n}\n\nfunction orderFieldKey(field: CompiledOrderField): string {\n return field.kind === \"column\"\n ? `column:${field.column}:${field.direction}`\n : `property:${field.propertyId}:${field.direction}`\n}\n\nfunction columnExpression(\n column: \"object_type_id\" | \"primary_id\" | \"_vector_score\",\n qualifier?: string\n): string {\n return qualifier ? `${qualifier}.${column}` : column\n}\n\nfunction jsonValueExpression(column = \"properties\"): string {\n return `json_extract(${column}, ?)`\n}\n\nfunction jsonTypeExpression(column = \"properties\"): string {\n return `json_type(${column}, ?)`\n}\n\nfunction jsonPath(propertyId: string): string {\n return `$.\"${propertyId.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`\n}\n\nfunction sqlValue(value: unknown): SqliteValue {\n if (value instanceof Date) return value.toISOString()\n if (typeof value === \"boolean\") return value ? 1 : 0\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"bigint\" ||\n value === null\n ) {\n return value\n }\n return JSON.stringify(value)\n}\n\nfunction tokenize(query: string): string[] {\n return query\n .trim()\n .toLowerCase()\n .split(/\\s+/)\n .filter((term) => term.length > 0)\n}\n\nfunction sqlComparisonOperator(op: \"lt\" | \"lte\" | \"gt\" | \"gte\"): \"<\" | \"<=\" | \">\" | \">=\" {\n switch (op) {\n case \"lt\":\n return \"<\"\n case \"lte\":\n return \"<=\"\n case \"gt\":\n return \">\"\n case \"gte\":\n return \">=\"\n }\n}\n\nfunction identityRows<T>(rows: readonly T[]): readonly T[] {\n return rows\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n",
43
46
  "/** Shared little-endian float32 encoding for stored vectors and sqlite-vec query bindings. */\nexport function encodeSqliteVector(values: readonly number[]): Uint8Array {\n const bytes = new Uint8Array(values.length * 4)\n const view = new DataView(bytes.buffer)\n for (let index = 0; index < values.length; index++) {\n view.setFloat32(index * 4, values[index]!, true)\n }\n return bytes\n}\n",
44
- "import type { Database } from \"bun:sqlite\"\nimport { type ObjectQuery, ObjectQueryExecutionError } from \"@sixb/core\"\nimport { hasVectorProfile } from \"@sixb/core/internal/query\"\nimport type {\n CountObjectsInput,\n CountObjectsResult,\n ExistsObjectsInput,\n ExistsObjectsResult,\n FacetObjectsInput,\n FacetObjectsResult,\n LinkBatchKey,\n LinkDirection,\n ObjectBatchKey,\n ObjectFacetRequest,\n ObjectLinkRow,\n ObjectReadStorage,\n ObjectRow,\n QueryObjectLinksInput,\n QueryObjectLinksResult,\n QueryObjectsInput,\n QueryObjectsResult,\n} from \"@sixb/core/storage\"\nimport { linkBatchKey, objectBatchKey } from \"@sixb/core/storage\"\nimport {\n type CompiledObjectQuery,\n compileObjectQuery,\n type SqliteObjectQuerySource,\n type SqliteValue,\n} from \"./query-compiler\"\nimport type { SqliteSelectedObjectReadSource } from \"./read-scope\"\nimport {\n type DatabaseRow,\n type LinkDatabaseRow,\n type ObjectQueryDatabaseRow,\n queryRowToObject,\n rowToLink,\n rowToObject,\n} from \"./rows\"\nimport { ensureSqliteVectorSearch } from \"./vector-extension\"\n\n/** Synchronous SQL reads over one explicit source; transaction and budget ownership stay outside. */\nexport class SqliteObjectReader {\n constructor(\n private readonly db: Database,\n private readonly source: SqliteObjectQuerySource | SqliteSelectedObjectReadSource\n ) {}\n\n private assertVectorSearch(\n params: QueryObjectsInput | CountObjectsInput | ExistsObjectsInput | FacetObjectsInput\n ): void {\n if (!hasVectorProfile(params.query)) return\n const compiled = compileObjectQuery(params.projectId, params.query, { source: this.source })\n if (!compiled.vectorProbe) return\n ensureSqliteVectorSearch(this.db)\n const probe = compiled.vectorProbe\n const row = this.db.query<{ total: number }, SqliteValue[]>(probe.sql).get(...probe.args)\n assertVectorCandidateCount(row?.total, probe.limit)\n }\n\n queryObjects(params: QueryObjectsInput): QueryObjectsResult {\n const source = this.source\n const compiled = compileObjectQuery(params.projectId, params.query, {\n includeTotal: params.includeTotal,\n source,\n })\n if (compiled.vectorProbe) ensureSqliteVectorSearch(this.db)\n const ordinaryTotal =\n params.includeTotal === false || compiled.vectorProbe\n ? undefined\n : readTotal(this.db, compiled)\n const rawRows = this.db.query(compiled.sql).all(...compiled.args) as ObjectQueryDatabaseRow[]\n const vectorTotal = this.vectorResultTotal(compiled, rawRows)\n const total = params.includeTotal === false ? undefined : (vectorTotal ?? ordinaryTotal)\n const rows = compiled.trimRows(rawRows) as readonly ObjectQueryDatabaseRow[]\n const hasMore =\n total === undefined && compiled.hasMoreProbe\n ? compiled.hasMoreProbe.hasMore(\n this.db.query(compiled.hasMoreProbe.sql).all(...compiled.hasMoreProbe.args).length\n )\n : compiled.hasMore(rawRows.length, total)\n\n return {\n objects: rows.map((row) => queryRowToObject(row)),\n hasMore,\n nextPageToken: compiled.nextPageToken(rows, rawRows.length),\n ...(total === undefined ? {} : { total }),\n }\n }\n\n private vectorResultTotal(\n compiled: CompiledObjectQuery,\n rows: readonly ObjectQueryDatabaseRow[]\n ): number | undefined {\n const probe = compiled.vectorProbe\n if (!probe) return undefined\n\n // A zero outer limit can hide the count row. Keep admission and total semantics for that\n // uncommon case, without rescanning candidates for ordinary vector queries.\n let count = rows[0]?._vector_candidate_count\n if (rows.length === 0) {\n count =\n probe.rowLimit === 0\n ? this.db.query<{ total: number }, SqliteValue[]>(probe.sql).get(...probe.args)?.total\n : 0\n }\n assertVectorCandidateCount(count, probe.limit)\n return Math.min(count, probe.totalLimit)\n }\n\n countObjects(params: CountObjectsInput): CountObjectsResult {\n this.assertVectorSearch(params)\n const source = this.source\n return {\n count: readTotal(\n this.db,\n compileObjectQuery(params.projectId, stripOuterRowShape(params.query), {\n source,\n })\n ),\n }\n }\n\n existsObjects(params: ExistsObjectsInput): ExistsObjectsResult {\n this.assertVectorSearch(params)\n const source = this.source\n const compiled = compileObjectQuery(params.projectId, existsProbeQuery(params.query), {\n source,\n })\n return { exists: this.db.query(compiled.sql).get(...compiled.args) !== null }\n }\n\n facetObjects(params: FacetObjectsInput): FacetObjectsResult {\n this.assertVectorSearch(params)\n const source = this.source\n const compiled = compileObjectQuery(params.projectId, stripOuterRowShape(params.query), {\n source,\n })\n return {\n total: readTotal(this.db, compiled),\n facets: params.facets.map((facet) => ({\n propertyId: facet.propertyId,\n buckets: readFacetBuckets(this.db, compiled, facet),\n })),\n }\n }\n\n getByPrimaryId(params: {\n projectId: string\n objectTypeId: string\n primaryId: string\n }): ObjectRow | null {\n const source = this.source\n const objectsTable = source.objectsTable\n const statement = source.wrapStatement(\n `SELECT * FROM ${objectsTable} WHERE project_id = ? AND object_type_id = ? AND primary_id = ?`,\n [params.projectId, params.objectTypeId, params.primaryId]\n )\n const row = this.db.query(statement.sql).get(...statement.args) as DatabaseRow | null\n\n return row ? rowToObject(row) : null\n }\n\n selectsObjectProperties(\n params: Parameters<ObjectReadStorage[\"selectsObjectProperties\"]>[0]\n ): readonly boolean[] {\n const source = this.source\n const result = params.items.map(() => false)\n if (params.items.length === 0) return result\n\n const items = params.items.map((item, batchIndex) => ({ ...item, batchIndex }))\n const requestedType = \"CAST(json_extract(requested.value, '$.objectTypeId') AS TEXT)\"\n const requestedId = \"CAST(json_extract(requested.value, '$.primaryId') AS TEXT)\"\n const requestedProperty = \"CAST(json_extract(requested.value, '$.propertyId') AS TEXT)\"\n const selected = \"objectPropertyPermissionsTable\" in source\n const storedTable = selected ? source.objectPropertyPermissionsTable : source.objectsTable\n const propertyJoin = selected ? `AND stored.property_id = ${requestedProperty}` : \"\"\n const statement = source.wrapStatement(\n `SELECT DISTINCT\n CAST(json_extract(requested.value, '$.batchIndex') AS INTEGER) AS _batch_index\n FROM ${storedTable} AS stored\n JOIN json_each(?) AS requested\n ON stored.object_type_id = ${requestedType}\n AND stored.primary_id = ${requestedId}\n ${propertyJoin}\n WHERE stored.project_id = ?`,\n [JSON.stringify(items), params.projectId]\n )\n const rows = this.db\n .query(statement.sql)\n .all(...statement.args) as PropertyPermissionBatchDatabaseRow[]\n for (const row of rows) result[row._batch_index] = true\n return result\n }\n\n listLinks(params: {\n projectId: string\n objectTypeId: string\n objectId: string\n linkId?: string\n direction?: LinkDirection\n }): readonly ObjectLinkRow[] {\n const source = this.source\n const direction = params.direction ?? \"outgoing\"\n const directionWhere =\n direction === \"incoming\"\n ? \"target_type_id = ? AND target_id = ?\"\n : direction === \"both\"\n ? \"((source_type_id = ? AND source_id = ?) OR (target_type_id = ? AND target_id = ?))\"\n : \"source_type_id = ? AND source_id = ?\"\n let query = `SELECT * FROM ${source.linksTable} WHERE project_id = ? AND ${directionWhere}`\n const args: (string | number)[] =\n direction === \"both\"\n ? [\n params.projectId,\n params.objectTypeId,\n params.objectId,\n params.objectTypeId,\n params.objectId,\n ]\n : [params.projectId, params.objectTypeId, params.objectId]\n\n if (params.linkId) {\n query += \" AND link_id = ?\"\n args.push(params.linkId)\n }\n\n const statement = source.wrapStatement(query, args)\n const rows = this.db.query(statement.sql).all(...statement.args) as LinkDatabaseRow[]\n\n return rows.map((row) => rowToLink(row))\n }\n\n getByPrimaryIdBatch(params: {\n projectId: string\n items: readonly { objectTypeId: string; primaryId: string }[]\n }): Map<ObjectBatchKey, ObjectRow> {\n const source = this.source\n const result = new Map<ObjectBatchKey, ObjectRow>()\n if (params.items.length === 0) return result\n\n const items = params.items.map((item, batchIndex) => ({ ...item, batchIndex }))\n const statement = source.wrapStatement(\n `\n SELECT\n object.*,\n CAST(json_extract(requested.value, '$.batchIndex') AS INTEGER) AS _batch_index\n FROM json_each(?) AS requested\n JOIN ${source.objectsTable} AS object\n ON object.project_id = ?\n AND object.object_type_id = json_extract(requested.value, '$.objectTypeId')\n AND object.primary_id = json_extract(requested.value, '$.primaryId')\n `,\n [JSON.stringify(items), params.projectId]\n )\n const rows = this.db.query(statement.sql).all(...statement.args) as ObjectBatchDatabaseRow[]\n const rowsByIndex = new Map(rows.map((row) => [row._batch_index, row]))\n for (const [index, item] of params.items.entries()) {\n const row = rowsByIndex.get(index)\n if (row) result.set(objectBatchKey(item.objectTypeId, item.primaryId), rowToObject(row))\n }\n return result\n }\n\n listLinksBatch(params: {\n projectId: string\n direction?: LinkDirection\n items: readonly { objectTypeId: string; objectId: string; linkId: string }[]\n }): Map<LinkBatchKey, ObjectLinkRow[]> {\n const source = this.source\n const result = new Map<LinkBatchKey, ObjectLinkRow[]>()\n if (params.items.length === 0) return result\n\n const direction = params.direction ?? \"outgoing\"\n const requestedType = \"CAST(json_extract(requested.value, '$.objectTypeId') AS TEXT)\"\n const requestedId = \"CAST(json_extract(requested.value, '$.objectId') AS TEXT)\"\n const requestedLink = \"CAST(json_extract(requested.value, '$.linkId') AS TEXT)\"\n const outgoing = `stored.source_type_id = ${requestedType} AND stored.source_id = ${requestedId}`\n const incoming = `stored.target_type_id = ${requestedType} AND stored.target_id = ${requestedId}`\n const directionJoin =\n direction === \"both\"\n ? `((${outgoing}) OR (${incoming}))`\n : direction === \"incoming\"\n ? incoming\n : outgoing\n const items = params.items.map((item, batchIndex) => ({ ...item, batchIndex }))\n const statement = source.wrapStatement(\n `\n SELECT\n stored.*,\n CAST(json_extract(requested.value, '$.batchIndex') AS INTEGER) AS _batch_index\n FROM ${source.linksTable} AS stored\n JOIN json_each(?) AS requested\n ON ${directionJoin}\n AND stored.link_id = ${requestedLink}\n WHERE stored.project_id = ?\n ORDER BY _batch_index, source_type_id, source_id, link_id, target_type_id, target_id\n `,\n [JSON.stringify(items), params.projectId]\n )\n const rows = this.db.query(statement.sql).all(...statement.args) as LinkBatchDatabaseRow[]\n const rowsByIndex = params.items.map(() => new Map<string, ObjectLinkRow>())\n for (const row of rows) {\n const link = rowToLink(row)\n rowsByIndex[row._batch_index]?.set(fullLinkIdentity(link), link)\n }\n for (const [index, item] of params.items.entries()) {\n const links = [...(rowsByIndex[index]?.values() ?? [])]\n if (links.length > 0) {\n result.set(linkBatchKey(item.objectTypeId, item.objectId, item.linkId), links)\n }\n }\n return result\n }\n\n queryLinks(params: QueryObjectLinksInput): QueryObjectLinksResult {\n const source = this.source\n if (params.objectRefs.length === 0 || params.endpointObjectTypeIds?.length === 0) {\n return { links: [], hasMore: false }\n }\n\n const requested = `\n SELECT DISTINCT\n json_extract(value, '$.objectTypeId') AS object_type_id,\n json_extract(value, '$.primaryId') AS object_id\n FROM json_each(?)\n `\n const linksTable = source.linksTable\n const sourceJoin = `\n SELECT link.*\n FROM ${linksTable} AS link\n JOIN (${requested}) AS requested\n ON requested.object_type_id = link.source_type_id\n AND requested.object_id = link.source_id\n WHERE link.project_id = ?\n `\n const targetJoin = `\n SELECT link.*\n FROM ${linksTable} AS link\n JOIN (${requested}) AS requested\n ON requested.object_type_id = link.target_type_id\n AND requested.object_id = link.target_id\n WHERE link.project_id = ?\n `\n const incidentSql =\n params.direction === \"outgoing\"\n ? sourceJoin\n : params.direction === \"incoming\"\n ? targetJoin\n : `${sourceJoin} UNION ${targetJoin}`\n const requestedJson = JSON.stringify(params.objectRefs)\n const args: (string | number)[] =\n params.direction === \"both\"\n ? [requestedJson, params.projectId, requestedJson, params.projectId]\n : [requestedJson, params.projectId]\n\n const predicates: string[] = []\n if (params.linkId !== undefined) {\n predicates.push(\"link_id = ?\")\n args.push(params.linkId)\n }\n if (params.endpointObjectTypeIds !== undefined) {\n const allowedTypes = JSON.stringify([...new Set(params.endpointObjectTypeIds)])\n predicates.push(\n \"source_type_id IN (SELECT value FROM json_each(?))\",\n \"target_type_id IN (SELECT value FROM json_each(?))\"\n )\n args.push(allowedTypes, allowedTypes)\n }\n if (params.after) {\n predicates.push(\n \"(source_type_id, source_id, link_id, target_type_id, target_id) > (?, ?, ?, ?, ?)\"\n )\n args.push(...params.after)\n }\n args.push(params.limit + 1)\n\n const whereSql = predicates.length > 0 ? `WHERE ${predicates.join(\" AND \")}` : \"\"\n const statement = source.wrapStatement(\n `\n SELECT *\n FROM (${incidentSql}) AS incident\n ${whereSql}\n ORDER BY source_type_id, source_id, link_id, target_type_id, target_id\n LIMIT ?\n `,\n args\n )\n const rows = this.db.query(statement.sql).all(...statement.args) as LinkDatabaseRow[]\n\n return {\n links: rows.slice(0, params.limit).map((row) => rowToLink(row)),\n hasMore: rows.length > params.limit,\n }\n }\n\n list(params: Parameters<ObjectReadStorage[\"list\"]>[0]): {\n objects: readonly ObjectRow[]\n hasMore: boolean\n total: number\n } {\n const source = this.source\n let query = `SELECT * FROM ${source.objectsTable} WHERE project_id = ?`\n const args: (string | number | null)[] = [params.projectId]\n\n if (params.objectTypeId) {\n if (typeof params.objectTypeId === \"string\") {\n query += \" AND object_type_id = ?\"\n args.push(params.objectTypeId)\n } else {\n query += ` AND object_type_id IN (${params.objectTypeId.map(() => \"?\").join(\", \")})`\n args.push(...params.objectTypeId)\n }\n }\n\n if (params.primaryIdPrefix) {\n query += \" AND primary_id LIKE ?\"\n args.push(`${params.primaryIdPrefix}%`)\n }\n\n if (params.primaryIdSuffix) {\n query += \" AND primary_id LIKE ?\"\n args.push(`%${params.primaryIdSuffix}`)\n }\n\n if (params.updatedAfter) {\n query += \" AND updated_at >= ?\"\n args.push(params.updatedAfter.toISOString())\n }\n\n if (params.updatedBefore) {\n query += \" AND updated_at <= ?\"\n args.push(params.updatedBefore.toISOString())\n }\n\n if (params.createdAfter) {\n query += \" AND created_at >= ?\"\n args.push(params.createdAfter.toISOString())\n }\n\n if (params.createdBefore) {\n query += \" AND created_at <= ?\"\n args.push(params.createdBefore.toISOString())\n }\n\n // Get total count\n const countStatement = source.wrapStatement(\n `SELECT COUNT(*) as total FROM (${query}) AS filtered_objects`,\n args\n )\n const countResult = this.db.query(countStatement.sql).get(...countStatement.args) as {\n total: number\n }\n const total = countResult.total\n\n const offset = params.offset ?? 0\n const limit = params.limit ?? 50\n if (limit === 0) return { objects: [], hasMore: offset < total, total }\n\n // Add ordering\n const orderBy = params.orderBy ?? \"updatedAt\"\n const order = params.order ?? \"desc\"\n const orderColumn =\n orderBy === \"primaryId\" ? \"primary_id\" : orderBy === \"createdAt\" ? \"created_at\" : \"updated_at\"\n query += ` ORDER BY ${orderColumn} ${order.toUpperCase()}`\n\n // Add pagination\n query += \" LIMIT ? OFFSET ?\"\n args.push(limit + 1, offset) // +1 to check for hasMore\n\n const rowsStatement = source.wrapStatement(query, args)\n const rows = this.db.query(rowsStatement.sql).all(...rowsStatement.args) as DatabaseRow[]\n const hasMore = rows.length > limit\n const objects = rows.slice(0, limit).map((row) => rowToObject(row))\n\n return { objects, hasMore, total }\n }\n}\n\nfunction fullLinkIdentity(link: ObjectLinkRow): string {\n return JSON.stringify([\n link.sourceTypeId,\n link.sourceId,\n link.linkId,\n link.targetTypeId,\n link.targetId,\n ])\n}\n\nexport function assertLinkQueryLimit(limit: number): void {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error(\"Object link query limit must be a positive safe integer.\")\n }\n}\n\nfunction readTotal(db: Database, compiled: CompiledObjectQuery): number {\n const row = db.query(compiled.totalSql).get(...compiled.totalArgs) as { total: number }\n return row.total\n}\n\nfunction readFacetBuckets(\n db: Database,\n compiled: CompiledObjectQuery,\n facet: ObjectFacetRequest\n): { value: unknown; count: number }[] {\n const path = sqliteJsonPath(facet.propertyId)\n const rows = db\n .query(\n `\n SELECT\n json_type(input.properties, ?) AS value_type,\n json_extract(input.properties, ?) AS value,\n COUNT(*) AS count\n FROM (${compiled.sql}) AS input\n WHERE json_type(input.properties, ?) IS NOT NULL\n GROUP BY value_type, value\n ORDER BY count DESC, CAST(value AS TEXT) ASC\n LIMIT ?\n `\n )\n .all(path, path, ...compiled.args, path, facet.limit) as FacetDatabaseRow[]\n\n return rows.map((row) => ({\n value: sqliteFacetValue(row.value_type, row.value),\n count: Number(row.count),\n }))\n}\n\nfunction sqliteJsonPath(propertyId: string): string {\n return `$.\"${propertyId.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`\n}\n\nfunction sqliteFacetValue(valueType: string | null, value: unknown): unknown {\n if (valueType === \"true\") return true\n if (valueType === \"false\") return false\n if (valueType === \"null\") return null\n // json_extract returns structured values, such as user references, as JSON text.\n if ((valueType === \"object\" || valueType === \"array\") && typeof value === \"string\") {\n return JSON.parse(value)\n }\n return value\n}\n\nfunction assertVectorCandidateCount(count: unknown, limit: number): asserts count is number {\n if (typeof count !== \"number\" || !Number.isSafeInteger(count) || count < 0) {\n throw new ObjectQueryExecutionError(\n \"invalid_vector_candidate_count\",\n \"Storage did not return a valid vector candidate count.\"\n )\n }\n if (count > limit) {\n throw new ObjectQueryExecutionError(\n \"vector_work_limit_exceeded\",\n `Exact vector search supports at most ${limit} eligible vectors at this dimension. Narrow the query filters.`\n )\n }\n}\n\nfunction existsProbeQuery(query: ObjectQuery): ObjectQuery {\n return { kind: \"limit\", limit: 1, input: stripOuterRowShape(query) }\n}\n\nfunction stripOuterRowShape(query: ObjectQuery): ObjectQuery {\n switch (query.kind) {\n case \"limit\":\n case \"page\":\n case \"project\":\n case \"sort\":\n return stripOuterRowShape(query.input)\n default:\n return query\n }\n}\n\ninterface ObjectBatchDatabaseRow extends DatabaseRow {\n _batch_index: number\n}\n\ninterface PropertyPermissionBatchDatabaseRow {\n _batch_index: number\n}\n\ninterface FacetDatabaseRow {\n value_type: string | null\n value: unknown\n count: number\n}\n\ninterface LinkBatchDatabaseRow extends LinkDatabaseRow {\n _batch_index: number\n}\n",
47
+ "import type {\n CompiledConditionalObjectReadScope,\n CompiledSelectedObjectReadScope,\n} from \"@sixb/core/storage\"\nimport {\n type CompiledObjectQuery,\n compilePredicate,\n type SqliteObjectQuerySource,\n type SqliteValue,\n sqliteJsonEachValue,\n} from \"./query-compiler\"\n\nexport interface SqliteSelectedObjectReadSource extends SqliteObjectQuerySource {\n readonly objectPropertyPermissionsTable: string\n readonly traversalProbe: {\n readonly sql: string\n readonly args: readonly SqliteValue[]\n }\n}\n\n/**\n * Prepare one immutable selected scope as live, path-sensitive SQLite relations.\n *\n * The complete compiled scope is serialized once. Every statement receives that one JSON document\n * and the bound project id, keeping the host-parameter count constant as selections grow.\n * CROSS JOIN keeps authorized parents/grants before indexed edge/object lookups, even when\n * statistics would otherwise make SQLite rescan all grants for every stored object.\n * Property grants are grouped only after path-sensitive reachability has been resolved.\n * Expose identities from grants/visible, so flattened joins can seek those relations by key\n * before loading stored values. Exposing stored identities makes traversal rescan grants per edge.\n */\nexport function compileSqliteSelectedObjectReadSource(\n projectId: string,\n scope: CompiledSelectedObjectReadScope,\n maxTraversalFacts: number\n): SqliteSelectedObjectReadSource {\n const scopeJson = JSON.stringify({\n roots: scope.roots,\n objects: scope.objects,\n steps: scope.steps,\n })\n const source = scopedQuerySource(compileSelectedReadScopeCte(scopeJson, projectId))\n\n return Object.freeze({\n ...source,\n objectPropertyPermissionsTable: \"_sixb_scope_object_permissions\",\n traversalProbe: source.wrapStatement(\n `\n SELECT COUNT(*) AS total\n FROM (\n SELECT 1 AS traversal_fact\n FROM _sixb_scope_root_facts\n\n UNION ALL\n\n SELECT 1 AS traversal_fact\n FROM _sixb_scope_reached_links\n\n LIMIT ?\n ) AS bounded_traversal_facts\n `,\n [BigInt(maxTraversalFacts) + 1n]\n ),\n })\n}\n\n/**\n * Prepare a conditional scope as SQLite relations that filter stored rows as they are read.\n *\n * Both relations are NOT MATERIALIZED, so SQLite flattens them into each statement: its filters,\n * index seeks and LIMIT reach the stored tables, and the conditions become one more filter. An\n * object of a conditioned type is visible while its condition matches; a link while each of its\n * conditioned endpoints is a visible object.\n */\nexport function compileSqliteConditionalObjectReadSource(\n projectId: string,\n scope: CompiledConditionalObjectReadScope\n): SqliteObjectQuerySource {\n const filters = new Map(\n scope.conditions.map((condition) => [\n condition.objectTypeId,\n compilePredicate(condition.predicate),\n ])\n )\n\n return Object.freeze({\n ...scopedQuerySource(compileConditionalReadScopeCte(projectId, filters)),\n // One type's visible objects are the stored ones its own condition matches.\n objectsOfType: (objectTypeId: string) => {\n const filter = filters.get(objectTypeId)\n return filter ? { table: \"objects\", filter } : { table: \"objects\" }\n },\n })\n}\n\ninterface CompiledReadScopeCte {\n readonly sql: string\n readonly args: readonly SqliteValue[]\n}\n\n/** Prefix every statement of a query with the scope's relations, ahead of its own arguments. */\nfunction scopedQuerySource(compiled: CompiledReadScopeCte): SqliteObjectQuerySource {\n const wrapStatement = (sql: string, args: readonly SqliteValue[] = []) => ({\n sql: `${compiled.sql}\\n${sql}`,\n args: [...compiled.args, ...args],\n })\n\n return {\n objectsTable: \"_sixb_scope_objects\",\n linksTable: \"_sixb_scope_links\",\n wrapStatement,\n wrapQuery: (query: CompiledObjectQuery): CompiledObjectQuery => ({\n ...query,\n ...wrapStatement(query.sql, query.args),\n vectorProbe: query.vectorProbe\n ? { ...query.vectorProbe, ...wrapStatement(query.vectorProbe.sql, query.vectorProbe.args) }\n : undefined,\n totalSql: `${compiled.sql}\\n${query.totalSql}`,\n totalArgs: [...compiled.args, ...query.totalArgs],\n ...(query.hasMoreProbe\n ? {\n hasMoreProbe: {\n ...query.hasMoreProbe,\n ...wrapStatement(query.hasMoreProbe.sql, query.hasMoreProbe.args),\n },\n }\n : {}),\n }),\n }\n}\n\n/** Conditions keyed by their concrete type, each compiled over that type's `properties`. */\ntype ConditionFilters = ReadonlyMap<\n string,\n { readonly sql: string; readonly args: readonly SqliteValue[] }\n>\n\nfunction compileConditionalReadScopeCte(\n projectId: string,\n filters: ConditionFilters\n): CompiledReadScopeCte {\n if (filters.size === 0) {\n return {\n sql: `\n WITH\n _sixb_scope_objects AS NOT MATERIALIZED (\n SELECT * FROM objects WHERE project_id = ?\n ),\n _sixb_scope_links AS NOT MATERIALIZED (\n SELECT * FROM links WHERE project_id = ?\n )\n `,\n args: [projectId, projectId],\n }\n }\n\n const conditionedTypeArgs = [...filters.keys()]\n const conditionedTypes = conditionedTypeArgs.map(() => \"?\").join(\", \")\n\n const matches: string[] = []\n const matchArgs: SqliteValue[] = []\n for (const [objectTypeId, filter] of filters) {\n matches.push(`(object_type_id = ? AND ${filter.sql})`)\n matchArgs.push(objectTypeId, ...filter.args)\n }\n\n const visibleEndpoint = (end: \"source\" | \"target\") => `\n (\n stored.${end}_type_id NOT IN (${conditionedTypes})\n OR EXISTS (\n SELECT 1\n FROM _sixb_scope_objects AS endpoint\n WHERE endpoint.project_id = stored.project_id\n AND endpoint.object_type_id = stored.${end}_type_id\n AND endpoint.primary_id = stored.${end}_id\n )\n )\n `\n\n return {\n sql: `\n WITH\n _sixb_scope_objects AS NOT MATERIALIZED (\n SELECT *\n FROM objects\n WHERE project_id = ?\n AND (object_type_id NOT IN (${conditionedTypes}) OR ${matches.join(\" OR \")})\n ),\n _sixb_scope_links AS NOT MATERIALIZED (\n SELECT stored.*\n FROM links AS stored\n WHERE stored.project_id = ?\n AND ${visibleEndpoint(\"source\")}\n AND ${visibleEndpoint(\"target\")}\n )\n `,\n args: [\n projectId,\n ...conditionedTypeArgs,\n ...matchArgs,\n projectId,\n ...conditionedTypeArgs,\n ...conditionedTypeArgs,\n ],\n }\n}\n\nfunction compileSelectedReadScopeCte(scopeJson: string, projectId: string): CompiledReadScopeCte {\n return {\n sql: `\n WITH RECURSIVE\n _sixb_scope_document(scope) AS (\n SELECT json(?)\n ),\n _sixb_scope_roots(root_id, node_id, object_type_id, primary_id) AS (\n SELECT\n CAST(root.key AS INTEGER),\n CAST(json_extract(root.value, '$.nodeId') AS INTEGER),\n CAST(json_extract(root.value, '$.objectTypeId') AS TEXT),\n CAST(json_extract(root.value, '$.primaryId') AS TEXT)\n FROM _sixb_scope_document AS document,\n json_each(json_extract(document.scope, '$.roots')) AS root\n ),\n _sixb_scope_root_facts(project_id, root_id, node_id, object_type_id, primary_id) AS (\n SELECT anchor.project_id, root.root_id, root.node_id, root.object_type_id, root.primary_id\n FROM _sixb_scope_roots AS root\n CROSS JOIN objects AS anchor\n ON anchor.project_id = ?\n AND anchor.object_type_id = root.object_type_id\n AND anchor.primary_id = root.primary_id\n ),\n _sixb_scope_object_selections(node_id, object_type_id, property_ids) AS (\n SELECT\n CAST(json_extract(selection.value, '$.nodeId') AS INTEGER),\n CAST(json_extract(selection.value, '$.objectTypeId') AS TEXT),\n json_extract(selection.value, '$.propertyIds')\n FROM _sixb_scope_document AS document,\n json_each(json_extract(document.scope, '$.objects')) AS selection\n ),\n _sixb_scope_link_selections(\n step_id,\n node_id,\n parent_node_id,\n source_object_type_id,\n link_id,\n target_object_type_id,\n property_ids\n ) AS (\n SELECT\n CAST(step.key AS INTEGER),\n CAST(json_extract(step.value, '$.nodeId') AS INTEGER),\n CAST(json_extract(step.value, '$.parentNodeId') AS INTEGER),\n CAST(json_extract(step.value, '$.sourceObjectTypeId') AS TEXT),\n CAST(json_extract(step.value, '$.linkId') AS TEXT),\n CAST(json_extract(step.value, '$.targetObjectTypeId') AS TEXT),\n json_extract(step.value, '$.propertyIds')\n FROM _sixb_scope_document AS document,\n json_each(json_extract(document.scope, '$.steps')) AS step\n ),\n _sixb_scope_reachable(project_id, node_id, object_type_id, primary_id) AS (\n SELECT root.project_id, root.node_id, root.object_type_id, root.primary_id\n FROM _sixb_scope_root_facts AS root\n\n UNION\n\n SELECT edge.project_id, selection.node_id, edge.target_type_id, edge.target_id\n FROM _sixb_scope_reachable AS parent\n CROSS JOIN _sixb_scope_link_selections AS selection\n ON selection.parent_node_id = parent.node_id\n AND selection.source_object_type_id = parent.object_type_id\n CROSS JOIN links AS edge\n ON edge.project_id = parent.project_id\n AND edge.source_type_id = parent.object_type_id\n AND edge.source_id = parent.primary_id\n AND edge.link_id = selection.link_id\n AND edge.target_type_id = selection.target_object_type_id\n CROSS JOIN objects AS target\n ON target.project_id = edge.project_id\n AND target.object_type_id = edge.target_type_id\n AND target.primary_id = edge.target_id\n ),\n _sixb_scope_object_permissions(project_id, object_type_id, primary_id, property_id) AS (\n SELECT DISTINCT\n reachable.project_id,\n reachable.object_type_id,\n reachable.primary_id,\n CAST(selected_property.value AS TEXT)\n FROM _sixb_scope_reachable AS reachable\n JOIN _sixb_scope_object_selections AS selection\n ON selection.node_id = reachable.node_id\n AND selection.object_type_id = reachable.object_type_id\n JOIN json_each(selection.property_ids) AS selected_property\n ),\n _sixb_scope_object_ids(project_id, object_type_id, primary_id) AS (\n SELECT DISTINCT project_id, object_type_id, primary_id\n FROM _sixb_scope_reachable\n ),\n _sixb_scope_object_grants AS (\n SELECT reachable.project_id, reachable.object_type_id, reachable.primary_id,\n json_group_array(DISTINCT selected_property.value) FILTER (WHERE selected_property.value IS NOT NULL) AS property_ids\n FROM _sixb_scope_reachable AS reachable\n LEFT JOIN _sixb_scope_object_selections AS selection\n ON selection.node_id = reachable.node_id\n AND selection.object_type_id = reachable.object_type_id\n LEFT JOIN json_each(selection.property_ids) AS selected_property ON true\n GROUP BY reachable.project_id, reachable.object_type_id, reachable.primary_id\n ),\n _sixb_scope_objects AS (\n SELECT grants.project_id, grants.object_type_id, grants.primary_id,\n COALESCE((\n SELECT json_group_object(property.key, ${sqliteJsonEachValue(\"property\")})\n FROM json_each(stored.properties) AS property\n WHERE property.key IN (SELECT value FROM json_each(grants.property_ids))\n ), json('{}')) AS properties,\n stored.created_at, stored.updated_at, stored.version, stored.last_commit_id\n FROM _sixb_scope_object_grants AS grants\n CROSS JOIN objects AS stored\n ON stored.project_id = grants.project_id\n AND stored.object_type_id = grants.object_type_id\n AND stored.primary_id = grants.primary_id\n ),\n _sixb_scope_reached_links(\n project_id,\n step_id,\n node_id,\n parent_node_id,\n source_type_id,\n source_id,\n link_id,\n target_type_id,\n target_id,\n property_ids\n ) AS (\n SELECT\n edge.project_id,\n selection.step_id,\n selection.node_id,\n selection.parent_node_id,\n edge.source_type_id,\n edge.source_id,\n edge.link_id,\n edge.target_type_id,\n edge.target_id,\n selection.property_ids\n FROM _sixb_scope_reachable AS parent\n CROSS JOIN _sixb_scope_link_selections AS selection\n ON selection.parent_node_id = parent.node_id\n AND selection.source_object_type_id = parent.object_type_id\n CROSS JOIN links AS edge\n ON edge.project_id = parent.project_id\n AND edge.source_type_id = parent.object_type_id\n AND edge.source_id = parent.primary_id\n AND edge.link_id = selection.link_id\n AND edge.target_type_id = selection.target_object_type_id\n CROSS JOIN objects AS target\n ON target.project_id = edge.project_id\n AND target.object_type_id = edge.target_type_id\n AND target.primary_id = edge.target_id\n ),\n _sixb_scope_link_permissions(\n project_id,\n source_type_id,\n source_id,\n link_id,\n target_type_id,\n target_id,\n property_id\n ) AS (\n SELECT DISTINCT\n reached.project_id,\n reached.source_type_id,\n reached.source_id,\n reached.link_id,\n reached.target_type_id,\n reached.target_id,\n CAST(selected_property.value AS TEXT)\n FROM _sixb_scope_reached_links AS reached\n JOIN json_each(reached.property_ids) AS selected_property\n ),\n _sixb_scope_link_ids(\n project_id,\n source_type_id,\n source_id,\n link_id,\n target_type_id,\n target_id\n ) AS (\n SELECT DISTINCT\n project_id,\n source_type_id,\n source_id,\n link_id,\n target_type_id,\n target_id\n FROM _sixb_scope_reached_links\n ),\n _sixb_scope_links AS (\n SELECT\n visible.project_id,\n visible.source_type_id,\n visible.source_id,\n visible.link_id,\n visible.target_type_id,\n visible.target_id,\n CASE\n WHEN stored.properties IS NULL THEN NULL\n ELSE NULLIF(\n (\n SELECT json_group_object(property.key, ${sqliteJsonEachValue(\"property\")})\n FROM json_each(stored.properties) AS property\n JOIN _sixb_scope_link_permissions AS permission\n ON permission.project_id = stored.project_id\n AND permission.source_type_id = stored.source_type_id\n AND permission.source_id = stored.source_id\n AND permission.link_id = stored.link_id\n AND permission.target_type_id = stored.target_type_id\n AND permission.target_id = stored.target_id\n AND permission.property_id = property.key\n ),\n json('{}')\n )\n END AS properties,\n stored.created_at,\n stored.updated_at,\n stored.last_commit_id\n FROM links AS stored\n JOIN _sixb_scope_link_ids AS visible\n ON visible.project_id = stored.project_id\n AND visible.source_type_id = stored.source_type_id\n AND visible.source_id = stored.source_id\n AND visible.link_id = stored.link_id\n AND visible.target_type_id = stored.target_type_id\n AND visible.target_id = stored.target_id\n )\n `,\n args: [scopeJson, projectId],\n }\n}\n",
48
+ "import type { Database } from \"bun:sqlite\"\nimport type {\n ObjectQueryCapabilities,\n ObjectReadExecutionLimits,\n ObjectReadStorage,\n} from \"@sixb/core/storage\"\nimport {\n assertObjectReaderProject,\n assertObjectReadFacetCount,\n assertObjectReadOutputWithinLimit,\n} from \"@sixb/core/storage\"\nimport { runDeferredReadTransaction } from \"../transactions\"\nimport type { SqliteObjectQuerySource } from \"./query-compiler\"\nimport { assertLinkQueryLimit, SqliteObjectReader } from \"./reader\"\n\n/**\n * Answer every terminal from one scoped source, each in its own synchronous snapshot so the\n * statements of one read, and the scope's own checks before them, agree.\n */\nexport function createSqliteScopedReader(\n db: Database,\n params: {\n projectId: string\n source: SqliteObjectQuerySource\n /** Runs first in each read's snapshot. */\n beforeRead?: () => void\n limits?: ObjectReadExecutionLimits\n },\n queryCapabilities: () => ObjectQueryCapabilities\n): ObjectReadStorage {\n const { projectId, source, beforeRead, limits } = params\n const reader = new SqliteObjectReader(db, source)\n const assertProject = (actualProjectId: string): void =>\n assertObjectReaderProject(projectId, actualProjectId)\n const read = <T>(run: () => T): T =>\n runDeferredReadTransaction(db, () => {\n beforeRead?.()\n const value = run()\n if (limits) assertObjectReadOutputWithinLimit(value, limits)\n return value\n })\n const readMap = <TKey, TValue>(run: () => Map<TKey, TValue>): Map<TKey, TValue> =>\n runDeferredReadTransaction(db, () => {\n beforeRead?.()\n const value = run()\n if (limits) assertObjectReadOutputWithinLimit([...value.entries()], limits)\n return value\n })\n\n return Object.freeze({\n queryCapabilities,\n queryObjects: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.queryObjects(input))\n },\n countObjects: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.countObjects(input))\n },\n existsObjects: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.existsObjects(input))\n },\n facetObjects: async (input) => {\n assertProject(input.projectId)\n assertObjectReadFacetCount(input.facets.length)\n return read(() => reader.facetObjects(input))\n },\n getByPrimaryId: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.getByPrimaryId(input))\n },\n getByUniqueValue: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.getByUniqueValue(input))\n },\n selectsObjectProperties: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.selectsObjectProperties(input))\n },\n listLinks: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.listLinks(input))\n },\n getByPrimaryIdBatch: async (input) => {\n assertProject(input.projectId)\n return readMap(() => reader.getByPrimaryIdBatch(input))\n },\n listLinksBatch: async (input) => {\n assertProject(input.projectId)\n return readMap(() => reader.listLinksBatch(input))\n },\n queryLinks: async (input) => {\n assertProject(input.projectId)\n assertLinkQueryLimit(input.limit)\n return read(() => reader.queryLinks(input))\n },\n list: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.list(input))\n },\n } satisfies ObjectReadStorage)\n}\n",
49
+ "import type { Database } from \"bun:sqlite\"\nimport { type ObjectQuery, ObjectQueryExecutionError } from \"@sixb/core\"\nimport { hasVectorProfile } from \"@sixb/core/internal/query\"\nimport type {\n CountObjectsInput,\n CountObjectsResult,\n ExistsObjectsInput,\n ExistsObjectsResult,\n FacetObjectsInput,\n FacetObjectsResult,\n LinkBatchKey,\n LinkDirection,\n ObjectBatchKey,\n ObjectFacetRequest,\n ObjectLinkRow,\n ObjectReadStorage,\n ObjectRow,\n QueryObjectLinksInput,\n QueryObjectLinksResult,\n QueryObjectsInput,\n QueryObjectsResult,\n} from \"@sixb/core/storage\"\nimport { linkBatchKey, objectBatchKey } from \"@sixb/core/storage\"\nimport {\n type CompiledObjectQuery,\n compileObjectQuery,\n type SqliteObjectQuerySource,\n type SqliteValue,\n sqliteObjectsOfType,\n} from \"./query-compiler\"\nimport type { SqliteSelectedObjectReadSource } from \"./read-scope\"\nimport {\n type DatabaseRow,\n type LinkDatabaseRow,\n type ObjectQueryDatabaseRow,\n queryRowToObject,\n rowToLink,\n rowToObject,\n} from \"./rows\"\nimport { ensureSqliteVectorSearch } from \"./vector-extension\"\n\n/** Synchronous SQL reads over one explicit source; transaction and budget ownership stay outside. */\nexport class SqliteObjectReader {\n constructor(\n private readonly db: Database,\n private readonly source: SqliteObjectQuerySource | SqliteSelectedObjectReadSource\n ) {}\n\n private assertVectorSearch(\n params: QueryObjectsInput | CountObjectsInput | ExistsObjectsInput | FacetObjectsInput\n ): void {\n if (!hasVectorProfile(params.query)) return\n const compiled = compileObjectQuery(params.projectId, params.query, { source: this.source })\n if (!compiled.vectorProbe) return\n ensureSqliteVectorSearch(this.db)\n const probe = compiled.vectorProbe\n const row = this.db.query<{ total: number }, SqliteValue[]>(probe.sql).get(...probe.args)\n assertVectorCandidateCount(row?.total, probe.limit)\n }\n\n queryObjects(params: QueryObjectsInput): QueryObjectsResult {\n const source = this.source\n const compiled = compileObjectQuery(params.projectId, params.query, {\n includeTotal: params.includeTotal,\n source,\n })\n if (compiled.vectorProbe) ensureSqliteVectorSearch(this.db)\n const ordinaryTotal =\n params.includeTotal === false || compiled.vectorProbe\n ? undefined\n : readTotal(this.db, compiled)\n const rawRows = this.db.query(compiled.sql).all(...compiled.args) as ObjectQueryDatabaseRow[]\n const vectorTotal = this.vectorResultTotal(compiled, rawRows)\n const total = params.includeTotal === false ? undefined : (vectorTotal ?? ordinaryTotal)\n const rows = compiled.trimRows(rawRows) as readonly ObjectQueryDatabaseRow[]\n const hasMore =\n total === undefined && compiled.hasMoreProbe\n ? compiled.hasMoreProbe.hasMore(\n this.db.query(compiled.hasMoreProbe.sql).all(...compiled.hasMoreProbe.args).length\n )\n : compiled.hasMore(rawRows.length, total)\n\n return {\n objects: rows.map((row) => queryRowToObject(row)),\n hasMore,\n nextPageToken: compiled.nextPageToken(rows, rawRows.length),\n ...(total === undefined ? {} : { total }),\n }\n }\n\n private vectorResultTotal(\n compiled: CompiledObjectQuery,\n rows: readonly ObjectQueryDatabaseRow[]\n ): number | undefined {\n const probe = compiled.vectorProbe\n if (!probe) return undefined\n\n // A zero outer limit can hide the count row. Keep admission and total semantics for that\n // uncommon case, without rescanning candidates for ordinary vector queries.\n let count = rows[0]?._vector_candidate_count\n if (rows.length === 0) {\n count =\n probe.rowLimit === 0\n ? this.db.query<{ total: number }, SqliteValue[]>(probe.sql).get(...probe.args)?.total\n : 0\n }\n assertVectorCandidateCount(count, probe.limit)\n return Math.min(count, probe.totalLimit)\n }\n\n countObjects(params: CountObjectsInput): CountObjectsResult {\n this.assertVectorSearch(params)\n const source = this.source\n return {\n count: readTotal(\n this.db,\n compileObjectQuery(params.projectId, stripOuterRowShape(params.query), {\n source,\n })\n ),\n }\n }\n\n existsObjects(params: ExistsObjectsInput): ExistsObjectsResult {\n this.assertVectorSearch(params)\n const source = this.source\n const compiled = compileObjectQuery(params.projectId, existsProbeQuery(params.query), {\n source,\n })\n return { exists: this.db.query(compiled.sql).get(...compiled.args) !== null }\n }\n\n facetObjects(params: FacetObjectsInput): FacetObjectsResult {\n this.assertVectorSearch(params)\n const source = this.source\n const compiled = compileObjectQuery(params.projectId, stripOuterRowShape(params.query), {\n source,\n })\n return {\n total: readTotal(this.db, compiled),\n facets: params.facets.map((facet) => ({\n propertyId: facet.propertyId,\n buckets: readFacetBuckets(this.db, compiled, facet),\n })),\n }\n }\n\n getByPrimaryId(params: {\n projectId: string\n objectTypeId: string\n primaryId: string\n }): ObjectRow | null {\n const source = this.source\n const objects = sqliteObjectsOfType(source, params.objectTypeId)\n const statement = source.wrapStatement(\n `SELECT * FROM ${objects.table} WHERE project_id = ? AND object_type_id = ? AND primary_id = ? ${objects.filter}`,\n [params.projectId, params.objectTypeId, params.primaryId, ...objects.args]\n )\n const row = this.db.query(statement.sql).get(...statement.args) as DatabaseRow | null\n\n return row ? rowToObject(row) : null\n }\n\n /** On a selected source, the holder must be in scope and selected for the property. */\n getByUniqueValue(params: Parameters<ObjectReadStorage[\"getByUniqueValue\"]>[0]): ObjectRow | null {\n const source = this.source\n const selected = \"objectPropertyPermissionsTable\" in source\n const permitted = selected\n ? `AND EXISTS (\n SELECT 1 FROM ${source.objectPropertyPermissionsTable} AS permitted\n WHERE permitted.project_id = objects.project_id\n AND permitted.object_type_id = objects.object_type_id\n AND permitted.primary_id = objects.primary_id\n AND permitted.property_id = held.property_id\n )`\n : \"\"\n const statement = source.wrapStatement(\n `SELECT objects.*\n FROM object_unique_values AS held\n JOIN ${source.objectsTable} AS objects\n ON objects.project_id = held.project_id\n AND objects.object_type_id = held.object_type_id\n AND objects.primary_id = held.primary_id\n WHERE held.project_id = ? AND held.object_type_id = ? AND held.property_id = ?\n AND held.value_key = ?\n ${permitted}`,\n [params.projectId, params.objectTypeId, params.propertyId, params.valueKey]\n )\n const row = this.db.query(statement.sql).get(...statement.args) as DatabaseRow | null\n\n return row ? rowToObject(row) : null\n }\n\n selectsObjectProperties(\n params: Parameters<ObjectReadStorage[\"selectsObjectProperties\"]>[0]\n ): readonly boolean[] {\n const source = this.source\n const result = params.items.map(() => false)\n if (params.items.length === 0) return result\n\n const items = params.items.map((item, batchIndex) => ({ ...item, batchIndex }))\n const requestedType = \"CAST(json_extract(requested.value, '$.objectTypeId') AS TEXT)\"\n const requestedId = \"CAST(json_extract(requested.value, '$.primaryId') AS TEXT)\"\n const requestedProperty = \"CAST(json_extract(requested.value, '$.propertyId') AS TEXT)\"\n const selected = \"objectPropertyPermissionsTable\" in source\n const storedTable = selected ? source.objectPropertyPermissionsTable : source.objectsTable\n const propertyJoin = selected ? `AND stored.property_id = ${requestedProperty}` : \"\"\n const statement = source.wrapStatement(\n `SELECT DISTINCT\n CAST(json_extract(requested.value, '$.batchIndex') AS INTEGER) AS _batch_index\n FROM ${storedTable} AS stored\n JOIN json_each(?) AS requested\n ON stored.object_type_id = ${requestedType}\n AND stored.primary_id = ${requestedId}\n ${propertyJoin}\n WHERE stored.project_id = ?`,\n [JSON.stringify(items), params.projectId]\n )\n const rows = this.db\n .query(statement.sql)\n .all(...statement.args) as PropertyPermissionBatchDatabaseRow[]\n for (const row of rows) result[row._batch_index] = true\n return result\n }\n\n listLinks(params: {\n projectId: string\n objectTypeId: string\n objectId: string\n linkId?: string\n direction?: LinkDirection\n }): readonly ObjectLinkRow[] {\n const source = this.source\n const direction = params.direction ?? \"outgoing\"\n const directionWhere =\n direction === \"incoming\"\n ? \"target_type_id = ? AND target_id = ?\"\n : direction === \"both\"\n ? \"((source_type_id = ? AND source_id = ?) OR (target_type_id = ? AND target_id = ?))\"\n : \"source_type_id = ? AND source_id = ?\"\n let query = `SELECT * FROM ${source.linksTable} WHERE project_id = ? AND ${directionWhere}`\n const args: (string | number)[] =\n direction === \"both\"\n ? [\n params.projectId,\n params.objectTypeId,\n params.objectId,\n params.objectTypeId,\n params.objectId,\n ]\n : [params.projectId, params.objectTypeId, params.objectId]\n\n if (params.linkId) {\n query += \" AND link_id = ?\"\n args.push(params.linkId)\n }\n\n const statement = source.wrapStatement(query, args)\n const rows = this.db.query(statement.sql).all(...statement.args) as LinkDatabaseRow[]\n\n return rows.map((row) => rowToLink(row))\n }\n\n getByPrimaryIdBatch(params: {\n projectId: string\n items: readonly { objectTypeId: string; primaryId: string }[]\n }): Map<ObjectBatchKey, ObjectRow> {\n const source = this.source\n const result = new Map<ObjectBatchKey, ObjectRow>()\n if (params.items.length === 0) return result\n\n const items = params.items.map((item, batchIndex) => ({ ...item, batchIndex }))\n const statement = source.wrapStatement(\n `\n SELECT\n object.*,\n CAST(json_extract(requested.value, '$.batchIndex') AS INTEGER) AS _batch_index\n FROM json_each(?) AS requested\n JOIN ${source.objectsTable} AS object\n ON object.project_id = ?\n AND object.object_type_id = json_extract(requested.value, '$.objectTypeId')\n AND object.primary_id = json_extract(requested.value, '$.primaryId')\n `,\n [JSON.stringify(items), params.projectId]\n )\n const rows = this.db.query(statement.sql).all(...statement.args) as ObjectBatchDatabaseRow[]\n const rowsByIndex = new Map(rows.map((row) => [row._batch_index, row]))\n for (const [index, item] of params.items.entries()) {\n const row = rowsByIndex.get(index)\n if (row) result.set(objectBatchKey(item.objectTypeId, item.primaryId), rowToObject(row))\n }\n return result\n }\n\n listLinksBatch(params: {\n projectId: string\n direction?: LinkDirection\n items: readonly { objectTypeId: string; objectId: string; linkId: string }[]\n }): Map<LinkBatchKey, ObjectLinkRow[]> {\n const source = this.source\n const result = new Map<LinkBatchKey, ObjectLinkRow[]>()\n if (params.items.length === 0) return result\n\n const direction = params.direction ?? \"outgoing\"\n const requestedType = \"CAST(json_extract(requested.value, '$.objectTypeId') AS TEXT)\"\n const requestedId = \"CAST(json_extract(requested.value, '$.objectId') AS TEXT)\"\n const requestedLink = \"CAST(json_extract(requested.value, '$.linkId') AS TEXT)\"\n const outgoing = `stored.source_type_id = ${requestedType} AND stored.source_id = ${requestedId}`\n const incoming = `stored.target_type_id = ${requestedType} AND stored.target_id = ${requestedId}`\n const directionJoin =\n direction === \"both\"\n ? `((${outgoing}) OR (${incoming}))`\n : direction === \"incoming\"\n ? incoming\n : outgoing\n const items = params.items.map((item, batchIndex) => ({ ...item, batchIndex }))\n const statement = source.wrapStatement(\n `\n SELECT\n stored.*,\n CAST(json_extract(requested.value, '$.batchIndex') AS INTEGER) AS _batch_index\n FROM ${source.linksTable} AS stored\n JOIN json_each(?) AS requested\n ON ${directionJoin}\n AND stored.link_id = ${requestedLink}\n WHERE stored.project_id = ?\n ORDER BY _batch_index, source_type_id, source_id, link_id, target_type_id, target_id\n `,\n [JSON.stringify(items), params.projectId]\n )\n const rows = this.db.query(statement.sql).all(...statement.args) as LinkBatchDatabaseRow[]\n const rowsByIndex = params.items.map(() => new Map<string, ObjectLinkRow>())\n for (const row of rows) {\n const link = rowToLink(row)\n rowsByIndex[row._batch_index]?.set(fullLinkIdentity(link), link)\n }\n for (const [index, item] of params.items.entries()) {\n const links = [...(rowsByIndex[index]?.values() ?? [])]\n if (links.length > 0) {\n result.set(linkBatchKey(item.objectTypeId, item.objectId, item.linkId), links)\n }\n }\n return result\n }\n\n queryLinks(params: QueryObjectLinksInput): QueryObjectLinksResult {\n const source = this.source\n if (params.objectRefs.length === 0 || params.endpointObjectTypeIds?.length === 0) {\n return { links: [], hasMore: false }\n }\n\n const requested = `\n SELECT DISTINCT\n json_extract(value, '$.objectTypeId') AS object_type_id,\n json_extract(value, '$.primaryId') AS object_id\n FROM json_each(?)\n `\n const linksTable = source.linksTable\n const sourceJoin = `\n SELECT link.*\n FROM ${linksTable} AS link\n JOIN (${requested}) AS requested\n ON requested.object_type_id = link.source_type_id\n AND requested.object_id = link.source_id\n WHERE link.project_id = ?\n `\n const targetJoin = `\n SELECT link.*\n FROM ${linksTable} AS link\n JOIN (${requested}) AS requested\n ON requested.object_type_id = link.target_type_id\n AND requested.object_id = link.target_id\n WHERE link.project_id = ?\n `\n const incidentSql =\n params.direction === \"outgoing\"\n ? sourceJoin\n : params.direction === \"incoming\"\n ? targetJoin\n : `${sourceJoin} UNION ${targetJoin}`\n const requestedJson = JSON.stringify(params.objectRefs)\n const args: (string | number)[] =\n params.direction === \"both\"\n ? [requestedJson, params.projectId, requestedJson, params.projectId]\n : [requestedJson, params.projectId]\n\n const predicates: string[] = []\n if (params.linkId !== undefined) {\n predicates.push(\"link_id = ?\")\n args.push(params.linkId)\n }\n if (params.endpointObjectTypeIds !== undefined) {\n const allowedTypes = JSON.stringify([...new Set(params.endpointObjectTypeIds)])\n predicates.push(\n \"source_type_id IN (SELECT value FROM json_each(?))\",\n \"target_type_id IN (SELECT value FROM json_each(?))\"\n )\n args.push(allowedTypes, allowedTypes)\n }\n if (params.after) {\n predicates.push(\n \"(source_type_id, source_id, link_id, target_type_id, target_id) > (?, ?, ?, ?, ?)\"\n )\n args.push(...params.after)\n }\n args.push(params.limit + 1)\n\n const whereSql = predicates.length > 0 ? `WHERE ${predicates.join(\" AND \")}` : \"\"\n const statement = source.wrapStatement(\n `\n SELECT *\n FROM (${incidentSql}) AS incident\n ${whereSql}\n ORDER BY source_type_id, source_id, link_id, target_type_id, target_id\n LIMIT ?\n `,\n args\n )\n const rows = this.db.query(statement.sql).all(...statement.args) as LinkDatabaseRow[]\n\n return {\n links: rows.slice(0, params.limit).map((row) => rowToLink(row)),\n hasMore: rows.length > params.limit,\n }\n }\n\n list(params: Parameters<ObjectReadStorage[\"list\"]>[0]): {\n objects: readonly ObjectRow[]\n hasMore: boolean\n total: number\n } {\n const source = this.source\n const typed =\n typeof params.objectTypeId === \"string\"\n ? sqliteObjectsOfType(source, params.objectTypeId)\n : { table: source.objectsTable, filter: \"\", args: [] }\n let query = `SELECT * FROM ${typed.table} WHERE project_id = ?`\n const args: SqliteValue[] = [params.projectId]\n\n if (typeof params.objectTypeId === \"string\") {\n query += ` AND object_type_id = ? ${typed.filter}`\n args.push(params.objectTypeId, ...typed.args)\n } else if (params.objectTypeId !== undefined) {\n query += ` AND object_type_id IN (${params.objectTypeId.map(() => \"?\").join(\", \")})`\n args.push(...params.objectTypeId)\n }\n\n if (params.primaryIdPrefix) {\n query += \" AND primary_id LIKE ?\"\n args.push(`${params.primaryIdPrefix}%`)\n }\n\n if (params.primaryIdSuffix) {\n query += \" AND primary_id LIKE ?\"\n args.push(`%${params.primaryIdSuffix}`)\n }\n\n if (params.updatedAfter) {\n query += \" AND updated_at >= ?\"\n args.push(params.updatedAfter.toISOString())\n }\n\n if (params.updatedBefore) {\n query += \" AND updated_at <= ?\"\n args.push(params.updatedBefore.toISOString())\n }\n\n if (params.createdAfter) {\n query += \" AND created_at >= ?\"\n args.push(params.createdAfter.toISOString())\n }\n\n if (params.createdBefore) {\n query += \" AND created_at <= ?\"\n args.push(params.createdBefore.toISOString())\n }\n\n // Get total count\n const countStatement = source.wrapStatement(\n `SELECT COUNT(*) as total FROM (${query}) AS filtered_objects`,\n args\n )\n const countResult = this.db.query(countStatement.sql).get(...countStatement.args) as {\n total: number\n }\n const total = countResult.total\n\n const offset = params.offset ?? 0\n const limit = params.limit ?? 50\n if (limit === 0) return { objects: [], hasMore: offset < total, total }\n\n // Add ordering\n const orderBy = params.orderBy ?? \"updatedAt\"\n const order = params.order ?? \"desc\"\n const orderColumn =\n orderBy === \"primaryId\" ? \"primary_id\" : orderBy === \"createdAt\" ? \"created_at\" : \"updated_at\"\n query += ` ORDER BY ${orderColumn} ${order.toUpperCase()}`\n\n // Add pagination\n query += \" LIMIT ? OFFSET ?\"\n args.push(limit + 1, offset) // +1 to check for hasMore\n\n const rowsStatement = source.wrapStatement(query, args)\n const rows = this.db.query(rowsStatement.sql).all(...rowsStatement.args) as DatabaseRow[]\n const hasMore = rows.length > limit\n const objects = rows.slice(0, limit).map((row) => rowToObject(row))\n\n return { objects, hasMore, total }\n }\n}\n\nfunction fullLinkIdentity(link: ObjectLinkRow): string {\n return JSON.stringify([\n link.sourceTypeId,\n link.sourceId,\n link.linkId,\n link.targetTypeId,\n link.targetId,\n ])\n}\n\nexport function assertLinkQueryLimit(limit: number): void {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error(\"Object link query limit must be a positive safe integer.\")\n }\n}\n\nfunction readTotal(db: Database, compiled: CompiledObjectQuery): number {\n const row = db.query(compiled.totalSql).get(...compiled.totalArgs) as { total: number }\n return row.total\n}\n\nfunction readFacetBuckets(\n db: Database,\n compiled: CompiledObjectQuery,\n facet: ObjectFacetRequest\n): { value: unknown; count: number }[] {\n const path = sqliteJsonPath(facet.propertyId)\n const rows = db\n .query(\n `\n SELECT\n json_type(input.properties, ?) AS value_type,\n json_extract(input.properties, ?) AS value,\n COUNT(*) AS count\n FROM (${compiled.sql}) AS input\n WHERE json_type(input.properties, ?) IS NOT NULL\n GROUP BY value_type, value\n ORDER BY count DESC, CAST(value AS TEXT) ASC\n LIMIT ?\n `\n )\n .all(path, path, ...compiled.args, path, facet.limit) as FacetDatabaseRow[]\n\n return rows.map((row) => ({\n value: sqliteFacetValue(row.value_type, row.value),\n count: Number(row.count),\n }))\n}\n\nfunction sqliteJsonPath(propertyId: string): string {\n return `$.\"${propertyId.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`\n}\n\nfunction sqliteFacetValue(valueType: string | null, value: unknown): unknown {\n if (valueType === \"true\") return true\n if (valueType === \"false\") return false\n if (valueType === \"null\") return null\n // json_extract returns structured values, such as user references, as JSON text.\n if ((valueType === \"object\" || valueType === \"array\") && typeof value === \"string\") {\n return JSON.parse(value)\n }\n return value\n}\n\nfunction assertVectorCandidateCount(count: unknown, limit: number): asserts count is number {\n if (typeof count !== \"number\" || !Number.isSafeInteger(count) || count < 0) {\n throw new ObjectQueryExecutionError(\n \"invalid_vector_candidate_count\",\n \"Storage did not return a valid vector candidate count.\"\n )\n }\n if (count > limit) {\n throw new ObjectQueryExecutionError(\n \"vector_work_limit_exceeded\",\n `Exact vector search supports at most ${limit} eligible vectors at this dimension. Narrow the query filters.`\n )\n }\n}\n\nfunction existsProbeQuery(query: ObjectQuery): ObjectQuery {\n return { kind: \"limit\", limit: 1, input: stripOuterRowShape(query) }\n}\n\nfunction stripOuterRowShape(query: ObjectQuery): ObjectQuery {\n switch (query.kind) {\n case \"limit\":\n case \"page\":\n case \"project\":\n case \"sort\":\n return stripOuterRowShape(query.input)\n default:\n return query\n }\n}\n\ninterface ObjectBatchDatabaseRow extends DatabaseRow {\n _batch_index: number\n}\n\ninterface PropertyPermissionBatchDatabaseRow {\n _batch_index: number\n}\n\ninterface FacetDatabaseRow {\n value_type: string | null\n value: unknown\n count: number\n}\n\ninterface LinkBatchDatabaseRow extends LinkDatabaseRow {\n _batch_index: number\n}\n",
45
50
  "import type {\n ExpandedLinkValue,\n ExpandedObjectRow,\n ObjectLinkRow,\n ObjectRow,\n ObjectRowLinks,\n} from \"@sixb/core/storage\"\n\nexport function rowToObject(row: DatabaseRow): ObjectRow {\n return {\n projectId: row.project_id,\n objectTypeId: row.object_type_id,\n primaryId: row.primary_id,\n properties: JSON.parse(row.properties),\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n version: row.version,\n lastCommitId: row.last_commit_id,\n }\n}\n\n/** Decode an expanded query row with the same shape as Core link hydration. */\nexport function queryRowToObject(row: ObjectQueryDatabaseRow): ObjectRow {\n const base = {\n ...rowToObject(row),\n ...(row._vector_score === undefined ? {} : { score: row._vector_score }),\n }\n const links = reviveExpandedLinks(parseExpandColumn(row._expand))\n return links ? { ...base, links } : base\n}\n\nexport function rowToLink(row: LinkDatabaseRow): ObjectLinkRow {\n return {\n projectId: row.project_id,\n sourceTypeId: row.source_type_id,\n sourceId: row.source_id,\n linkId: row.link_id,\n targetTypeId: row.target_type_id,\n targetId: row.target_id,\n ...(row.properties === null ? {} : { properties: JSON.parse(row.properties) }),\n createdAt: new Date(row.created_at),\n updatedAt: new Date(row.updated_at),\n lastCommitId: row.last_commit_id,\n }\n}\n\n// The `_expand` column comes back from SQLite as a JSON string (or null/absent\n// when the query carried no expansion); parse it before reviving.\nfunction parseExpandColumn(value: unknown): unknown {\n if (typeof value !== \"string\") return value ?? undefined\n return JSON.parse(value)\n}\n\nfunction reviveExpandedLinks(value: unknown): ObjectRowLinks | undefined {\n if (!isPlainObject(value)) return undefined\n const links: ObjectRowLinks = {}\n for (const [linkId, raw] of Object.entries(value)) {\n links[linkId] = reviveExpandedLinkValue(raw)\n }\n return links\n}\n\n// A \"one\" expansion arrives as a single object or null; a \"many\" expansion as an\n// array (already ordered and trimmed in the database).\nfunction reviveExpandedLinkValue(value: unknown): ExpandedLinkValue {\n if (value === null || value === undefined) return null\n if (Array.isArray(value)) return value.map(reviveExpandedRow)\n return reviveExpandedRow(value)\n}\n\n// Revive one hydrated neighbour from `compileExpansionChildJson`: timestamp\n// strings back to `Date`, null/empty link properties dropped (matching the\n// fallback), and nested links recursed.\nfunction reviveExpandedRow(value: unknown): ExpandedObjectRow {\n const row = isPlainObject(value) ? value : {}\n const expanded: ExpandedObjectRow = {\n projectId: String(row.projectId),\n objectTypeId: String(row.objectTypeId),\n primaryId: String(row.primaryId),\n properties: isPlainObject(row.properties) ? row.properties : {},\n createdAt: new Date(row.createdAt as string),\n updatedAt: new Date(row.updatedAt as string),\n version: Number(row.version),\n lastCommitId: String(row.lastCommitId),\n }\n if (isPlainObject(row.linkProperties) && Object.keys(row.linkProperties).length > 0) {\n expanded.linkProperties = row.linkProperties\n }\n const links = reviveExpandedLinks(row.links)\n if (links) expanded.links = links\n return expanded\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\nexport interface DatabaseRow {\n project_id: string\n object_type_id: string\n primary_id: string\n properties: string\n created_at: string\n updated_at: string\n version: number\n last_commit_id: string\n}\n\nexport interface ObjectQueryDatabaseRow extends DatabaseRow {\n _vector_candidate_count?: number\n _vector_score?: number\n _cursor_properties?: string\n /** `json_object(linkId, value, ...)` serialized text from an `expand` pushdown; absent otherwise. */\n _expand?: string | null\n}\n\nexport interface LinkDatabaseRow {\n project_id: string\n source_type_id: string\n source_id: string\n link_id: string\n target_type_id: string\n target_id: string\n properties: string | null\n created_at: string\n updated_at: string\n last_commit_id: string\n}\n",
46
51
  "import type { Database } from \"bun:sqlite\"\nimport { ObjectQueryExecutionError } from \"@sixb/core\"\nimport { load } from \"sqlite-vec\"\n\nconst loaded = new WeakSet<Database>()\n\n/** Load only for vector reads, leaving ordinary SQLite use independent of extension support. */\nexport function ensureSqliteVectorSearch(db: Database): void {\n if (loaded.has(db)) return\n const options = db.query<{ compile_options: string }, []>(\"PRAGMA compile_options\").all()\n if (options.some((option) => option.compile_options === \"OMIT_LOAD_EXTENSION\")) {\n throw new ObjectQueryExecutionError(\n \"vector_extension_missing\",\n \"SQLite vector search requires extension support. On macOS install SQLite (brew install sqlite), then call Database.setCustomSQLite with its library path before opening any database.\"\n )\n }\n try {\n load(db)\n loaded.add(db)\n } catch (cause) {\n throw new Error(\n \"[SixbSqlite] Could not load sqlite-vec for vector search. Check that its native package supports your platform.\",\n { cause }\n )\n }\n}\n",
47
- "import type { Database } from \"bun:sqlite\"\nimport type {\n CompiledSelectedObjectReadScope,\n ObjectQueryCapabilities,\n ObjectReadExecutionLimits,\n ObjectReadStorage,\n} from \"@sixb/core/storage\"\nimport {\n assertObjectReaderProject,\n assertObjectReadFacetCount,\n assertObjectReadOutputWithinLimit,\n ObjectReadLimitExceededError,\n snapshotObjectReadExecutionLimits,\n} from \"@sixb/core/storage\"\nimport { runDeferredReadTransaction } from \"../transactions\"\nimport {\n compileSqliteSelectedObjectReadSource,\n type SqliteSelectedObjectReadSource,\n} from \"./read-scope\"\nimport { assertLinkQueryLimit, SqliteObjectReader } from \"./reader\"\n\n/** Keep the traversal probe and every terminal statement in the same synchronous snapshot. */\nexport function createSqliteSelectedReader(\n db: Database,\n params: {\n projectId: string\n scope: CompiledSelectedObjectReadScope\n limits: ObjectReadExecutionLimits\n },\n queryCapabilities: () => ObjectQueryCapabilities\n): ObjectReadStorage {\n const projectId = params.projectId\n const limits = snapshotObjectReadExecutionLimits(params.limits)\n const source = compileSqliteSelectedObjectReadSource(\n projectId,\n params.scope,\n limits.maxTraversalFacts\n )\n const reader = new SqliteObjectReader(db, source)\n const assertProject = (actualProjectId: string): void =>\n assertObjectReaderProject(projectId, actualProjectId)\n const read = <T>(run: () => T): T =>\n runDeferredReadTransaction(db, () => {\n assertTraversalBudget(db, source, limits.maxTraversalFacts)\n const value = run()\n assertObjectReadOutputWithinLimit(value, limits)\n return value\n })\n const readMap = <TKey, TValue>(run: () => Map<TKey, TValue>): Map<TKey, TValue> =>\n runDeferredReadTransaction(db, () => {\n assertTraversalBudget(db, source, limits.maxTraversalFacts)\n const value = run()\n assertObjectReadOutputWithinLimit([...value.entries()], limits)\n return value\n })\n\n return Object.freeze({\n queryCapabilities,\n queryObjects: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.queryObjects(input))\n },\n countObjects: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.countObjects(input))\n },\n existsObjects: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.existsObjects(input))\n },\n facetObjects: async (input) => {\n assertProject(input.projectId)\n assertObjectReadFacetCount(input.facets.length)\n return read(() => reader.facetObjects(input))\n },\n getByPrimaryId: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.getByPrimaryId(input))\n },\n selectsObjectProperties: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.selectsObjectProperties(input))\n },\n listLinks: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.listLinks(input))\n },\n getByPrimaryIdBatch: async (input) => {\n assertProject(input.projectId)\n return readMap(() => reader.getByPrimaryIdBatch(input))\n },\n listLinksBatch: async (input) => {\n assertProject(input.projectId)\n return readMap(() => reader.listLinksBatch(input))\n },\n queryLinks: async (input) => {\n assertProject(input.projectId)\n assertLinkQueryLimit(input.limit)\n return read(() => reader.queryLinks(input))\n },\n list: async (input) => {\n assertProject(input.projectId)\n return read(() => reader.list(input))\n },\n } satisfies ObjectReadStorage)\n}\n\nfunction assertTraversalBudget(\n db: Database,\n source: SqliteSelectedObjectReadSource,\n maxTraversalFacts: number\n): void {\n const row = db.query(source.traversalProbe.sql).get(...source.traversalProbe.args) as {\n total: number | bigint\n }\n if (BigInt(row.total) > BigInt(maxTraversalFacts)) {\n throw new ObjectReadLimitExceededError(\"traversalFacts\", maxTraversalFacts)\n }\n}\n",
48
- "import type { CompiledSelectedObjectReadScope } from \"@sixb/core/storage\"\nimport {\n type CompiledObjectQuery,\n type SqliteObjectQuerySource,\n type SqliteValue,\n sqliteJsonEachValue,\n} from \"./query-compiler\"\n\nexport interface SqliteSelectedObjectReadSource extends SqliteObjectQuerySource {\n readonly objectPropertyPermissionsTable: string\n readonly traversalProbe: {\n readonly sql: string\n readonly args: readonly SqliteValue[]\n }\n}\n\n/**\n * Prepare one immutable selected scope as live, path-sensitive SQLite relations.\n *\n * The complete compiled scope is serialized once. Every statement receives that one JSON document\n * and the bound project id, keeping the host-parameter count constant as selections grow.\n * CROSS JOIN keeps authorized parents/grants before indexed edge/object lookups, even when\n * statistics would otherwise make SQLite rescan all grants for every stored object.\n * Property grants are grouped only after path-sensitive reachability has been resolved.\n * Expose identities from grants/visible, so flattened joins can seek those relations by key\n * before loading stored values. Exposing stored identities makes traversal rescan grants per edge.\n */\nexport function compileSqliteSelectedObjectReadSource(\n projectId: string,\n scope: CompiledSelectedObjectReadScope,\n maxTraversalFacts: number\n): SqliteSelectedObjectReadSource {\n const scopeJson = JSON.stringify({\n roots: scope.roots,\n objects: scope.objects,\n steps: scope.steps,\n })\n const compiled = compileSelectedReadScopeCte(scopeJson, projectId)\n const wrapStatement = (sql: string, args: readonly SqliteValue[] = []) => ({\n sql: `${compiled.sql}\\n${sql}`,\n args: [...compiled.args, ...args],\n })\n\n return Object.freeze({\n objectsTable: \"_sixb_scope_objects\",\n linksTable: \"_sixb_scope_links\",\n objectPropertyPermissionsTable: \"_sixb_scope_object_permissions\",\n wrapStatement,\n wrapQuery: (query: CompiledObjectQuery): CompiledObjectQuery => ({\n ...query,\n ...wrapStatement(query.sql, query.args),\n vectorProbe: query.vectorProbe\n ? { ...query.vectorProbe, ...wrapStatement(query.vectorProbe.sql, query.vectorProbe.args) }\n : undefined,\n totalSql: `${compiled.sql}\\n${query.totalSql}`,\n totalArgs: [...compiled.args, ...query.totalArgs],\n ...(query.hasMoreProbe\n ? {\n hasMoreProbe: {\n ...query.hasMoreProbe,\n ...wrapStatement(query.hasMoreProbe.sql, query.hasMoreProbe.args),\n },\n }\n : {}),\n }),\n traversalProbe: wrapStatement(\n `\n SELECT COUNT(*) AS total\n FROM (\n SELECT 1 AS traversal_fact\n FROM _sixb_scope_root_facts\n\n UNION ALL\n\n SELECT 1 AS traversal_fact\n FROM _sixb_scope_reached_links\n\n LIMIT ?\n ) AS bounded_traversal_facts\n `,\n [BigInt(maxTraversalFacts) + 1n]\n ),\n })\n}\n\ninterface CompiledReadScopeCte {\n readonly sql: string\n readonly args: readonly SqliteValue[]\n}\n\nfunction compileSelectedReadScopeCte(scopeJson: string, projectId: string): CompiledReadScopeCte {\n return {\n sql: `\n WITH RECURSIVE\n _sixb_scope_document(scope) AS (\n SELECT json(?)\n ),\n _sixb_scope_roots(root_id, node_id, object_type_id, primary_id) AS (\n SELECT\n CAST(root.key AS INTEGER),\n CAST(json_extract(root.value, '$.nodeId') AS INTEGER),\n CAST(json_extract(root.value, '$.objectTypeId') AS TEXT),\n CAST(json_extract(root.value, '$.primaryId') AS TEXT)\n FROM _sixb_scope_document AS document,\n json_each(json_extract(document.scope, '$.roots')) AS root\n ),\n _sixb_scope_root_facts(project_id, root_id, node_id, object_type_id, primary_id) AS (\n SELECT anchor.project_id, root.root_id, root.node_id, root.object_type_id, root.primary_id\n FROM _sixb_scope_roots AS root\n CROSS JOIN objects AS anchor\n ON anchor.project_id = ?\n AND anchor.object_type_id = root.object_type_id\n AND anchor.primary_id = root.primary_id\n ),\n _sixb_scope_object_selections(node_id, object_type_id, property_ids) AS (\n SELECT\n CAST(json_extract(selection.value, '$.nodeId') AS INTEGER),\n CAST(json_extract(selection.value, '$.objectTypeId') AS TEXT),\n json_extract(selection.value, '$.propertyIds')\n FROM _sixb_scope_document AS document,\n json_each(json_extract(document.scope, '$.objects')) AS selection\n ),\n _sixb_scope_link_selections(\n step_id,\n node_id,\n parent_node_id,\n source_object_type_id,\n link_id,\n target_object_type_id,\n property_ids\n ) AS (\n SELECT\n CAST(step.key AS INTEGER),\n CAST(json_extract(step.value, '$.nodeId') AS INTEGER),\n CAST(json_extract(step.value, '$.parentNodeId') AS INTEGER),\n CAST(json_extract(step.value, '$.sourceObjectTypeId') AS TEXT),\n CAST(json_extract(step.value, '$.linkId') AS TEXT),\n CAST(json_extract(step.value, '$.targetObjectTypeId') AS TEXT),\n json_extract(step.value, '$.propertyIds')\n FROM _sixb_scope_document AS document,\n json_each(json_extract(document.scope, '$.steps')) AS step\n ),\n _sixb_scope_reachable(project_id, node_id, object_type_id, primary_id) AS (\n SELECT root.project_id, root.node_id, root.object_type_id, root.primary_id\n FROM _sixb_scope_root_facts AS root\n\n UNION\n\n SELECT edge.project_id, selection.node_id, edge.target_type_id, edge.target_id\n FROM _sixb_scope_reachable AS parent\n CROSS JOIN _sixb_scope_link_selections AS selection\n ON selection.parent_node_id = parent.node_id\n AND selection.source_object_type_id = parent.object_type_id\n CROSS JOIN links AS edge\n ON edge.project_id = parent.project_id\n AND edge.source_type_id = parent.object_type_id\n AND edge.source_id = parent.primary_id\n AND edge.link_id = selection.link_id\n AND edge.target_type_id = selection.target_object_type_id\n CROSS JOIN objects AS target\n ON target.project_id = edge.project_id\n AND target.object_type_id = edge.target_type_id\n AND target.primary_id = edge.target_id\n ),\n _sixb_scope_object_permissions(project_id, object_type_id, primary_id, property_id) AS (\n SELECT DISTINCT\n reachable.project_id,\n reachable.object_type_id,\n reachable.primary_id,\n CAST(selected_property.value AS TEXT)\n FROM _sixb_scope_reachable AS reachable\n JOIN _sixb_scope_object_selections AS selection\n ON selection.node_id = reachable.node_id\n AND selection.object_type_id = reachable.object_type_id\n JOIN json_each(selection.property_ids) AS selected_property\n ),\n _sixb_scope_object_ids(project_id, object_type_id, primary_id) AS (\n SELECT DISTINCT project_id, object_type_id, primary_id\n FROM _sixb_scope_reachable\n ),\n _sixb_scope_object_grants AS (\n SELECT reachable.project_id, reachable.object_type_id, reachable.primary_id,\n json_group_array(DISTINCT selected_property.value) FILTER (WHERE selected_property.value IS NOT NULL) AS property_ids\n FROM _sixb_scope_reachable AS reachable\n LEFT JOIN _sixb_scope_object_selections AS selection\n ON selection.node_id = reachable.node_id\n AND selection.object_type_id = reachable.object_type_id\n LEFT JOIN json_each(selection.property_ids) AS selected_property ON true\n GROUP BY reachable.project_id, reachable.object_type_id, reachable.primary_id\n ),\n _sixb_scope_objects AS (\n SELECT grants.project_id, grants.object_type_id, grants.primary_id,\n COALESCE((\n SELECT json_group_object(property.key, ${sqliteJsonEachValue(\"property\")})\n FROM json_each(stored.properties) AS property\n WHERE property.key IN (SELECT value FROM json_each(grants.property_ids))\n ), json('{}')) AS properties,\n stored.created_at, stored.updated_at, stored.version, stored.last_commit_id\n FROM _sixb_scope_object_grants AS grants\n CROSS JOIN objects AS stored\n ON stored.project_id = grants.project_id\n AND stored.object_type_id = grants.object_type_id\n AND stored.primary_id = grants.primary_id\n ),\n _sixb_scope_reached_links(\n project_id,\n step_id,\n node_id,\n parent_node_id,\n source_type_id,\n source_id,\n link_id,\n target_type_id,\n target_id,\n property_ids\n ) AS (\n SELECT\n edge.project_id,\n selection.step_id,\n selection.node_id,\n selection.parent_node_id,\n edge.source_type_id,\n edge.source_id,\n edge.link_id,\n edge.target_type_id,\n edge.target_id,\n selection.property_ids\n FROM _sixb_scope_reachable AS parent\n CROSS JOIN _sixb_scope_link_selections AS selection\n ON selection.parent_node_id = parent.node_id\n AND selection.source_object_type_id = parent.object_type_id\n CROSS JOIN links AS edge\n ON edge.project_id = parent.project_id\n AND edge.source_type_id = parent.object_type_id\n AND edge.source_id = parent.primary_id\n AND edge.link_id = selection.link_id\n AND edge.target_type_id = selection.target_object_type_id\n CROSS JOIN objects AS target\n ON target.project_id = edge.project_id\n AND target.object_type_id = edge.target_type_id\n AND target.primary_id = edge.target_id\n ),\n _sixb_scope_link_permissions(\n project_id,\n source_type_id,\n source_id,\n link_id,\n target_type_id,\n target_id,\n property_id\n ) AS (\n SELECT DISTINCT\n reached.project_id,\n reached.source_type_id,\n reached.source_id,\n reached.link_id,\n reached.target_type_id,\n reached.target_id,\n CAST(selected_property.value AS TEXT)\n FROM _sixb_scope_reached_links AS reached\n JOIN json_each(reached.property_ids) AS selected_property\n ),\n _sixb_scope_link_ids(\n project_id,\n source_type_id,\n source_id,\n link_id,\n target_type_id,\n target_id\n ) AS (\n SELECT DISTINCT\n project_id,\n source_type_id,\n source_id,\n link_id,\n target_type_id,\n target_id\n FROM _sixb_scope_reached_links\n ),\n _sixb_scope_links AS (\n SELECT\n visible.project_id,\n visible.source_type_id,\n visible.source_id,\n visible.link_id,\n visible.target_type_id,\n visible.target_id,\n CASE\n WHEN stored.properties IS NULL THEN NULL\n ELSE NULLIF(\n (\n SELECT json_group_object(property.key, ${sqliteJsonEachValue(\"property\")})\n FROM json_each(stored.properties) AS property\n JOIN _sixb_scope_link_permissions AS permission\n ON permission.project_id = stored.project_id\n AND permission.source_type_id = stored.source_type_id\n AND permission.source_id = stored.source_id\n AND permission.link_id = stored.link_id\n AND permission.target_type_id = stored.target_type_id\n AND permission.target_id = stored.target_id\n AND permission.property_id = property.key\n ),\n json('{}')\n )\n END AS properties,\n stored.created_at,\n stored.updated_at,\n stored.last_commit_id\n FROM links AS stored\n JOIN _sixb_scope_link_ids AS visible\n ON visible.project_id = stored.project_id\n AND visible.source_type_id = stored.source_type_id\n AND visible.source_id = stored.source_id\n AND visible.link_id = stored.link_id\n AND visible.target_type_id = stored.target_type_id\n AND visible.target_id = stored.target_id\n )\n `,\n args: [scopeJson, projectId],\n }\n}\n",
52
+ "import type { Database } from \"bun:sqlite\"\nimport type {\n CompiledConditionalObjectReadScope,\n ObjectQueryCapabilities,\n ObjectReadStorage,\n} from \"@sixb/core/storage\"\nimport { compileSqliteConditionalObjectReadSource } from \"./read-scope\"\nimport { createSqliteScopedReader } from \"./scoped-reader\"\n\n/** Read objects and links through relations that apply the scope's conditions as they are read. */\nexport function createSqliteConditionalReader(\n db: Database,\n params: {\n projectId: string\n scope: CompiledConditionalObjectReadScope\n },\n queryCapabilities: () => ObjectQueryCapabilities\n): ObjectReadStorage {\n return createSqliteScopedReader(\n db,\n {\n projectId: params.projectId,\n source: compileSqliteConditionalObjectReadSource(params.projectId, params.scope),\n },\n queryCapabilities\n )\n}\n",
53
+ "import type { Database } from \"bun:sqlite\"\nimport type {\n CompiledSelectedObjectReadScope,\n ObjectQueryCapabilities,\n ObjectReadExecutionLimits,\n ObjectReadStorage,\n} from \"@sixb/core/storage\"\nimport { ObjectReadLimitExceededError, snapshotObjectReadExecutionLimits } from \"@sixb/core/storage\"\nimport {\n compileSqliteSelectedObjectReadSource,\n type SqliteSelectedObjectReadSource,\n} from \"./read-scope\"\nimport { createSqliteScopedReader } from \"./scoped-reader\"\n\n/** Keep the traversal probe and every terminal statement in the same synchronous snapshot. */\nexport function createSqliteSelectedReader(\n db: Database,\n params: {\n projectId: string\n scope: CompiledSelectedObjectReadScope\n limits: ObjectReadExecutionLimits\n },\n queryCapabilities: () => ObjectQueryCapabilities\n): ObjectReadStorage {\n const projectId = params.projectId\n const limits = snapshotObjectReadExecutionLimits(params.limits)\n const source = compileSqliteSelectedObjectReadSource(\n projectId,\n params.scope,\n limits.maxTraversalFacts\n )\n\n return createSqliteScopedReader(\n db,\n {\n projectId,\n source,\n beforeRead: () => assertTraversalBudget(db, source, limits.maxTraversalFacts),\n limits,\n },\n queryCapabilities\n )\n}\n\nfunction assertTraversalBudget(\n db: Database,\n source: SqliteSelectedObjectReadSource,\n maxTraversalFacts: number\n): void {\n const row = db.query(source.traversalProbe.sql).get(...source.traversalProbe.args) as {\n total: number | bigint\n }\n if (BigInt(row.total) > BigInt(maxTraversalFacts)) {\n throw new ObjectReadLimitExceededError(\"traversalFacts\", maxTraversalFacts)\n }\n}\n",
49
54
  "import type { Database } from \"bun:sqlite\"\nimport { parseSixbFailure } from \"@sixb/core/internal/errors\"\nimport { MaterializationConflictError } from \"@sixb/core/internal/materialization\"\nimport {\n type ClaimedOutboxDraft,\n sourceAssertionFromColumns,\n sourceEntityFromKey,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type {\n AssertSourceMaterializationExecutionInput,\n OntologyCommitRecord,\n OntologyCommitWrite,\n OntologySourceRecord,\n StageSourceAssertion,\n} from \"@sixb/core/storage\"\nimport { ONTOLOGY_OUTBOX_FAILURE_CODES } from \"@sixb/core/storage\"\n\nexport {\n assertNonblank,\n assertNonnegativeInteger,\n assertPositiveInteger,\n assertTimestamp,\n canonicalJson,\n linkRefFromColumns,\n objectRefFromColumns,\n originColumns,\n originWhere,\n sourceEntityKey,\n} from \"@sixb/core/internal/ontology-storage-provider\"\n\nexport type SqliteRootOperation = <T>(run: () => Promise<T> | T) => Promise<T>\n\nexport interface SqliteOntologyCommitRow {\n readonly project_id: string\n readonly id: string\n readonly idempotency_key: string\n readonly request_hash: string\n readonly execution_id: string\n readonly origin_kind: string\n readonly origin_run_id: string | null\n readonly origin_batch_ordinal: number | null\n readonly origin: string\n readonly ontology_revision: string\n readonly projection_revision: string | null\n readonly ownership_hash: string | null\n readonly intent: string\n readonly result: string\n readonly committed_at: string\n}\n\nexport interface SqliteOntologySourceRow {\n readonly version_id: number\n readonly project_id: string\n readonly source_id: string\n readonly materialization_id: string\n readonly projection_run_id: string\n readonly projection_kind: \"object\" | \"link\"\n readonly protocol: \"replacement\"\n readonly status: OntologySourceRecord[\"status\"]\n readonly execution_token: string | null\n readonly dataset_id: string\n readonly dataset_version_id: string\n readonly dataset_version_created_at: string\n readonly projection_revision: string\n readonly ownership_hash: string\n readonly ontology_revision: string\n readonly root_count: number | null\n readonly base_materialization_id: string | null\n readonly base_commit_id: string | null\n readonly assertion_count: number | null\n readonly created_at: string\n readonly ready_at: string | null\n readonly activated_at: string | null\n readonly terminal_at: string | null\n readonly last_commit_id: string | null\n readonly updated_at: string\n}\n\n/** An assertion with its root and version, as `SOURCE_ASSERTION_COLUMNS` selects it. */\nexport interface SqliteOntologySourceAssertionRow {\n readonly source_id: string\n readonly materialization_id: string\n readonly root_key: string\n readonly staging_ordinal: number\n readonly entity_kind: \"object\" | \"link\"\n readonly object_type_id: string | null\n readonly primary_id: string | null\n readonly source_type_id: string | null\n readonly source_primary_id: string | null\n readonly link_id: string | null\n readonly target_type_id: string | null\n readonly target_primary_id: string | null\n readonly payload: string | null\n}\n\nexport interface SqliteStoredOverrideRow {\n readonly value: string\n readonly last_commit_id: string\n readonly updated_at: string\n}\n\nexport interface SqliteOntologyOutboxRow {\n readonly id: string\n readonly commit_id: string\n readonly commit_ordinal: number\n readonly event: string\n readonly available_at: string\n readonly attempts: number\n readonly lease_id: string | null\n readonly lease_expires_at: string | null\n readonly published_at: string | null\n readonly last_failure: string | null\n readonly created_at: string\n}\n\nexport function parseJson<T>(value: string): T {\n return JSON.parse(value) as T\n}\n\nexport function sourceRecord(row: SqliteOntologySourceRow): OntologySourceRecord {\n return {\n projectId: row.project_id,\n source: { projectionId: row.source_id },\n materializationId: row.materialization_id,\n projectionRunId: row.projection_run_id,\n projectionKind: row.projection_kind,\n protocol: row.protocol,\n status: row.status,\n executionToken: row.execution_token,\n datasetVersion: {\n datasetId: row.dataset_id,\n versionId: row.dataset_version_id,\n createdAt: row.dataset_version_created_at,\n },\n projectionRevision: row.projection_revision,\n ownershipHash: row.ownership_hash,\n ontologyRevision: row.ontology_revision,\n ...(row.base_materialization_id === null\n ? {}\n : {\n base: {\n materializationId: row.base_materialization_id,\n lastCommitId: row.base_commit_id!,\n },\n }),\n rootCount: row.root_count,\n assertionCount: row.assertion_count,\n createdAt: row.created_at,\n readyAt: row.ready_at,\n activatedAt: row.activated_at,\n terminalAt: row.terminal_at,\n lastCommitId: row.last_commit_id,\n updatedAt: row.updated_at,\n }\n}\n\nexport function sourceAssertion(row: SqliteOntologySourceAssertionRow): StageSourceAssertion {\n return {\n root: sourceEntityFromKey(row.root_key),\n assertion: sourceAssertionFromColumns(\n row,\n row.payload === null ? null : parseJson<unknown>(row.payload)\n ),\n stagingOrdinal: row.staging_ordinal,\n }\n}\n\nexport function commitRecord(row: SqliteOntologyCommitRow): OntologyCommitRecord {\n const base = {\n projectId: row.project_id,\n id: row.id,\n idempotencyKey: row.idempotency_key,\n requestHash: row.request_hash,\n executionId: row.execution_id,\n origin: parseJson<OntologyCommitWrite[\"origin\"]>(row.origin),\n ontologyRevision: row.ontology_revision,\n ...(row.projection_revision === null ? {} : { projectionRevision: row.projection_revision }),\n ...(row.ownership_hash === null ? {} : { ownershipHash: row.ownership_hash }),\n committedAt: row.committed_at,\n }\n const intent = parseJson<OntologyCommitWrite[\"intent\"]>(row.intent)\n const result = parseJson<OntologyCommitRecord[\"result\"]>(row.result)\n return { ...base, intent, result } as OntologyCommitRecord\n}\n\n/** A claimed row as stored: its draft, to rebuild from its commit. */\nexport function claimedOutboxDraft(row: SqliteOntologyOutboxRow): ClaimedOutboxDraft {\n if (row.lease_id === null || row.lease_expires_at === null) {\n throw new MaterializationConflictError(\n \"outbox-lease\",\n \"Ontology outbox claim returned an unpaired lease.\"\n )\n }\n return {\n id: row.id,\n commitId: row.commit_id,\n commitOrdinal: row.commit_ordinal,\n event: parseJson<ClaimedOutboxDraft[\"event\"]>(row.event),\n availableAt: row.available_at,\n attempts: row.attempts,\n leaseId: row.lease_id,\n leaseExpiresAt: row.lease_expires_at,\n publishedAt: row.published_at,\n lastFailure:\n row.last_failure === null\n ? null\n : parseSixbFailure(row.last_failure, ONTOLOGY_OUTBOX_FAILURE_CODES),\n createdAt: row.created_at,\n }\n}\n\nexport function assertProjectionExecution(\n db: Database,\n input: {\n readonly projectId: string\n readonly sourceId: string\n readonly projectionRunId: string\n readonly executionToken: string\n readonly identity?: AssertSourceMaterializationExecutionInput[\"identity\"]\n }\n): void {\n const run = db\n .query(\n `\n SELECT projection_id, projection_kind, status, materialization_protocol, execution_token,\n dataset_id, dataset_version_id, dataset_version_created_at,\n ontology_revision, projection_revision, ownership_hash\n FROM projection_runs\n WHERE project_id = ? AND id = ?\n `\n )\n .get(input.projectId, input.projectionRunId) as {\n projection_id: string\n projection_kind: string\n status: string\n materialization_protocol: string | null\n execution_token: string | null\n dataset_id: string\n dataset_version_id: string\n dataset_version_created_at: string | null\n ontology_revision: string | null\n projection_revision: string | null\n ownership_hash: string | null\n } | null\n if (!run || run.status !== \"running\") {\n throw new MaterializationConflictError(\n \"run-correlation\",\n `Projection run '${input.projectionRunId}' is missing or is not running.`\n )\n }\n if (run.projection_id !== input.sourceId || run.materialization_protocol !== \"replacement\") {\n throw new MaterializationConflictError(\n \"run-correlation\",\n `Projection run '${input.projectionRunId}' does not own replacement source '${input.sourceId}'.`\n )\n }\n if (run.execution_token !== input.executionToken) {\n throw new MaterializationConflictError(\n \"execution-lost\",\n `Projection run '${input.projectionRunId}' execution token is stale.`\n )\n }\n const identity = input.identity\n if (\n identity &&\n (run.projection_kind !== identity.projectionKind ||\n run.materialization_protocol !== identity.protocol ||\n run.dataset_id !== identity.datasetVersion.datasetId ||\n run.dataset_version_id !== identity.datasetVersion.versionId ||\n run.dataset_version_created_at !== identity.datasetVersion.createdAt ||\n run.ontology_revision !== identity.ontologyRevision ||\n run.projection_revision !== identity.projectionRevision ||\n run.ownership_hash !== identity.ownershipHash)\n ) {\n throw new MaterializationConflictError(\n \"run-correlation\",\n `Projection run '${input.projectionRunId}' immutable source identity does not match.`\n )\n }\n}\n\nexport function requireChanges(\n changes: number,\n kind: ConstructorParameters<typeof MaterializationConflictError>[0],\n message: string\n): void {\n if (changes !== 1) throw new MaterializationConflictError(kind, message)\n}\n\nexport function isSqliteConstraintError(error: unknown): boolean {\n if (!(error instanceof Error)) return false\n const details = error as Error & { readonly code?: unknown; readonly errno?: unknown }\n if (typeof details.code === \"string\") {\n return [\n \"SQLITE_CONSTRAINT_CHECK\",\n \"SQLITE_CONSTRAINT_FOREIGNKEY\",\n \"SQLITE_CONSTRAINT_NOTNULL\",\n \"SQLITE_CONSTRAINT_PRIMARYKEY\",\n \"SQLITE_CONSTRAINT_UNIQUE\",\n ].includes(details.code)\n }\n return details.errno === 19\n}\n",
50
55
  "import type { Database } from \"bun:sqlite\"\nimport type {\n GetOntologyCommitByIdempotencyKeyInput,\n GetOntologyCommitByIdInput,\n GetOntologyCommitByOriginInput,\n ListOntologyCommitsInput,\n ListOntologyCommitsResult,\n OntologyCommitRecord,\n OntologyCommitStorage,\n} from \"@sixb/core/storage\"\nimport {\n assertNonblank,\n assertNonnegativeInteger,\n commitRecord,\n originWhere,\n type SqliteOntologyCommitRow,\n type SqliteRootOperation,\n} from \"./shared\"\n\nexport class SqliteOntologyCommitStorage implements OntologyCommitStorage {\n constructor(\n private readonly db: Database,\n private readonly runRootOperation: SqliteRootOperation\n ) {}\n\n async getByIdempotencyKey(\n input: GetOntologyCommitByIdempotencyKeyInput\n ): Promise<OntologyCommitRecord | null> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Ontology commit project id\")\n assertNonblank(input.idempotencyKey, \"Ontology commit idempotency key\")\n return this.readOne(\n \"project_id = ? AND idempotency_key = ?\",\n input.projectId,\n input.idempotencyKey\n )\n })\n }\n\n async getById(input: GetOntologyCommitByIdInput): Promise<OntologyCommitRecord | null> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Ontology commit project id\")\n assertNonblank(input.id, \"Ontology commit id\")\n return this.readOne(\"project_id = ? AND id = ?\", input.projectId, input.id)\n })\n }\n\n async getByOrigin(input: GetOntologyCommitByOriginInput): Promise<OntologyCommitRecord | null> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Ontology commit project id\")\n const origin = originWhere(input.origin)\n assertNonblank(origin.runId, \"Ontology commit origin run id\")\n if (origin.batchOrdinal !== null) {\n assertNonnegativeInteger(origin.batchOrdinal, \"Ontology telemetry commit batch ordinal\")\n }\n return origin.batchOrdinal === null\n ? this.readOne(\n \"project_id = ? AND origin_kind = ? AND origin_run_id = ? AND origin_batch_ordinal IS NULL\",\n input.projectId,\n origin.kind,\n origin.runId\n )\n : this.readOne(\n \"project_id = ? AND origin_kind = ? AND origin_run_id = ? AND origin_batch_ordinal = ?\",\n input.projectId,\n origin.kind,\n origin.runId,\n origin.batchOrdinal\n )\n })\n }\n\n async list(input: ListOntologyCommitsInput): Promise<ListOntologyCommitsResult> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Ontology commit project id\")\n if (input.run) assertNonblank(input.run.id, \"Ontology commit run id\")\n const offset = input.offset ?? 0\n const limit = input.limit ?? -1\n assertNonnegativeInteger(offset, \"Ontology commit list offset\")\n if (limit !== -1) assertNonnegativeInteger(limit, \"Ontology commit list limit\")\n const filters = [\"project_id = ?\"]\n const values: (string | number)[] = [input.projectId]\n if (input.run?.kind === \"action\") {\n filters.push(\"origin_kind = 'action' AND origin_run_id = ?\")\n values.push(input.run.id)\n } else if (input.run?.kind === \"projection\") {\n filters.push(\"origin_run_id = ? AND origin_kind IN ('projection', 'telemetry')\")\n values.push(input.run.id)\n }\n const where = filters.join(\" AND \")\n const totalRow = this.db\n .query(`SELECT COUNT(*) AS total FROM ontology_commits WHERE ${where}`)\n .get(...values) as { readonly total: number }\n const direction = input.order === \"desc\" ? \"DESC\" : \"ASC\"\n const order =\n input.run?.kind === \"projection\"\n ? `CASE WHEN origin_kind = 'telemetry' THEN origin_batch_ordinal ELSE -1 END ${direction}, committed_at ${direction}, id ${direction}`\n : `committed_at ${direction}, id ${direction}`\n const rows = this.db\n .query(\n `\n SELECT * FROM ontology_commits\n WHERE ${where}\n ORDER BY ${order}\n LIMIT ? OFFSET ?\n `\n )\n .all(...values, limit, offset) as SqliteOntologyCommitRow[]\n const commits = rows.map(commitRecord)\n return {\n commits,\n total: totalRow.total,\n hasMore: offset + commits.length < totalRow.total,\n }\n })\n }\n\n private readOne(\n where: string,\n ...values: readonly (string | number)[]\n ): OntologyCommitRecord | null {\n const row = this.db\n .query(`SELECT * FROM ontology_commits WHERE ${where}`)\n .get(...values) as SqliteOntologyCommitRow | null\n return row ? commitRecord(row) : null\n }\n}\n",
51
- "import type { Database } from \"bun:sqlite\"\nimport {\n assertPinnedDatasetWatermark,\n linkRefKey,\n linkRefSortKey,\n linkScopeSortKey,\n MaterializationConflictError,\n MaterializationValidationError,\n objectRefKey,\n objectRefSortKey,\n telemetryPointKey,\n telemetryPointSortKey,\n} from \"@sixb/core/internal/materialization\"\nimport {\n assertExpectedLinkRevision,\n assertExpectedLinkScopeRevision,\n assertExpectedObjectRevision,\n assertMaterializationFinalizationCorrelation,\n assertMaterializationHeader,\n assertPageRows,\n assertSourceActivationCorrelation,\n beginMaterializationApply,\n beginMaterializationVectorChanges,\n createCardinalityValidator,\n invalidCorrelation,\n materializationOutboxWrite,\n materializationPlanChunk,\n sameNonnegativeCounts as sameCounts,\n uniqueSorted,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type {\n AppliedMaterialization,\n ApplyMaterializationInput,\n ApplyMaterializationResult,\n FinalizeMaterializationInput,\n MaterializationPlanHeader,\n MaterializationPlanWorkRecord,\n MaterializationSession,\n MaterializationStatePage,\n MaterializationVectorChangePage,\n OntologyCommitRecord,\n OntologyMaterializationStorage,\n SourceActivationWrite,\n StageMaterializationWorkInput,\n StreamMaterializationStateInput,\n StreamMaterializationVectorChangesInput,\n} from \"@sixb/core/storage\"\nimport { yieldSqliteEventLoop } from \"../transactions\"\nimport {\n type SqliteMaterializationSessionState,\n SqliteMaterializationSessions,\n type SqliteOntologyTransactionContext,\n} from \"./materialization-session\"\nimport { SqliteMaterializationStateReader } from \"./materialization-state\"\nimport { SqliteMaterializationWriter } from \"./materialization-writer\"\nimport { boundReplacementPlan } from \"./replacement-plans\"\nimport {\n assertProjectionExecution,\n canonicalJson,\n commitRecord,\n isSqliteConstraintError,\n originColumns,\n requireChanges,\n type SqliteOntologyCommitRow,\n type SqliteOntologySourceRow,\n} from \"./shared\"\nimport { activateSourceRoots } from \"./source-roots\"\n\n/** Rows the provider reads and writes at once while it applies a staged plan. */\nconst APPLY_PAGE_ROWS = 1_000\n\n/**\n * Records the entities whose plan inputs a commit's applied work changed, once each, as the\n * in-memory `touchPlanItem` does: a replacement plan's refresh rechecks only those.\n */\nfunction touchAppliedWorkStatement(workTable: string): string {\n return `\n INSERT INTO ontology_commit_touches (project_id, commit_id, entity_kind, identity_key)\n SELECT DISTINCT $projectId, $commitId, kind, CASE kind\n WHEN 'object' THEN\n json_array(json_extract(ref, '$.objectTypeId'), json_extract(ref, '$.primaryId'))\n WHEN 'scope' THEN json_array(\n json_extract(ref, '$.source.objectTypeId'), json_extract(ref, '$.source.primaryId'),\n json_extract(ref, '$.linkId')\n )\n ELSE json_array(\n json_extract(ref, '$.source.objectTypeId'), json_extract(ref, '$.source.primaryId'),\n json_extract(ref, '$.linkId'), json_extract(ref, '$.target.objectTypeId'),\n json_extract(ref, '$.target.primaryId')\n )\n END\n FROM (\n SELECT CASE json_extract(payload, '$.item.kind')\n WHEN 'object-upsert' THEN 'object'\n WHEN 'object-delete' THEN 'object'\n WHEN 'object-override-upsert' THEN 'object'\n WHEN 'object-override-delete' THEN 'object'\n WHEN 'point-upsert' THEN 'object'\n WHEN 'link-upsert' THEN 'link'\n WHEN 'link-delete' THEN 'link'\n WHEN 'link-override-upsert' THEN 'link'\n WHEN 'link-override-delete' THEN 'link'\n WHEN 'link-slot-override-upsert' THEN 'scope'\n WHEN 'link-slot-override-delete' THEN 'scope'\n END AS kind,\n CASE json_extract(payload, '$.item.kind')\n WHEN 'object-upsert' THEN json_extract(payload, '$.item.value.row.ref')\n WHEN 'link-upsert' THEN json_extract(payload, '$.item.value.row.ref')\n WHEN 'point-upsert' THEN json_extract(payload, '$.item.value.point.series.object')\n ELSE json_extract(payload, '$.item.value.ref')\n END AS ref\n FROM ${workTable}\n WHERE work_id = $workId AND lane = 'apply'\n )`\n}\n\nexport class SqliteOntologyMaterializationStorage implements OntologyMaterializationStorage {\n private readonly sessions: SqliteMaterializationSessions\n private readonly writer: SqliteMaterializationWriter\n\n constructor(\n private readonly db: Database,\n context: SqliteOntologyTransactionContext | null\n ) {\n this.sessions = new SqliteMaterializationSessions(db, context)\n this.writer = new SqliteMaterializationWriter(db)\n }\n\n assertVectorSession(session: MaterializationSession, projectId: string, commitId?: string): void {\n const active = this.sessions.require(session)\n if (\n active.header.commit.projectId !== projectId ||\n (commitId !== undefined && active.header.commit.id !== commitId)\n ) {\n throw new MaterializationValidationError(\n \"Vector mutation does not belong to this materialization session.\"\n )\n }\n }\n\n async begin(input: MaterializationPlanHeader): Promise<MaterializationSession> {\n assertMaterializationHeader(input)\n const session = this.sessions.create(\n input,\n input.plan ? boundReplacementPlan(this.db, input) : null\n )\n try {\n this.assertCommitAbsent(input)\n const reader = new SqliteMaterializationStateReader(this.db, input.commit.projectId)\n for (const expected of input.expected.sources)\n this.assertSource(expected, input.commit.projectId)\n for (const expected of input.expected.objects) {\n assertExpectedObjectRevision(reader.effectiveObjectRevision(expected.ref), expected)\n }\n for (const expected of input.expected.links) {\n assertExpectedLinkRevision(reader.effectiveLinkLastCommit(expected.ref), expected)\n }\n const linkScopeRevisions = reader.linkScopeRevisions(input.expected.linkScopes)\n for (const [index, expected] of input.expected.linkScopes.entries()) {\n assertExpectedLinkScopeRevision(linkScopeRevisions[index]?.fingerprint, expected)\n }\n for (const expected of input.expected.points) {\n const point = reader.exactPoint(expected.series, expected.at)\n if ((point?.lastCommitId ?? null) !== expected.lastCommitId) {\n throw new MaterializationConflictError(\n \"timeseries-point\",\n `Telemetry point ${telemetryPointKey(expected.series, expected.at)} changed.`\n )\n }\n }\n return session.publicSession()\n } catch (error) {\n this.sessions.release(session)\n throw error\n }\n }\n\n async *streamState(\n input: StreamMaterializationStateInput\n ): AsyncIterable<MaterializationStatePage> {\n const session = this.sessions.require(input.session)\n assertPageRows(input.pageRows)\n const reader = new SqliteMaterializationStateReader(this.db, session.header.commit.projectId)\n for await (const request of input.requests) {\n this.sessions.require(input.session)\n const objects = uniqueSorted(request.objects, objectRefKey, objectRefSortKey)\n for (let offset = 0; offset < objects.length; offset += input.pageRows) {\n const page = reader.objectStates(objects.slice(offset, offset + input.pageRows))\n yield { objects: page, links: [], linkScopes: [], points: [] }\n }\n const links = uniqueSorted(request.links, linkRefKey, linkRefSortKey)\n for (let offset = 0; offset < links.length; offset += input.pageRows) {\n const page = reader.linkStates(links.slice(offset, offset + input.pageRows))\n yield { objects: [], links: page, linkScopes: [], points: [] }\n }\n for (const refs of reader.incidentLinks(request.incidentObjects, input.pageRows)) {\n this.sessions.require(input.session)\n yield {\n objects: [],\n links: reader.linkStates(refs),\n linkScopes: [],\n points: [],\n }\n }\n const scopes = uniqueSorted(\n request.linkScopes,\n (scope) =>\n JSON.stringify([scope.source.objectTypeId, scope.source.primaryId, scope.linkId]),\n (scope) => linkScopeSortKey(scope.source, scope.linkId)\n )\n for (let offset = 0; offset < scopes.length; offset += input.pageRows) {\n yield {\n objects: [],\n links: [],\n linkScopes: reader.linkSlotStates(scopes.slice(offset, offset + input.pageRows)),\n points: [],\n }\n }\n const points = uniqueSorted(\n request.points,\n (point) => telemetryPointKey(point.series, point.at),\n (point) => telemetryPointSortKey(point.series, point.at)\n )\n for (let offset = 0; offset < points.length; offset += input.pageRows) {\n const page = reader.exactPoints(points.slice(offset, offset + input.pageRows))\n if (page.length > 0) yield { objects: [], links: [], linkScopes: [], points: page }\n }\n }\n }\n\n async stageWork(input: StageMaterializationWorkInput): Promise<void> {\n this.sessions.stage(input)\n await yieldSqliteEventLoop()\n }\n\n async *streamVectorChanges(\n input: StreamMaterializationVectorChangesInput\n ): AsyncIterable<MaterializationVectorChangePage> {\n const session = this.sessions.require(input.session)\n assertPageRows(input.pageRows)\n beginMaterializationVectorChanges(session)\n for (const items of this.sessions.vectorChangePages(\n session,\n input.objectTypeIds,\n input.pageRows\n )) {\n yield { items }\n }\n }\n\n async apply(input: ApplyMaterializationInput): Promise<AppliedMaterialization> {\n const session = this.sessions.require(input.session)\n beginMaterializationApply(session)\n const { commit } = session.header\n const cardinality = createCardinalityValidator()\n for (const records of this.sessions.lanePages(session, \"cardinality\", APPLY_PAGE_ROWS)) {\n for (const record of records) cardinality.accept(record)\n }\n let eventCount = 0\n this.db.run(\"SAVEPOINT sixb_ontology_apply\")\n try {\n for (const records of this.sessions.lanePages(session, \"apply\", APPLY_PAGE_ROWS)) {\n // The writer orders tables its own way within a chunk; one phase per chunk keeps the\n // canonical phase order.\n for (const phase of splitByPhase(records)) {\n this.writer.apply(\n commit.projectId,\n commit.id,\n materializationPlanChunk(phase.map((record) => record.item))\n )\n }\n await yieldSqliteEventLoop()\n }\n for (const records of this.sessions.lanePages(session, \"event\", APPLY_PAGE_ROWS)) {\n const outbox = records.map((record) =>\n materializationOutboxWrite(commit, record.draft, eventCount++)\n )\n this.writer.apply(commit.projectId, commit.id, materializationPlanChunk([], outbox))\n await yieldSqliteEventLoop()\n }\n this.db\n .query(touchAppliedWorkStatement(session.workTable))\n .run({ $projectId: commit.projectId, $commitId: commit.id, $workId: session.workId })\n this.db.run(\"RELEASE SAVEPOINT sixb_ontology_apply\")\n } catch (error) {\n this.db.run(\"ROLLBACK TO SAVEPOINT sixb_ontology_apply\")\n this.db.run(\"RELEASE SAVEPOINT sixb_ontology_apply\")\n throw error\n }\n session.appliedEventCount = eventCount\n return { eventCount }\n }\n\n async finalize(input: FinalizeMaterializationInput): Promise<ApplyMaterializationResult> {\n const session = this.sessions.require(input.session)\n this.assertCommitAbsent(session.header)\n await this.assertFinalization(session, input)\n for (const activation of input.finalization.sourceActivations) {\n this.activateSource(session, activation)\n }\n const record = this.insertCommit(session.header, input)\n this.sessions.release(session)\n return { commit: record }\n }\n\n deactivateSessions(): void {\n this.sessions.deactivateAll()\n }\n\n private assertCommitAbsent(header: MaterializationPlanHeader): void {\n const origin = originColumns(header.commit.origin)\n const duplicate = this.db\n .query(\n `\n SELECT CASE\n WHEN id = ? THEN 'id'\n WHEN idempotency_key = ? THEN 'idempotency'\n ELSE 'origin'\n END AS duplicate\n FROM ontology_commits\n WHERE project_id = ? AND (\n id = ? OR idempotency_key = ? OR (\n ? IS NOT NULL AND origin_kind = ? AND origin_run_id = ?\n AND (origin_batch_ordinal IS ? OR origin_batch_ordinal = ?)\n )\n )\n LIMIT 1\n `\n )\n .get(\n header.commit.id,\n header.commit.idempotencyKey,\n header.commit.projectId,\n header.commit.id,\n header.commit.idempotencyKey,\n origin.runId,\n origin.kind,\n origin.runId,\n origin.batchOrdinal,\n origin.batchOrdinal\n ) as { readonly duplicate: \"id\" | \"idempotency\" | \"origin\" } | null\n if (!duplicate) return\n if (duplicate.duplicate === \"origin\") {\n throw new MaterializationConflictError(\n \"run-correlation\",\n \"Ontology commit origin already has an authoritative commit.\"\n )\n }\n throw new MaterializationConflictError(\n \"idempotency\",\n duplicate.duplicate === \"id\"\n ? `Ontology commit '${header.commit.id}' already exists.`\n : \"Ontology idempotency key already exists.\"\n )\n }\n\n private assertSource(\n expected: MaterializationPlanHeader[\"expected\"][\"sources\"][number],\n projectId: string\n ): void {\n const active = this.getActiveSource(projectId, expected.source.projectionId)\n if (\n (active?.materialization_id ?? null) !== expected.activeMaterializationId ||\n (active?.last_commit_id ?? null) !== expected.lastCommitId\n ) {\n throw new MaterializationConflictError(\n \"projection-fence\",\n `Source '${expected.source.projectionId}' changed.`\n )\n }\n }\n\n private async assertFinalization(\n session: SqliteMaterializationSessionState,\n input: FinalizeMaterializationInput\n ): Promise<void> {\n const { commit } = session.header\n const { result } = input.finalization\n assertMaterializationFinalizationCorrelation(session, input)\n this.assertFinalCardinality(session)\n await yieldSqliteEventLoop()\n const eventCount = session.appliedEventCount\n const outbox = this.db\n .query(\n `\n SELECT COUNT(*) AS count, MIN(commit_ordinal) AS minimum, MAX(commit_ordinal) AS maximum\n FROM ontology_outbox WHERE project_id = ? AND commit_id = ?\n `\n )\n .get(commit.projectId, commit.id) as {\n readonly count: number\n readonly minimum: number | null\n readonly maximum: number | null\n }\n if (\n outbox.count !== eventCount ||\n (eventCount > 0 && (outbox.minimum !== 0 || outbox.maximum !== eventCount - 1))\n ) {\n invalidCorrelation(\"Outbox event ordinals must be contiguous from zero.\")\n }\n await yieldSqliteEventLoop()\n\n if (commit.intent.kind === \"telemetry\") {\n const summary = this.sessions.telemetrySummary(session, commit.intent.pointCount)\n await yieldSqliteEventLoop()\n if (summary.classifiedPoints !== commit.intent.pointCount) {\n invalidCorrelation(\n \"Telemetry point classification coverage does not match the commit intent.\"\n )\n }\n if (result.kind !== \"telemetry\" || !sameCounts(result, summary.counts)) {\n invalidCorrelation(\"Telemetry result counts do not correlate with finalized work.\")\n }\n }\n if (commit.intent.kind === \"projection\") {\n if (result.kind !== \"projection\") return\n this.sessions.assertClassificationCoverage(session)\n await yieldSqliteEventLoop()\n const counts = this.sessions.projectionCounts(session)\n await yieldSqliteEventLoop()\n if (!sameCounts(result.counts, counts)) {\n invalidCorrelation(\"Projection result counts do not correlate with finalized work.\")\n }\n }\n }\n\n private assertFinalCardinality(session: SqliteMaterializationSessionState): void {\n const violation = this.db\n .query(\n `\n WITH scopes AS (\n SELECT sort_one AS scope_sort_key,\n cardinality_source_type_id AS source_type_id,\n cardinality_source_primary_id AS source_id,\n cardinality_link_id AS link_id,\n SUM(cardinality_occupied) AS expected_count,\n MAX(CASE WHEN cardinality_occupied = 1\n THEN cardinality_target_type_id END) AS expected_target_type_id,\n MAX(CASE WHEN cardinality_occupied = 1\n THEN cardinality_target_primary_id END) AS expected_target_id\n FROM ${session.workTable}\n WHERE work_id = ? AND kind = 'cardinality'\n AND cardinality_view = 'effective'\n GROUP BY sort_one, cardinality_source_type_id,\n cardinality_source_primary_id, cardinality_link_id\n ), validated AS (\n SELECT scopes.scope_sort_key, scopes.expected_count,\n COUNT(links.source_id) AS actual_count,\n COUNT(links.source_id) FILTER (\n WHERE links.target_type_id = scopes.expected_target_type_id\n AND links.target_id = scopes.expected_target_id\n ) AS matching_count\n FROM scopes\n LEFT JOIN links\n ON links.project_id = ?\n AND links.source_type_id = scopes.source_type_id\n AND links.source_id = scopes.source_id\n AND links.link_id = scopes.link_id\n GROUP BY scopes.scope_sort_key, scopes.expected_count,\n scopes.expected_target_type_id, scopes.expected_target_id\n )\n SELECT 1 AS mismatch\n FROM validated\n WHERE actual_count <> expected_count OR matching_count <> expected_count\n LIMIT 1\n `\n )\n .get(session.workId, session.header.commit.projectId)\n // Apply already rejected a scope with two staged occupants; this checks what it wrote.\n if (violation) {\n invalidCorrelation(\n \"Materialization cardinality work does not match the final effective link scope.\"\n )\n }\n }\n\n private activateSource(\n session: SqliteMaterializationSessionState,\n activation: SourceActivationWrite\n ): void {\n const { commit } = session.header\n assertSourceActivationCorrelation(session, activation)\n const candidate = this.getSource(\n commit.projectId,\n activation.source.projectionId,\n activation.materializationId\n )\n if (!candidate || candidate.status !== \"ready\" || candidate.execution_token === null) {\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"Source activation candidate is missing or is not ready.\"\n )\n }\n assertProjectionExecution(this.db, {\n projectId: commit.projectId,\n sourceId: activation.source.projectionId,\n projectionRunId: activation.execution.projectionRunId,\n executionToken: activation.execution.executionToken,\n })\n if (\n candidate.projection_run_id !== activation.execution.projectionRunId ||\n candidate.execution_token !== activation.execution.executionToken ||\n candidate.projection_kind !== activation.projectionKind ||\n candidate.protocol !== activation.protocol ||\n candidate.dataset_id !== activation.datasetVersion.datasetId ||\n candidate.dataset_version_id !== activation.datasetVersion.versionId ||\n candidate.dataset_version_created_at !== activation.datasetVersion.createdAt ||\n candidate.projection_revision !== activation.projectionRevision ||\n candidate.ownership_hash !== activation.ownershipHash ||\n candidate.ontology_revision !== activation.ontologyRevision ||\n candidate.ready_at === null ||\n activation.updatedAt < candidate.ready_at\n ) {\n invalidCorrelation(\"Source activation does not match its ready candidate identity.\")\n }\n this.assertSource(activation.expected, commit.projectId)\n activateSourceRoots(this.db, commit.projectId, commit.id, candidate, activation)\n const previous = this.getActiveSource(commit.projectId, activation.source.projectionId)\n if (previous) {\n assertPinnedDatasetWatermark(\n {\n datasetId: previous.dataset_id,\n versionId: previous.dataset_version_id,\n createdAt: previous.dataset_version_created_at,\n },\n activation.datasetVersion,\n \"Source activation\"\n )\n if (activation.updatedAt < previous.updated_at) {\n invalidCorrelation(\"Source activation cannot precede the active materialization update.\")\n }\n requireChanges(\n this.db\n .query(\n `\n UPDATE ontology_sources\n SET status = 'superseded', execution_token = NULL, terminal_at = ?, updated_at = ?\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?\n AND status = 'active' AND last_commit_id = ?\n `\n )\n .run(\n activation.updatedAt,\n activation.updatedAt,\n commit.projectId,\n activation.source.projectionId,\n previous.materialization_id,\n activation.expected.lastCommitId\n ).changes,\n \"projection-fence\",\n `Source '${activation.source.projectionId}' changed.`\n )\n }\n requireChanges(\n this.db\n .query(\n `\n UPDATE ontology_sources\n SET status = 'active', execution_token = NULL, activated_at = ?,\n last_commit_id = ?, updated_at = ?\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?\n AND status = 'ready' AND execution_token = ?\n `\n )\n .run(\n activation.updatedAt,\n activation.lastCommitId,\n activation.updatedAt,\n commit.projectId,\n activation.source.projectionId,\n activation.materializationId,\n activation.execution.executionToken\n ).changes,\n \"source-materialization\",\n \"Source activation candidate changed.\"\n )\n }\n\n private insertCommit(\n header: MaterializationPlanHeader,\n input: FinalizeMaterializationInput\n ): OntologyCommitRecord {\n const { commit } = header\n const origin = originColumns(commit.origin)\n try {\n this.db\n .query(\n `\n INSERT INTO ontology_commits (\n project_id, id, idempotency_key, request_hash, execution_id,\n origin_kind, origin_run_id, origin_batch_ordinal, origin,\n ontology_revision, projection_revision, ownership_hash,\n intent, result, committed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, json(?), ?, ?, ?, json(?), json(?), ?)\n `\n )\n .run(\n commit.projectId,\n commit.id,\n commit.idempotencyKey,\n commit.requestHash,\n commit.executionId,\n origin.kind,\n origin.runId,\n origin.batchOrdinal,\n canonicalJson(commit.origin),\n commit.ontologyRevision,\n commit.projectionRevision ?? null,\n commit.ownershipHash ?? null,\n canonicalJson(commit.intent),\n canonicalJson(input.finalization.result),\n commit.committedAt\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw new MaterializationConflictError(\n \"idempotency\",\n \"Ontology commit identity already exists.\"\n )\n }\n throw error\n }\n const row = this.db\n .query(\"SELECT * FROM ontology_commits WHERE project_id = ? AND id = ?\")\n .get(commit.projectId, commit.id) as SqliteOntologyCommitRow\n return commitRecord(row)\n }\n\n private getActiveSource(projectId: string, sourceId: string): SqliteOntologySourceRow | null {\n return this.db\n .query(\n `SELECT * FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND status = 'active'`\n )\n .get(projectId, sourceId) as SqliteOntologySourceRow | null\n }\n\n private getSource(\n projectId: string,\n sourceId: string,\n materializationId: string\n ): SqliteOntologySourceRow | null {\n return this.db\n .query(\n `SELECT * FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?`\n )\n .get(projectId, sourceId, materializationId) as SqliteOntologySourceRow | null\n }\n}\n\nfunction splitByPhase(\n records: readonly MaterializationPlanWorkRecord[]\n): MaterializationPlanWorkRecord[][] {\n const phases: MaterializationPlanWorkRecord[][] = []\n for (const record of records) {\n const current = phases[phases.length - 1]\n if (current && current[0]!.applyPhase === record.applyPhase) current.push(record)\n else phases.push([record])\n }\n return phases\n}\n",
56
+ "import type { Database } from \"bun:sqlite\"\nimport {\n assertPinnedDatasetWatermark,\n linkRefKey,\n linkRefSortKey,\n linkScopeSortKey,\n MaterializationConflictError,\n MaterializationValidationError,\n objectRefKey,\n objectRefSortKey,\n telemetryPointKey,\n telemetryPointSortKey,\n} from \"@sixb/core/internal/materialization\"\nimport {\n assertExpectedLinkRevision,\n assertExpectedLinkScopeRevision,\n assertExpectedObjectRevision,\n assertMaterializationFinalizationCorrelation,\n assertMaterializationHeader,\n assertPageRows,\n assertSourceActivationCorrelation,\n beginMaterializationApply,\n beginMaterializationVectorChanges,\n createCardinalityValidator,\n invalidCorrelation,\n materializationOutboxWrite,\n materializationPlanChunk,\n sameNonnegativeCounts as sameCounts,\n uniqueSorted,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type {\n AppliedMaterialization,\n ApplyMaterializationInput,\n ApplyMaterializationResult,\n FinalizeMaterializationInput,\n MaterializationPlanHeader,\n MaterializationPlanWorkRecord,\n MaterializationSession,\n MaterializationStatePage,\n MaterializationVectorChangePage,\n OntologyCommitRecord,\n OntologyMaterializationStorage,\n SourceActivationWrite,\n StageMaterializationWorkInput,\n StreamMaterializationStateInput,\n StreamMaterializationVectorChangesInput,\n} from \"@sixb/core/storage\"\nimport { yieldSqliteEventLoop } from \"../transactions\"\nimport {\n type SqliteMaterializationSessionState,\n SqliteMaterializationSessions,\n type SqliteOntologyTransactionContext,\n} from \"./materialization-session\"\nimport { SqliteMaterializationStateReader } from \"./materialization-state\"\nimport { SqliteMaterializationWriter } from \"./materialization-writer\"\nimport { boundReplacementPlan } from \"./replacement-plans\"\nimport {\n assertProjectionExecution,\n canonicalJson,\n commitRecord,\n isSqliteConstraintError,\n originColumns,\n requireChanges,\n type SqliteOntologyCommitRow,\n type SqliteOntologySourceRow,\n} from \"./shared\"\nimport { activateSourceRoots } from \"./source-roots\"\nimport { sqliteUniqueHolder } from \"./unique-values\"\n\n/** Rows the provider reads and writes at once while it applies a staged plan. */\nconst APPLY_PAGE_ROWS = 1_000\n\n/**\n * Records the entities whose plan inputs a commit's applied work changed, once each, as the\n * in-memory `touchPlanItem` does: a replacement plan's refresh rechecks only those.\n */\nfunction touchAppliedWorkStatement(workTable: string): string {\n return `\n INSERT INTO ontology_commit_touches (project_id, commit_id, entity_kind, identity_key)\n SELECT DISTINCT $projectId, $commitId, kind, CASE kind\n WHEN 'object' THEN\n json_array(json_extract(ref, '$.objectTypeId'), json_extract(ref, '$.primaryId'))\n WHEN 'scope' THEN json_array(\n json_extract(ref, '$.source.objectTypeId'), json_extract(ref, '$.source.primaryId'),\n json_extract(ref, '$.linkId')\n )\n ELSE json_array(\n json_extract(ref, '$.source.objectTypeId'), json_extract(ref, '$.source.primaryId'),\n json_extract(ref, '$.linkId'), json_extract(ref, '$.target.objectTypeId'),\n json_extract(ref, '$.target.primaryId')\n )\n END\n FROM (\n SELECT CASE json_extract(payload, '$.item.kind')\n WHEN 'object-upsert' THEN 'object'\n WHEN 'object-delete' THEN 'object'\n WHEN 'object-override-upsert' THEN 'object'\n WHEN 'object-override-delete' THEN 'object'\n WHEN 'point-upsert' THEN 'object'\n WHEN 'link-upsert' THEN 'link'\n WHEN 'link-delete' THEN 'link'\n WHEN 'link-override-upsert' THEN 'link'\n WHEN 'link-override-delete' THEN 'link'\n WHEN 'link-slot-override-upsert' THEN 'scope'\n WHEN 'link-slot-override-delete' THEN 'scope'\n END AS kind,\n CASE json_extract(payload, '$.item.kind')\n WHEN 'object-upsert' THEN json_extract(payload, '$.item.value.row.ref')\n WHEN 'link-upsert' THEN json_extract(payload, '$.item.value.row.ref')\n WHEN 'point-upsert' THEN json_extract(payload, '$.item.value.point.series.object')\n ELSE json_extract(payload, '$.item.value.ref')\n END AS ref\n FROM ${workTable}\n WHERE work_id = $workId AND lane = 'apply'\n )\n -- Unique values are no plan input: a stale claim fails when it applies.\n WHERE kind IS NOT NULL`\n}\n\nexport class SqliteOntologyMaterializationStorage implements OntologyMaterializationStorage {\n private readonly sessions: SqliteMaterializationSessions\n private readonly writer: SqliteMaterializationWriter\n\n constructor(\n private readonly db: Database,\n context: SqliteOntologyTransactionContext | null\n ) {\n this.sessions = new SqliteMaterializationSessions(db, context)\n this.writer = new SqliteMaterializationWriter(db)\n }\n\n assertVectorSession(session: MaterializationSession, projectId: string, commitId?: string): void {\n const active = this.sessions.require(session)\n if (\n active.header.commit.projectId !== projectId ||\n (commitId !== undefined && active.header.commit.id !== commitId)\n ) {\n throw new MaterializationValidationError(\n \"Vector mutation does not belong to this materialization session.\"\n )\n }\n }\n\n async begin(input: MaterializationPlanHeader): Promise<MaterializationSession> {\n assertMaterializationHeader(input)\n const session = this.sessions.create(\n input,\n input.plan ? boundReplacementPlan(this.db, input) : null\n )\n try {\n this.assertCommitAbsent(input)\n const reader = new SqliteMaterializationStateReader(this.db, input.commit.projectId)\n for (const expected of input.expected.sources)\n this.assertSource(expected, input.commit.projectId)\n for (const expected of input.expected.objects) {\n assertExpectedObjectRevision(reader.effectiveObjectRevision(expected.ref), expected)\n }\n for (const expected of input.expected.links) {\n assertExpectedLinkRevision(reader.effectiveLinkLastCommit(expected.ref), expected)\n }\n const linkScopeRevisions = reader.linkScopeRevisions(input.expected.linkScopes)\n for (const [index, expected] of input.expected.linkScopes.entries()) {\n assertExpectedLinkScopeRevision(linkScopeRevisions[index]?.fingerprint, expected)\n }\n for (const expected of input.expected.points) {\n const point = reader.exactPoint(expected.series, expected.at)\n if ((point?.lastCommitId ?? null) !== expected.lastCommitId) {\n throw new MaterializationConflictError(\n \"timeseries-point\",\n `Telemetry point ${telemetryPointKey(expected.series, expected.at)} changed.`\n )\n }\n }\n return session.publicSession()\n } catch (error) {\n this.sessions.release(session)\n throw error\n }\n }\n\n async *streamState(\n input: StreamMaterializationStateInput\n ): AsyncIterable<MaterializationStatePage> {\n const session = this.sessions.require(input.session)\n assertPageRows(input.pageRows)\n const reader = new SqliteMaterializationStateReader(this.db, session.header.commit.projectId)\n for await (const request of input.requests) {\n this.sessions.require(input.session)\n const objects = uniqueSorted(request.objects, objectRefKey, objectRefSortKey)\n for (let offset = 0; offset < objects.length; offset += input.pageRows) {\n const page = reader.objectStates(objects.slice(offset, offset + input.pageRows))\n yield { objects: page, links: [], linkScopes: [], points: [] }\n }\n const links = uniqueSorted(request.links, linkRefKey, linkRefSortKey)\n for (let offset = 0; offset < links.length; offset += input.pageRows) {\n const page = reader.linkStates(links.slice(offset, offset + input.pageRows))\n yield { objects: [], links: page, linkScopes: [], points: [] }\n }\n for (const refs of reader.incidentLinks(request.incidentObjects, input.pageRows)) {\n this.sessions.require(input.session)\n yield {\n objects: [],\n links: reader.linkStates(refs),\n linkScopes: [],\n points: [],\n }\n }\n const scopes = uniqueSorted(\n request.linkScopes,\n (scope) =>\n JSON.stringify([scope.source.objectTypeId, scope.source.primaryId, scope.linkId]),\n (scope) => linkScopeSortKey(scope.source, scope.linkId)\n )\n for (let offset = 0; offset < scopes.length; offset += input.pageRows) {\n yield {\n objects: [],\n links: [],\n linkScopes: reader.linkSlotStates(scopes.slice(offset, offset + input.pageRows)),\n points: [],\n }\n }\n const points = uniqueSorted(\n request.points,\n (point) => telemetryPointKey(point.series, point.at),\n (point) => telemetryPointSortKey(point.series, point.at)\n )\n for (let offset = 0; offset < points.length; offset += input.pageRows) {\n const page = reader.exactPoints(points.slice(offset, offset + input.pageRows))\n if (page.length > 0) yield { objects: [], links: [], linkScopes: [], points: page }\n }\n const uniqueValues = request.uniqueValues ?? []\n for (let offset = 0; offset < uniqueValues.length; offset += input.pageRows) {\n const uniqueHolders = uniqueValues\n .slice(offset, offset + input.pageRows)\n .flatMap((value) => {\n const primaryId = sqliteUniqueHolder(this.db, session.header.commit.projectId, value)\n return primaryId === null ? [] : [{ ...value, primaryId }]\n })\n if (uniqueHolders.length > 0) {\n yield { objects: [], links: [], linkScopes: [], points: [], uniqueHolders }\n }\n }\n }\n }\n\n async stageWork(input: StageMaterializationWorkInput): Promise<void> {\n this.sessions.stage(input)\n await yieldSqliteEventLoop()\n }\n\n async *streamVectorChanges(\n input: StreamMaterializationVectorChangesInput\n ): AsyncIterable<MaterializationVectorChangePage> {\n const session = this.sessions.require(input.session)\n assertPageRows(input.pageRows)\n beginMaterializationVectorChanges(session)\n for (const items of this.sessions.vectorChangePages(\n session,\n input.objectTypeIds,\n input.pageRows\n )) {\n yield { items }\n }\n }\n\n async apply(input: ApplyMaterializationInput): Promise<AppliedMaterialization> {\n const session = this.sessions.require(input.session)\n beginMaterializationApply(session)\n const { commit } = session.header\n const cardinality = createCardinalityValidator()\n for (const records of this.sessions.lanePages(session, \"cardinality\", APPLY_PAGE_ROWS)) {\n for (const record of records) cardinality.accept(record)\n }\n let eventCount = 0\n this.db.run(\"SAVEPOINT sixb_ontology_apply\")\n try {\n for (const records of this.sessions.lanePages(session, \"apply\", APPLY_PAGE_ROWS)) {\n // The writer orders tables its own way within a chunk; one phase per chunk keeps the\n // canonical phase order.\n for (const phase of splitByPhase(records)) {\n this.writer.apply(\n commit.projectId,\n commit.id,\n materializationPlanChunk(phase.map((record) => record.item))\n )\n }\n await yieldSqliteEventLoop()\n }\n for (const records of this.sessions.lanePages(session, \"event\", APPLY_PAGE_ROWS)) {\n const outbox = records.map((record) =>\n materializationOutboxWrite(commit, record.draft, eventCount++)\n )\n this.writer.apply(commit.projectId, commit.id, materializationPlanChunk([], outbox))\n await yieldSqliteEventLoop()\n }\n this.db\n .query(touchAppliedWorkStatement(session.workTable))\n .run({ $projectId: commit.projectId, $commitId: commit.id, $workId: session.workId })\n this.db.run(\"RELEASE SAVEPOINT sixb_ontology_apply\")\n } catch (error) {\n this.db.run(\"ROLLBACK TO SAVEPOINT sixb_ontology_apply\")\n this.db.run(\"RELEASE SAVEPOINT sixb_ontology_apply\")\n throw error\n }\n session.appliedEventCount = eventCount\n return { eventCount }\n }\n\n async finalize(input: FinalizeMaterializationInput): Promise<ApplyMaterializationResult> {\n const session = this.sessions.require(input.session)\n this.assertCommitAbsent(session.header)\n await this.assertFinalization(session, input)\n for (const activation of input.finalization.sourceActivations) {\n this.activateSource(session, activation)\n }\n const record = this.insertCommit(session.header, input)\n this.sessions.release(session)\n return { commit: record }\n }\n\n deactivateSessions(): void {\n this.sessions.deactivateAll()\n }\n\n private assertCommitAbsent(header: MaterializationPlanHeader): void {\n const origin = originColumns(header.commit.origin)\n const duplicate = this.db\n .query(\n `\n SELECT CASE\n WHEN id = ? THEN 'id'\n WHEN idempotency_key = ? THEN 'idempotency'\n ELSE 'origin'\n END AS duplicate\n FROM ontology_commits\n WHERE project_id = ? AND (\n id = ? OR idempotency_key = ? OR (\n ? IS NOT NULL AND origin_kind = ? AND origin_run_id = ?\n AND (origin_batch_ordinal IS ? OR origin_batch_ordinal = ?)\n )\n )\n LIMIT 1\n `\n )\n .get(\n header.commit.id,\n header.commit.idempotencyKey,\n header.commit.projectId,\n header.commit.id,\n header.commit.idempotencyKey,\n origin.runId,\n origin.kind,\n origin.runId,\n origin.batchOrdinal,\n origin.batchOrdinal\n ) as { readonly duplicate: \"id\" | \"idempotency\" | \"origin\" } | null\n if (!duplicate) return\n if (duplicate.duplicate === \"origin\") {\n throw new MaterializationConflictError(\n \"run-correlation\",\n \"Ontology commit origin already has an authoritative commit.\"\n )\n }\n throw new MaterializationConflictError(\n \"idempotency\",\n duplicate.duplicate === \"id\"\n ? `Ontology commit '${header.commit.id}' already exists.`\n : \"Ontology idempotency key already exists.\"\n )\n }\n\n private assertSource(\n expected: MaterializationPlanHeader[\"expected\"][\"sources\"][number],\n projectId: string\n ): void {\n const active = this.getActiveSource(projectId, expected.source.projectionId)\n if (\n (active?.materialization_id ?? null) !== expected.activeMaterializationId ||\n (active?.last_commit_id ?? null) !== expected.lastCommitId\n ) {\n throw new MaterializationConflictError(\n \"projection-fence\",\n `Source '${expected.source.projectionId}' changed.`\n )\n }\n }\n\n private async assertFinalization(\n session: SqliteMaterializationSessionState,\n input: FinalizeMaterializationInput\n ): Promise<void> {\n const { commit } = session.header\n const { result } = input.finalization\n assertMaterializationFinalizationCorrelation(session, input)\n this.assertFinalCardinality(session)\n await yieldSqliteEventLoop()\n const eventCount = session.appliedEventCount\n const outbox = this.db\n .query(\n `\n SELECT COUNT(*) AS count, MIN(commit_ordinal) AS minimum, MAX(commit_ordinal) AS maximum\n FROM ontology_outbox WHERE project_id = ? AND commit_id = ?\n `\n )\n .get(commit.projectId, commit.id) as {\n readonly count: number\n readonly minimum: number | null\n readonly maximum: number | null\n }\n if (\n outbox.count !== eventCount ||\n (eventCount > 0 && (outbox.minimum !== 0 || outbox.maximum !== eventCount - 1))\n ) {\n invalidCorrelation(\"Outbox event ordinals must be contiguous from zero.\")\n }\n await yieldSqliteEventLoop()\n\n if (commit.intent.kind === \"telemetry\") {\n const summary = this.sessions.telemetrySummary(session, commit.intent.pointCount)\n await yieldSqliteEventLoop()\n if (summary.classifiedPoints !== commit.intent.pointCount) {\n invalidCorrelation(\n \"Telemetry point classification coverage does not match the commit intent.\"\n )\n }\n if (result.kind !== \"telemetry\" || !sameCounts(result, summary.counts)) {\n invalidCorrelation(\"Telemetry result counts do not correlate with finalized work.\")\n }\n }\n if (commit.intent.kind === \"projection\") {\n if (result.kind !== \"projection\") return\n this.sessions.assertClassificationCoverage(session)\n await yieldSqliteEventLoop()\n const counts = this.sessions.projectionCounts(session)\n await yieldSqliteEventLoop()\n if (!sameCounts(result.counts, counts)) {\n invalidCorrelation(\"Projection result counts do not correlate with finalized work.\")\n }\n }\n }\n\n private assertFinalCardinality(session: SqliteMaterializationSessionState): void {\n const violation = this.db\n .query(\n `\n WITH scopes AS (\n SELECT sort_one AS scope_sort_key,\n cardinality_source_type_id AS source_type_id,\n cardinality_source_primary_id AS source_id,\n cardinality_link_id AS link_id,\n SUM(cardinality_occupied) AS expected_count,\n MAX(CASE WHEN cardinality_occupied = 1\n THEN cardinality_target_type_id END) AS expected_target_type_id,\n MAX(CASE WHEN cardinality_occupied = 1\n THEN cardinality_target_primary_id END) AS expected_target_id\n FROM ${session.workTable}\n WHERE work_id = ? AND kind = 'cardinality'\n AND cardinality_view = 'effective'\n GROUP BY sort_one, cardinality_source_type_id,\n cardinality_source_primary_id, cardinality_link_id\n ), validated AS (\n SELECT scopes.scope_sort_key, scopes.expected_count,\n COUNT(links.source_id) AS actual_count,\n COUNT(links.source_id) FILTER (\n WHERE links.target_type_id = scopes.expected_target_type_id\n AND links.target_id = scopes.expected_target_id\n ) AS matching_count\n FROM scopes\n LEFT JOIN links\n ON links.project_id = ?\n AND links.source_type_id = scopes.source_type_id\n AND links.source_id = scopes.source_id\n AND links.link_id = scopes.link_id\n GROUP BY scopes.scope_sort_key, scopes.expected_count,\n scopes.expected_target_type_id, scopes.expected_target_id\n )\n SELECT 1 AS mismatch\n FROM validated\n WHERE actual_count <> expected_count OR matching_count <> expected_count\n LIMIT 1\n `\n )\n .get(session.workId, session.header.commit.projectId)\n // Apply already rejected a scope with two staged occupants; this checks what it wrote.\n if (violation) {\n invalidCorrelation(\n \"Materialization cardinality work does not match the final effective link scope.\"\n )\n }\n }\n\n private activateSource(\n session: SqliteMaterializationSessionState,\n activation: SourceActivationWrite\n ): void {\n const { commit } = session.header\n assertSourceActivationCorrelation(session, activation)\n const candidate = this.getSource(\n commit.projectId,\n activation.source.projectionId,\n activation.materializationId\n )\n if (!candidate || candidate.status !== \"ready\" || candidate.execution_token === null) {\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"Source activation candidate is missing or is not ready.\"\n )\n }\n assertProjectionExecution(this.db, {\n projectId: commit.projectId,\n sourceId: activation.source.projectionId,\n projectionRunId: activation.execution.projectionRunId,\n executionToken: activation.execution.executionToken,\n })\n if (\n candidate.projection_run_id !== activation.execution.projectionRunId ||\n candidate.execution_token !== activation.execution.executionToken ||\n candidate.projection_kind !== activation.projectionKind ||\n candidate.protocol !== activation.protocol ||\n candidate.dataset_id !== activation.datasetVersion.datasetId ||\n candidate.dataset_version_id !== activation.datasetVersion.versionId ||\n candidate.dataset_version_created_at !== activation.datasetVersion.createdAt ||\n candidate.projection_revision !== activation.projectionRevision ||\n candidate.ownership_hash !== activation.ownershipHash ||\n candidate.ontology_revision !== activation.ontologyRevision ||\n candidate.ready_at === null ||\n activation.updatedAt < candidate.ready_at\n ) {\n invalidCorrelation(\"Source activation does not match its ready candidate identity.\")\n }\n this.assertSource(activation.expected, commit.projectId)\n activateSourceRoots(this.db, commit.projectId, commit.id, candidate, activation)\n const previous = this.getActiveSource(commit.projectId, activation.source.projectionId)\n if (previous) {\n assertPinnedDatasetWatermark(\n {\n datasetId: previous.dataset_id,\n versionId: previous.dataset_version_id,\n createdAt: previous.dataset_version_created_at,\n },\n activation.datasetVersion,\n \"Source activation\"\n )\n if (activation.updatedAt < previous.updated_at) {\n invalidCorrelation(\"Source activation cannot precede the active materialization update.\")\n }\n requireChanges(\n this.db\n .query(\n `\n UPDATE ontology_sources\n SET status = 'superseded', execution_token = NULL, terminal_at = ?, updated_at = ?\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?\n AND status = 'active' AND last_commit_id = ?\n `\n )\n .run(\n activation.updatedAt,\n activation.updatedAt,\n commit.projectId,\n activation.source.projectionId,\n previous.materialization_id,\n activation.expected.lastCommitId\n ).changes,\n \"projection-fence\",\n `Source '${activation.source.projectionId}' changed.`\n )\n }\n requireChanges(\n this.db\n .query(\n `\n UPDATE ontology_sources\n SET status = 'active', execution_token = NULL, activated_at = ?,\n last_commit_id = ?, updated_at = ?\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?\n AND status = 'ready' AND execution_token = ?\n `\n )\n .run(\n activation.updatedAt,\n activation.lastCommitId,\n activation.updatedAt,\n commit.projectId,\n activation.source.projectionId,\n activation.materializationId,\n activation.execution.executionToken\n ).changes,\n \"source-materialization\",\n \"Source activation candidate changed.\"\n )\n }\n\n private insertCommit(\n header: MaterializationPlanHeader,\n input: FinalizeMaterializationInput\n ): OntologyCommitRecord {\n const { commit } = header\n const origin = originColumns(commit.origin)\n try {\n this.db\n .query(\n `\n INSERT INTO ontology_commits (\n project_id, id, idempotency_key, request_hash, execution_id,\n origin_kind, origin_run_id, origin_batch_ordinal, origin,\n ontology_revision, projection_revision, ownership_hash,\n intent, result, committed_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, json(?), ?, ?, ?, json(?), json(?), ?)\n `\n )\n .run(\n commit.projectId,\n commit.id,\n commit.idempotencyKey,\n commit.requestHash,\n commit.executionId,\n origin.kind,\n origin.runId,\n origin.batchOrdinal,\n canonicalJson(commit.origin),\n commit.ontologyRevision,\n commit.projectionRevision ?? null,\n commit.ownershipHash ?? null,\n canonicalJson(commit.intent),\n canonicalJson(input.finalization.result),\n commit.committedAt\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw new MaterializationConflictError(\n \"idempotency\",\n \"Ontology commit identity already exists.\"\n )\n }\n throw error\n }\n const row = this.db\n .query(\"SELECT * FROM ontology_commits WHERE project_id = ? AND id = ?\")\n .get(commit.projectId, commit.id) as SqliteOntologyCommitRow\n return commitRecord(row)\n }\n\n private getActiveSource(projectId: string, sourceId: string): SqliteOntologySourceRow | null {\n return this.db\n .query(\n `SELECT * FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND status = 'active'`\n )\n .get(projectId, sourceId) as SqliteOntologySourceRow | null\n }\n\n private getSource(\n projectId: string,\n sourceId: string,\n materializationId: string\n ): SqliteOntologySourceRow | null {\n return this.db\n .query(\n `SELECT * FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?`\n )\n .get(projectId, sourceId, materializationId) as SqliteOntologySourceRow | null\n }\n}\n\nfunction splitByPhase(\n records: readonly MaterializationPlanWorkRecord[]\n): MaterializationPlanWorkRecord[][] {\n const phases: MaterializationPlanWorkRecord[][] = []\n for (const record of records) {\n const current = phases[phases.length - 1]\n if (current && current[0]!.applyPhase === record.applyPhase) current.push(record)\n else phases.push([record])\n }\n return phases\n}\n",
52
57
  "import type { Database } from \"bun:sqlite\"\nimport {\n type EffectiveChangeCounts,\n MaterializationConflictError,\n} from \"@sixb/core/internal/materialization\"\nimport {\n duplicateMaterializationWork as duplicateWork,\n ProviderMaterializationSessionState,\n type ProviderMaterializationTransactionLifecycle,\n prepareMaterializationWork,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type {\n MaterializationCardinalityOccupantWorkRecord,\n MaterializationEventWorkRecord,\n MaterializationPlanHeader,\n MaterializationPlanWorkRecord,\n MaterializationSession,\n MaterializationVectorChange,\n MaterializationWorkRecord,\n StageMaterializationWorkInput,\n} from \"@sixb/core/storage\"\nimport { SQLITE_MATERIALIZATION_WORK_TABLE } from \"./materialization-state\"\nimport {\n assertReplacementPlanCoverage,\n replacementPlanCounts,\n SQLITE_PLAN_WORK_TABLE,\n type SqliteReplacementPlan,\n} from \"./replacement-plans\"\nimport { canonicalJson, isSqliteConstraintError, parseJson } from \"./shared\"\n\nexport interface SqliteOntologyTransactionContext {\n readonly id: object\n readonly materializations: ProviderMaterializationTransactionLifecycle\n active: boolean\n}\n\ninterface WorkCursor {\n readonly majorOrder: number\n readonly minorOrder: number\n readonly sortOne: string\n readonly sortTwo: string\n readonly recordKey: string\n}\n\ninterface WorkDatabaseRow {\n readonly record_key: string\n readonly major_order: number\n readonly minor_order: number\n readonly sort_one: string\n readonly sort_two: string\n readonly payload: string\n}\n\ninterface WorkSummary {\n objectClassifications: number\n linkClassifications: number\n pointClassifications: number\n objectsCreated: number\n objectsUpdated: number\n objectsDeleted: number\n linksCreated: number\n linksUpdated: number\n linksDeleted: number\n pointsCreated: number\n pointsUpdated: number\n latestObjectsChanged: number\n}\n\ntype WorkLane = \"apply\" | \"cardinality\" | \"event\"\n\ninterface LaneRecord {\n readonly apply: MaterializationPlanWorkRecord\n readonly cardinality: MaterializationCardinalityOccupantWorkRecord\n readonly event: MaterializationEventWorkRecord\n}\n\nexport class SqliteMaterializationSessionState extends ProviderMaterializationSessionState {\n readonly summary: WorkSummary = emptyWorkSummary()\n /** Work staged on the session lives in a temp table; a plan-bound session reads its plan's. */\n readonly workTable: string\n readonly workId: string | number\n\n constructor(\n header: MaterializationPlanHeader,\n transactionId: object,\n readonly plan: SqliteReplacementPlan | null\n ) {\n super(header, transactionId)\n this.workTable = plan ? SQLITE_PLAN_WORK_TABLE : SQLITE_MATERIALIZATION_WORK_TABLE\n this.workId = plan ? plan.versionId : this.id\n }\n}\n\nexport class SqliteMaterializationSessions {\n private readonly sessions = new WeakMap<object, SqliteMaterializationSessionState>()\n private readonly live = new Set<SqliteMaterializationSessionState>()\n\n constructor(\n private readonly db: Database,\n private readonly context: SqliteOntologyTransactionContext | null\n ) {}\n\n create(\n header: MaterializationPlanHeader,\n plan: SqliteReplacementPlan | null\n ): SqliteMaterializationSessionState {\n if (!this.context?.active) {\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Materialization sessions require an active storage transaction.\"\n )\n }\n this.ensureTables()\n const session = new SqliteMaterializationSessionState(\n structuredClone(header),\n this.context.id,\n plan\n )\n this.sessions.set(session.providerToken, session)\n this.live.add(session)\n this.context.materializations.register(session.providerToken)\n return session\n }\n\n require(session: MaterializationSession): SqliteMaterializationSessionState {\n const value = this.sessions.get(session.providerToken)\n if (\n !value ||\n !value.active ||\n !this.context?.active ||\n value.transactionId !== this.context.id\n ) {\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Materialization session is inactive.\"\n )\n }\n return value\n }\n\n release(session: SqliteMaterializationSessionState): void {\n if (!session.active) return\n session.active = false\n this.live.delete(session)\n // The normal transaction has one session. Dropping its transaction-local spool avoids an\n // indexed DELETE over hundreds of thousands of rows and releases temp pages immediately.\n // Preserve per-session deletion only when another live session still shares the tables.\n // A plan's rows outlive the session: maintenance deletes them once the candidate moved on.\n if (this.live.size === 0) this.dropWorkTables()\n else if (!session.plan) this.deleteWork(session.id)\n this.context?.materializations.complete(session.providerToken)\n }\n\n deactivateAll(): void {\n for (const session of this.live) this.release(session)\n }\n\n stage(input: StageMaterializationWorkInput): void {\n const session = this.require(input.session)\n const records = prepareMaterializationWork(session, input)\n if (records.length === 0) return\n const insert = this.db.query(\n `\n INSERT INTO ${SQLITE_MATERIALIZATION_WORK_TABLE} (\n work_id, record_key, unique_key, kind, lane,\n major_order, minor_order, sort_one, sort_two,\n classification_entity_kind, classification_identity_key,\n cardinality_view, cardinality_occupied, cardinality_source_type_id,\n cardinality_source_primary_id, cardinality_link_id,\n cardinality_target_type_id, cardinality_target_primary_id, payload\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, json(?))\n `\n )\n this.db.run(\"SAVEPOINT sixb_ontology_stage_work\")\n let currentRecordKey: string | undefined\n try {\n for (const { record, uniqueKey, columns } of records) {\n currentRecordKey = record.recordKey\n const classification = record.kind === \"classification\" ? record : null\n const cardinality = record.kind === \"cardinality\" ? record : null\n insert.run(\n session.id,\n record.recordKey,\n uniqueKey,\n record.kind,\n columns.lane,\n columns.majorOrder,\n columns.minorOrder,\n columns.sortOne,\n columns.sortTwo,\n classification?.entityKind ?? null,\n classification?.identityKey ?? null,\n cardinality?.view ?? null,\n cardinality ? Number(cardinality.occupied) : null,\n cardinality?.ref.source.objectTypeId ?? null,\n cardinality?.ref.source.primaryId ?? null,\n cardinality?.ref.linkId ?? null,\n cardinality?.ref.target.objectTypeId ?? null,\n cardinality?.ref.target.primaryId ?? null,\n canonicalJson(record)\n )\n }\n this.db.run(\"RELEASE SAVEPOINT sixb_ontology_stage_work\")\n } catch (error) {\n this.db.run(\"ROLLBACK TO SAVEPOINT sixb_ontology_stage_work\")\n this.db.run(\"RELEASE SAVEPOINT sixb_ontology_stage_work\")\n if (isSqliteConstraintError(error)) {\n throw duplicateWork(currentRecordKey)\n }\n throw error\n }\n for (const prepared of records) recordSummary(session.summary, prepared.record)\n }\n\n /** Pages of one work lane in canonical order. */\n *lanePages<TLane extends WorkLane>(\n session: SqliteMaterializationSessionState,\n lane: TLane,\n pageRows: number\n ): Iterable<readonly LaneRecord[TLane][]> {\n let cursor: WorkCursor | null = null\n while (true) {\n this.require(session.publicSession())\n const rows = this.readLane(session, lane, cursor, pageRows)\n if (rows.length === 0) return\n cursor = workCursor(rows[rows.length - 1]!)\n yield rows.map((row) => parseJson<LaneRecord[TLane]>(row.payload))\n }\n }\n\n /** Staged object upserts and deletes of profiled types, or of objects with a stored vector. */\n *vectorChangePages(\n session: SqliteMaterializationSessionState,\n objectTypeIds: readonly string[],\n pageRows: number\n ): Iterable<readonly MaterializationVectorChange[]> {\n if (\n objectTypeIds.length === 0 &&\n !this.db\n .query(`SELECT 1 FROM object_vectors WHERE project_id = ? LIMIT 1`)\n .get(session.header.commit.projectId)\n ) {\n return\n }\n const query = this.db.query(\n `\n WITH changes AS (\n SELECT record_key, payload,\n coalesce(\n json_extract(payload, '$.item.value.row.ref.objectTypeId'),\n json_extract(payload, '$.item.value.ref.objectTypeId')\n ) AS object_type_id,\n coalesce(\n json_extract(payload, '$.item.value.row.ref.primaryId'),\n json_extract(payload, '$.item.value.ref.primaryId')\n ) AS primary_id\n FROM ${session.workTable}\n WHERE work_id = ? AND lane = 'apply' AND kind = 'plan'\n AND json_extract(payload, '$.item.kind') IN ('object-upsert', 'object-delete')\n AND record_key > ?\n )\n SELECT record_key, payload FROM changes\n WHERE object_type_id IN (SELECT value FROM json_each(?))\n OR EXISTS (\n SELECT 1 FROM object_vectors\n WHERE project_id = ? AND object_type_id = changes.object_type_id\n AND primary_id = changes.primary_id\n )\n ORDER BY record_key\n LIMIT ?\n `\n )\n let after = \"\"\n while (true) {\n this.require(session.publicSession())\n const rows = query.all(\n session.workId,\n after,\n JSON.stringify(objectTypeIds),\n session.header.commit.projectId,\n pageRows\n ) as { readonly record_key: string; readonly payload: string }[]\n if (rows.length === 0) return\n after = rows[rows.length - 1]!.record_key\n yield rows.map(\n (row) => parseJson<MaterializationPlanWorkRecord>(row.payload).item\n ) as MaterializationVectorChange[]\n }\n }\n\n projectionCounts(session: SqliteMaterializationSessionState): EffectiveChangeCounts {\n if (session.plan) return replacementPlanCounts(this.db, session.plan.versionId)\n const summary = session.summary\n return {\n objectsCreated: summary.objectsCreated,\n objectsUpdated: summary.objectsUpdated,\n objectsDeleted: summary.objectsDeleted,\n objectsUnchanged:\n summary.objectClassifications -\n summary.objectsCreated -\n summary.objectsUpdated -\n summary.objectsDeleted,\n linksCreated: summary.linksCreated,\n linksUpdated: summary.linksUpdated,\n linksDeleted: summary.linksDeleted,\n linksUnchanged:\n summary.linkClassifications -\n summary.linksCreated -\n summary.linksUpdated -\n summary.linksDeleted,\n }\n }\n\n telemetrySummary(session: SqliteMaterializationSessionState, pointCount: number) {\n const summary = session.summary\n return {\n classifiedPoints: summary.pointClassifications,\n counts: {\n pointsCreated: summary.pointsCreated,\n pointsUpdated: summary.pointsUpdated,\n pointsUnchanged: pointCount - summary.pointsCreated - summary.pointsUpdated,\n latestObjectsChanged: summary.latestObjectsChanged,\n },\n }\n }\n\n assertClassificationCoverage(session: SqliteMaterializationSessionState): void {\n if (session.plan) assertReplacementPlanCoverage(this.db, session.plan)\n }\n\n private readLane(\n session: SqliteMaterializationSessionState,\n lane: WorkLane,\n cursor: WorkCursor | null,\n limit: number\n ): WorkDatabaseRow[] {\n if (limit === 0) return []\n const selected = `record_key, major_order, minor_order, sort_one, sort_two, payload`\n if (!cursor) {\n return this.db\n .query(\n `SELECT ${selected} FROM ${session.workTable}\n WHERE work_id = ? AND lane = ?\n ORDER BY major_order, minor_order, sort_one, sort_two, record_key\n LIMIT ?`\n )\n .all(session.workId, lane, limit) as WorkDatabaseRow[]\n }\n return this.db\n .query(\n `SELECT ${selected} FROM ${session.workTable}\n WHERE work_id = ? AND lane = ?\n AND (major_order, minor_order, sort_one, sort_two, record_key) > (?, ?, ?, ?, ?)\n ORDER BY major_order, minor_order, sort_one, sort_two, record_key\n LIMIT ?`\n )\n .all(\n session.workId,\n lane,\n cursor.majorOrder,\n cursor.minorOrder,\n cursor.sortOne,\n cursor.sortTwo,\n cursor.recordKey,\n limit\n ) as WorkDatabaseRow[]\n }\n\n private ensureTables(): void {\n this.db.run(`\n CREATE TEMP TABLE IF NOT EXISTS ${SQLITE_MATERIALIZATION_WORK_TABLE} (\n work_id TEXT NOT NULL,\n record_key TEXT NOT NULL,\n unique_key TEXT NOT NULL,\n kind TEXT NOT NULL,\n lane TEXT NOT NULL,\n major_order INTEGER NOT NULL,\n minor_order INTEGER NOT NULL,\n sort_one TEXT NOT NULL,\n sort_two TEXT NOT NULL,\n classification_entity_kind TEXT,\n classification_identity_key TEXT,\n cardinality_view TEXT,\n cardinality_occupied INTEGER,\n cardinality_source_type_id TEXT,\n cardinality_source_primary_id TEXT,\n cardinality_link_id TEXT,\n cardinality_target_type_id TEXT,\n cardinality_target_primary_id TEXT,\n payload TEXT NOT NULL CHECK (json_valid(payload)),\n PRIMARY KEY (work_id, record_key),\n UNIQUE (work_id, unique_key)\n );\n CREATE INDEX IF NOT EXISTS idx_ontology_materialization_work_lane\n ON ${SQLITE_MATERIALIZATION_WORK_TABLE}(\n work_id, lane, major_order, minor_order, sort_one, sort_two, record_key\n );\n `)\n }\n\n private deleteWork(sessionId: string): void {\n this.db\n .query(`DELETE FROM ${SQLITE_MATERIALIZATION_WORK_TABLE} WHERE work_id = ?`)\n .run(sessionId)\n }\n\n private dropWorkTables(): void {\n this.db.run(`\n DROP TABLE IF EXISTS ${SQLITE_MATERIALIZATION_WORK_TABLE};\n `)\n }\n}\n\nfunction workCursor(row: WorkDatabaseRow): WorkCursor {\n return {\n majorOrder: row.major_order,\n minorOrder: row.minor_order,\n sortOne: row.sort_one,\n sortTwo: row.sort_two,\n recordKey: row.record_key,\n }\n}\n\nfunction emptyWorkSummary(): WorkSummary {\n return {\n objectClassifications: 0,\n linkClassifications: 0,\n pointClassifications: 0,\n objectsCreated: 0,\n objectsUpdated: 0,\n objectsDeleted: 0,\n linksCreated: 0,\n linksUpdated: 0,\n linksDeleted: 0,\n pointsCreated: 0,\n pointsUpdated: 0,\n latestObjectsChanged: 0,\n }\n}\n\nfunction recordSummary(summary: WorkSummary, record: MaterializationWorkRecord): void {\n if (record.kind === \"classification\") {\n if (record.entityKind === \"object\") summary.objectClassifications += 1\n if (record.entityKind === \"link\") summary.linkClassifications += 1\n if (record.entityKind === \"point\") summary.pointClassifications += 1\n return\n }\n if (record.kind !== \"plan\") return\n\n switch (record.item.kind) {\n case \"object-upsert\":\n summary.latestObjectsChanged += 1\n if (record.item.value.expected.exists) summary.objectsUpdated += 1\n else summary.objectsCreated += 1\n return\n case \"object-delete\":\n summary.objectsDeleted += 1\n return\n case \"link-upsert\":\n if (record.item.value.expected.exists) summary.linksUpdated += 1\n else summary.linksCreated += 1\n return\n case \"link-delete\":\n summary.linksDeleted += 1\n return\n case \"point-upsert\":\n if (record.item.value.expected.lastCommitId === null) summary.pointsCreated += 1\n else summary.pointsUpdated += 1\n return\n case \"object-override-upsert\":\n case \"object-override-delete\":\n case \"link-override-upsert\":\n case \"link-override-delete\":\n return\n }\n}\n",
53
58
  "import type { Database } from \"bun:sqlite\"\nimport type {\n EffectiveLinkSnapshot,\n EffectiveObjectSnapshot,\n OntologyLinkRef,\n OntologyObjectRef,\n ProjectionEntityRef,\n TelemetrySeriesRef,\n} from \"@sixb/core/internal/materialization\"\nimport {\n linkRefKey,\n linkScopeSortKey,\n MaterializationConflictError,\n objectRefKey,\n projectionEntityKey,\n telemetryPointSortKey,\n} from \"@sixb/core/internal/materialization\"\nimport {\n appendScopeSnapshot,\n finishScopeAccumulator,\n linkSlotOverrideValue,\n startScopeAccumulator,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type {\n MaterializationLinkScopeRevision,\n MaterializationLinkScopeState,\n MaterializationLinkState,\n MaterializationObjectState,\n SourceReplacementLinkState,\n SourceReplacementObjectState,\n StoredLinkOverride,\n StoredLinkSlotOverride,\n StoredObjectOverride,\n StoredSourceAssertion,\n StoredSourceLinkAssertion,\n StoredSourceObjectAssertion,\n StoredTelemetryPoint,\n} from \"@sixb/core/storage\"\nimport {\n canonicalJson,\n linkRefFromColumns,\n objectRefFromColumns,\n parseJson,\n type SqliteOntologySourceAssertionRow,\n type SqliteStoredOverrideRow,\n sourceAssertion,\n} from \"./shared\"\nimport {\n activeSourceRows,\n LIVE_SOURCE_ROWS_JOIN,\n replacementAssertionRows,\n SOURCE_ASSERTION_COLUMNS,\n} from \"./source-roots\"\n\nexport const SQLITE_MATERIALIZATION_WORK_TABLE = \"ontology_materialization_work\"\n\ninterface EffectiveObjectRow {\n readonly object_type_id: string\n readonly primary_id: string\n readonly properties: string\n readonly created_at: string\n readonly updated_at: string\n readonly version: number\n readonly last_commit_id: string | null\n}\n\ninterface EffectiveLinkRow {\n readonly source_type_id: string\n readonly source_id: string\n readonly link_id: string\n readonly target_type_id: string\n readonly target_id: string\n readonly properties: string | null\n readonly created_at: string\n readonly updated_at: string\n readonly last_commit_id: string | null\n}\n\ninterface TelemetryRow {\n readonly object_type_id: string\n readonly object_id: string\n readonly property_id: string\n readonly value: string\n readonly unit: string | null\n readonly at: string\n readonly last_commit_id: string | null\n}\n\ninterface LinkScopeRow extends EffectiveLinkRow {\n readonly scope_sort_key: string\n}\n\nfunction linkScopeRequestJson(\n scopes: readonly { readonly source: OntologyObjectRef; readonly linkId: string }[]\n): string {\n return canonicalJson(\n scopes.map(({ source, linkId }) => ({\n scopeSortKey: linkScopeSortKey(source, linkId),\n sourceTypeId: source.objectTypeId,\n sourceId: source.primaryId,\n linkId,\n }))\n )\n}\n\ninterface ObjectOverrideRow extends SqliteStoredOverrideRow {\n readonly object_type_id: string\n readonly primary_id: string\n readonly edited_at: string\n}\n\ninterface LinkOverrideRow extends SqliteStoredOverrideRow {\n readonly source_type_id: string\n readonly source_primary_id: string\n readonly link_id: string\n readonly target_type_id: string\n readonly target_primary_id: string\n}\n\ninterface LinkSlotOverrideRow {\n readonly source_type_id: string\n readonly source_primary_id: string\n readonly link_id: string\n readonly target_type_id: string\n readonly target_primary_id: string\n readonly value: string\n readonly last_commit_id: string\n readonly updated_at: string\n}\n\ninterface ReplacementSources {\n readonly owned: ReadonlySet<string>\n readonly byMaterialization: ReadonlyMap<string, ReadonlyMap<string, StoredSourceAssertion>>\n}\n\n/** A link a replacement plan decides, and whether its plan needs a diff. */\nexport interface ReplacementLinkIdentity {\n readonly ref: OntologyLinkRef\n readonly sortKey: string\n readonly diffRequired: boolean\n}\n\nexport class SqliteMaterializationStateReader {\n constructor(\n private readonly db: Database,\n readonly projectId: string\n ) {}\n\n objectState(ref: OntologyObjectRef): MaterializationObjectState {\n return this.objectStates([ref])[0]!\n }\n\n objectStates(refs: readonly OntologyObjectRef[]): readonly MaterializationObjectState[] {\n if (refs.length === 0) return []\n const requested = canonicalJson(\n refs.map((ref) => ({ objectTypeId: ref.objectTypeId, primaryId: ref.primaryId }))\n )\n const requestedObjects = `\n SELECT DISTINCT json_extract(value, '$.objectTypeId') AS object_type_id,\n json_extract(value, '$.primaryId') AS primary_id\n FROM json_each(?)\n `\n // Keep the JSON request set on the outer side of each lookup. SQLite cannot estimate the\n // cardinality of json_each() and otherwise scans every project row once per requested key.\n // CROSS JOIN deliberately fixes the loop order so the existing composite indexes are used.\n const effectiveRows = this.db\n .query(\n `WITH requested AS (${requestedObjects})\n SELECT objects.* FROM requested\n CROSS JOIN objects\n ON objects.project_id = ?\n AND objects.object_type_id = requested.object_type_id\n AND objects.primary_id = requested.primary_id`\n )\n .all(requested, this.projectId) as EffectiveObjectRow[]\n const sourceRows = activeSourceRows(\n this.db,\n this.projectId,\n refs.map((ref) => ({ kind: \"object\", ref }))\n )\n const overrideRows = this.db\n .query(\n `WITH requested AS (${requestedObjects})\n SELECT overrides.* FROM requested\n CROSS JOIN ontology_object_overrides AS overrides\n ON overrides.project_id = ?\n AND overrides.object_type_id = requested.object_type_id\n AND overrides.primary_id = requested.primary_id`\n )\n .all(requested, this.projectId) as ObjectOverrideRow[]\n const telemetryRows = this.db\n .query(\n `WITH requested AS (${requestedObjects}), ranked AS (\n SELECT timeseries.*,\n ROW_NUMBER() OVER (\n PARTITION BY timeseries.object_type_id, timeseries.object_id,\n timeseries.property_id\n ORDER BY timeseries.at DESC\n ) AS rank\n FROM requested\n CROSS JOIN timeseries\n ON timeseries.project_id = ?\n AND timeseries.object_type_id = requested.object_type_id\n AND timeseries.object_id = requested.primary_id\n )\n SELECT * FROM ranked WHERE rank = 1`\n )\n .all(requested, this.projectId) as TelemetryRow[]\n\n const effective = new Map(\n effectiveRows.map((row) => [objectRefKey(objectRefFromColumns(row)), row] as const)\n )\n const sources = activeSourceMap(sourceRows)\n const overrides = new Map(\n overrideRows.map(\n (row) => [objectRefKey(objectRefFromColumns(row)), storedObjectOverride(row)] as const\n )\n )\n const telemetry = new Map<string, StoredTelemetryPoint[]>()\n for (const row of telemetryRows) {\n const key = objectRefKey({ objectTypeId: row.object_type_id, primaryId: row.object_id })\n const points = telemetry.get(key) ?? []\n points.push(storedPoint(row))\n telemetry.set(key, points)\n }\n for (const points of telemetry.values()) {\n points.sort((left, right) =>\n telemetryPointSortKey(left.series, left.at).localeCompare(\n telemetryPointSortKey(right.series, right.at)\n )\n )\n }\n\n return refs.map((ref) => {\n const key = objectRefKey(ref)\n const effectiveRow = effective.get(key)\n return {\n ref: structuredClone(ref),\n source: sourceObject(sources.get(projectionEntityKey({ kind: \"object\", ref }))),\n override: overrides.get(key) ?? null,\n effective: effectiveRow ? effectiveObjectSnapshot(effectiveRow) : null,\n latestTelemetry: telemetry.get(key) ?? [],\n }\n })\n }\n\n linkState(ref: OntologyLinkRef): MaterializationLinkState {\n return this.linkStates([ref])[0]!\n }\n\n linkStates(refs: readonly OntologyLinkRef[]): readonly MaterializationLinkState[] {\n if (refs.length === 0) return []\n const requested = canonicalJson(\n refs.map((ref) => ({\n sourceTypeId: ref.source.objectTypeId,\n sourceId: ref.source.primaryId,\n linkId: ref.linkId,\n targetTypeId: ref.target.objectTypeId,\n targetId: ref.target.primaryId,\n }))\n )\n const effectiveRequest = `\n SELECT DISTINCT json_extract(value, '$.sourceTypeId') AS source_type_id,\n json_extract(value, '$.sourceId') AS source_id,\n json_extract(value, '$.linkId') AS link_id,\n json_extract(value, '$.targetTypeId') AS target_type_id,\n json_extract(value, '$.targetId') AS target_id\n FROM json_each(?)\n `\n const sourceRequest = `\n SELECT DISTINCT json_extract(value, '$.sourceTypeId') AS source_type_id,\n json_extract(value, '$.sourceId') AS source_primary_id,\n json_extract(value, '$.linkId') AS link_id,\n json_extract(value, '$.targetTypeId') AS target_type_id,\n json_extract(value, '$.targetId') AS target_primary_id\n FROM json_each(?)\n `\n const effectiveRows = this.db\n .query(\n `WITH requested AS (${effectiveRequest})\n SELECT links.* FROM requested\n CROSS JOIN links\n ON links.project_id = ?\n AND links.source_type_id = requested.source_type_id\n AND links.source_id = requested.source_id\n AND links.link_id = requested.link_id\n AND links.target_type_id = requested.target_type_id\n AND links.target_id = requested.target_id`\n )\n .all(requested, this.projectId) as EffectiveLinkRow[]\n const sourceRows = activeSourceRows(\n this.db,\n this.projectId,\n refs.map((ref) => ({ kind: \"link\", ref }))\n )\n const overrideRows = this.db\n .query(\n `WITH requested AS (${sourceRequest})\n SELECT overrides.* FROM requested\n CROSS JOIN ontology_link_overrides AS overrides\n ON overrides.project_id = ?\n AND overrides.identity_kind = 'edge'\n AND overrides.source_type_id = requested.source_type_id\n AND overrides.source_primary_id = requested.source_primary_id\n AND overrides.link_id = requested.link_id\n AND overrides.target_type_id = requested.target_type_id\n AND overrides.target_primary_id = requested.target_primary_id`\n )\n .all(requested, this.projectId) as LinkOverrideRow[]\n const slotOverrideRows = this.db\n .query(\n `WITH requested AS (${sourceRequest})\n SELECT overrides.* FROM requested\n CROSS JOIN ontology_link_overrides AS overrides\n ON overrides.project_id = ?\n AND overrides.identity_kind = 'slot'\n AND overrides.source_type_id = requested.source_type_id\n AND overrides.source_primary_id = requested.source_primary_id\n AND overrides.link_id = requested.link_id`\n )\n .all(requested, this.projectId) as LinkSlotOverrideRow[]\n const effective = new Map(\n effectiveRows.map((row) => [linkRefKey(linkRefFromColumns(row)), row] as const)\n )\n const sources = activeSourceMap(sourceRows)\n const overrides = new Map(\n overrideRows.map(\n (row) => [linkRefKey(linkRefFromOverrideColumns(row)), storedLinkOverride(row)] as const\n )\n )\n const slotOverrides = new Map(\n slotOverrideRows.map((row) => {\n const stored = storedLinkSlotOverride(row)\n return [linkScopeSortKey(stored.ref.source, stored.ref.linkId), stored] as const\n })\n )\n return refs.map((ref) => {\n const key = linkRefKey(ref)\n const effectiveRow = effective.get(key)\n return {\n ref: structuredClone(ref),\n source: sourceLink(sources.get(projectionEntityKey({ kind: \"link\", ref }))),\n override: overrides.get(key) ?? null,\n slotOverride: slotOverrides.get(linkScopeSortKey(ref.source, ref.linkId)) ?? null,\n effective: effectiveRow ? effectiveLinkSnapshot(effectiveRow) : null,\n }\n })\n }\n\n exactPoint(series: TelemetrySeriesRef, at: string): StoredTelemetryPoint | null {\n return this.exactPoints([{ series, at }])[0] ?? null\n }\n\n exactPoints(\n points: readonly { readonly series: TelemetrySeriesRef; readonly at: string }[]\n ): readonly StoredTelemetryPoint[] {\n if (points.length === 0) return []\n const requested = canonicalJson(\n points.map(({ series, at }) => ({\n objectTypeId: series.object.objectTypeId,\n objectId: series.object.primaryId,\n propertyId: series.propertyId,\n at,\n }))\n )\n const rows = this.db\n .query(\n `WITH requested AS (\n SELECT DISTINCT json_extract(value, '$.objectTypeId') AS object_type_id,\n json_extract(value, '$.objectId') AS object_id,\n json_extract(value, '$.propertyId') AS property_id,\n json_extract(value, '$.at') AS at\n FROM json_each(?)\n )\n SELECT timeseries.* FROM requested\n CROSS JOIN timeseries\n ON timeseries.project_id = ?\n AND timeseries.object_type_id = requested.object_type_id\n AND timeseries.object_id = requested.object_id\n AND timeseries.property_id = requested.property_id\n AND timeseries.at = requested.at`\n )\n .all(requested, this.projectId) as TelemetryRow[]\n const found = new Map(\n rows.map((row) => {\n const point = storedPoint(row)\n return [telemetryPointSortKey(point.series, point.at), point] as const\n })\n )\n return points.flatMap((point) => {\n const stored = found.get(telemetryPointSortKey(point.series, point.at))\n return stored ? [stored] : []\n })\n }\n\n linkScopeRevisions(\n scopes: readonly { readonly source: OntologyObjectRef; readonly linkId: string }[]\n ): readonly MaterializationLinkScopeRevision[] {\n if (scopes.length === 0) return []\n return this.readEffectiveLinkScopes(scopes, linkScopeRequestJson(scopes)).revisions\n }\n\n linkSlotStates(\n scopes: readonly { readonly source: OntologyObjectRef; readonly linkId: string }[]\n ): readonly MaterializationLinkScopeState[] {\n if (scopes.length === 0) return []\n const requestedJson = linkScopeRequestJson(scopes)\n const sourceRows = this.db\n .query(\n `WITH requested AS (\n SELECT DISTINCT\n json_extract(value, '$.sourceTypeId') AS source_type_id,\n json_extract(value, '$.sourceId') AS source_primary_id,\n json_extract(value, '$.linkId') AS link_id\n FROM json_each(?)\n )\n SELECT ${SOURCE_ASSERTION_COLUMNS} FROM requested\n CROSS JOIN ontology_source_rows AS rows\n ON rows.entity_kind = 'link'\n AND rows.source_type_id = requested.source_type_id\n AND rows.source_primary_id = requested.source_primary_id\n AND rows.link_id = requested.link_id\n ${LIVE_SOURCE_ROWS_JOIN}`\n )\n .all(requestedJson, this.projectId) as SqliteOntologySourceAssertionRow[]\n const slotOverrideRows = this.db\n .query(\n `WITH requested AS (\n SELECT DISTINCT\n json_extract(value, '$.sourceTypeId') AS source_type_id,\n json_extract(value, '$.sourceId') AS source_primary_id,\n json_extract(value, '$.linkId') AS link_id\n FROM json_each(?)\n )\n SELECT overrides.* FROM requested\n CROSS JOIN ontology_link_overrides AS overrides\n ON overrides.project_id = ?\n AND overrides.identity_kind = 'slot'\n AND overrides.source_type_id = requested.source_type_id\n AND overrides.source_primary_id = requested.source_primary_id\n AND overrides.link_id = requested.link_id`\n )\n .all(requestedJson, this.projectId) as LinkSlotOverrideRow[]\n const sources = activeScopeSourceMap(sourceRows)\n const overrides = new Map(\n slotOverrideRows.map((row) => {\n const stored = storedLinkSlotOverride(row)\n return [linkScopeSortKey(stored.ref.source, stored.ref.linkId), stored] as const\n })\n )\n const { revisions, effective } = this.readEffectiveLinkScopes(scopes, requestedJson)\n return scopes.map(({ source, linkId }, index) => {\n const key = linkScopeSortKey(source, linkId)\n return {\n ...revisions[index]!,\n sourceAssertion: sources.get(key) ?? null,\n override: overrides.get(key) ?? null,\n effective: effective.get(key) ?? null,\n }\n })\n }\n\n private readEffectiveLinkScopes(\n scopes: readonly { readonly source: OntologyObjectRef; readonly linkId: string }[],\n requestedJson: string\n ): {\n readonly revisions: readonly MaterializationLinkScopeRevision[]\n readonly effective: ReadonlyMap<string, EffectiveLinkSnapshot | null>\n } {\n const accumulators = new Map(\n scopes.map(({ source, linkId }) => {\n const key = linkScopeSortKey(source, linkId)\n return [key, startScopeAccumulator(source, linkId)] as const\n })\n )\n const effective = new Map<string, EffectiveLinkSnapshot | null>()\n const rows = this.db\n .query(\n `\n WITH requested AS (\n SELECT DISTINCT\n json_extract(value, '$.scopeSortKey') AS scope_sort_key,\n json_extract(value, '$.sourceTypeId') AS source_type_id,\n json_extract(value, '$.sourceId') AS source_id,\n json_extract(value, '$.linkId') AS link_id\n FROM json_each(?)\n )\n SELECT requested.scope_sort_key, links.*\n FROM requested\n CROSS JOIN links\n ON links.project_id = ?\n AND links.source_type_id = requested.source_type_id\n AND links.source_id = requested.source_id\n AND links.link_id = requested.link_id\n ORDER BY requested.scope_sort_key, ${linkSortExpression(\"links\")}\n `\n )\n .iterate(requestedJson, this.projectId) as Iterable<LinkScopeRow>\n for (const row of rows) {\n const accumulator = accumulators.get(row.scope_sort_key)\n if (!accumulator) {\n throw new MaterializationConflictError(\n \"effective-state\",\n `Unexpected link scope '${row.scope_sort_key}' returned by storage.`\n )\n }\n const snapshot = effectiveLinkSnapshot(row)\n appendScopeSnapshot(accumulator, snapshot)\n effective.set(row.scope_sort_key, accumulator.effectiveCount === 1 ? snapshot : null)\n }\n return {\n revisions: scopes.map(({ source, linkId }) =>\n finishScopeAccumulator(accumulators.get(linkScopeSortKey(source, linkId))!)\n ),\n effective,\n }\n }\n\n *incidentLinks(\n objects: readonly OntologyObjectRef[],\n pageRows: number\n ): Iterable<OntologyLinkRef[]> {\n if (objects.length === 0) return\n const values = objects.map(() => \"(?, ?)\").join(\", \")\n const args = objects.flatMap((ref) => [ref.objectTypeId, ref.primaryId])\n let cursor: string | null = null\n while (true) {\n const rows = this.db\n .query(\n `\n WITH requested(object_type_id, primary_id) AS (VALUES ${values}),\n authority_links AS (\n SELECT source_type_id, source_id, link_id, target_type_id, target_id\n FROM links WHERE project_id = ?\n UNION\n SELECT source_type_id, source_primary_id, link_id, target_type_id, target_primary_id\n FROM ontology_link_overrides\n WHERE project_id = ?\n UNION\n SELECT rows.source_type_id, rows.source_primary_id, rows.link_id,\n rows.target_type_id, rows.target_primary_id\n FROM ontology_source_rows AS rows\n ${LIVE_SOURCE_ROWS_JOIN}\n WHERE rows.entity_kind = 'link'\n ), selected AS (\n SELECT DISTINCT links.*,\n ${linkSortExpression(\"links\")} AS sort_key\n FROM authority_links AS links\n WHERE EXISTS (\n SELECT 1 FROM requested\n WHERE (requested.object_type_id = links.source_type_id\n AND requested.primary_id = links.source_id)\n OR (requested.object_type_id = links.target_type_id\n AND requested.primary_id = links.target_id)\n )\n )\n SELECT * FROM selected\n WHERE (? IS NULL OR sort_key > ?)\n ORDER BY sort_key\n LIMIT ?\n `\n )\n .all(\n ...args,\n this.projectId,\n this.projectId,\n this.projectId,\n cursor,\n cursor,\n pageRows\n ) as (EffectiveLinkRow & { readonly sort_key: string })[]\n if (rows.length === 0) break\n yield rows.map(linkRefFromColumns)\n cursor = rows[rows.length - 1]?.sort_key ?? null\n }\n }\n\n replacementObjectStates(\n sourceId: string,\n candidateMaterializationId: string,\n refs: readonly OntologyObjectRef[]\n ): readonly SourceReplacementObjectState[] {\n const base = this.objectStates(refs)\n const candidates = this.replacementSources(\n sourceId,\n [candidateMaterializationId],\n refs.map((ref) => ({ kind: \"object\" as const, ref }))\n )\n return base.map((state) => ({\n ref: state.ref,\n candidateSource: sourceObject(\n candidates.byMaterialization\n .get(candidateMaterializationId)\n ?.get(projectionEntityKey({ kind: \"object\", ref: state.ref }))\n ),\n override: state.override,\n effective: state.effective,\n latestTelemetry: state.latestTelemetry,\n }))\n }\n\n replacementLinkStates(\n sourceId: string,\n candidateMaterializationId: string,\n materializationIds: readonly string[],\n identities: readonly ReplacementLinkIdentity[],\n incremental = false\n ): readonly SourceReplacementLinkState[] {\n const refs = identities.map((identity) => identity.ref)\n const base = this.linkStates(refs)\n const replacements = this.replacementSources(\n sourceId,\n materializationIds,\n refs.map((ref) => ({ kind: \"link\" as const, ref })),\n incremental\n )\n const candidate = replacements.byMaterialization.get(candidateMaterializationId)\n return base.map((state, index) => {\n const key = projectionEntityKey({ kind: \"link\", ref: state.ref })\n return {\n ref: state.ref,\n candidateSource: replacements.owned.has(key)\n ? sourceLink(candidate?.get(key))\n : state.source,\n override: state.override,\n slotOverride: state.slotOverride,\n effective: state.effective,\n diffRequired: identities[index]!.diffRequired,\n }\n })\n }\n\n effectiveObjectRevision(ref: OntologyObjectRef): {\n readonly version: number\n readonly lastCommitId: string | null\n } | null {\n const row = this.db\n .query(\n `SELECT version, last_commit_id FROM objects\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?`\n )\n .get(this.projectId, ref.objectTypeId, ref.primaryId) as {\n readonly version: number\n readonly last_commit_id: string | null\n } | null\n return row ? { version: row.version, lastCommitId: row.last_commit_id } : null\n }\n\n effectiveLinkLastCommit(ref: OntologyLinkRef): string | null | undefined {\n const row = this.db\n .query(\n `\n SELECT last_commit_id FROM links\n WHERE project_id = ? AND source_type_id = ? AND source_id = ? AND link_id = ?\n AND target_type_id = ? AND target_id = ?\n `\n )\n .get(\n this.projectId,\n ref.source.objectTypeId,\n ref.source.primaryId,\n ref.linkId,\n ref.target.objectTypeId,\n ref.target.primaryId\n ) as { readonly last_commit_id: string | null } | null\n return row ? row.last_commit_id : undefined\n }\n\n private replacementSources(\n sourceId: string,\n materializationIds: readonly string[],\n refs: readonly ProjectionEntityRef[],\n incremental = false\n ): ReplacementSources {\n if (materializationIds.length === 0 || refs.length === 0) {\n return { owned: new Set(), byMaterialization: new Map() }\n }\n const rows = replacementAssertionRows(this.db, {\n projectId: this.projectId,\n sourceId,\n materializationId: materializationIds[0]!,\n incremental,\n includePrevious: materializationIds.length > 1,\n refs,\n })\n const owned = new Set<string>()\n const byMaterialization = new Map<string, Map<string, StoredSourceAssertion>>()\n for (const row of rows) {\n const source = storedSource(row)\n const key = projectionEntityKey(source.assertion)\n owned.add(key)\n const materialization = byMaterialization.get(row.materialization_id) ?? new Map()\n materialization.set(key, source)\n byMaterialization.set(row.materialization_id, materialization)\n }\n return { owned, byMaterialization }\n }\n}\n\nfunction activeSourceMap(\n rows: readonly SqliteOntologySourceAssertionRow[]\n): ReadonlyMap<string, StoredSourceAssertion> {\n const result = new Map<string, StoredSourceAssertion>()\n for (const row of rows) {\n const source = storedSource(row)\n const key = projectionEntityKey(source.assertion)\n if (result.has(key)) {\n throw new MaterializationConflictError(\n \"source-materialization\",\n `Multiple active sources assert ${key}.`\n )\n }\n result.set(key, source)\n }\n return result\n}\n\nfunction activeScopeSourceMap(\n rows: readonly SqliteOntologySourceAssertionRow[]\n): ReadonlyMap<string, StoredSourceLinkAssertion> {\n const result = new Map<string, StoredSourceLinkAssertion>()\n for (const row of rows) {\n const source = sourceLink(storedSource(row))\n if (!source) continue\n const ref = source.assertion.ref\n const key = linkScopeSortKey(ref.source, ref.linkId)\n if (result.has(key)) {\n throw new MaterializationConflictError(\n \"source-materialization\",\n `Multiple active sources assert cardinality-one link slot ${key}.`\n )\n }\n result.set(key, source)\n }\n return result\n}\n\nfunction sourceObject(\n source: StoredSourceAssertion | undefined\n): StoredSourceObjectAssertion | null {\n return source?.assertion.kind === \"object\" ? (source as StoredSourceObjectAssertion) : null\n}\n\nfunction sourceLink(source: StoredSourceAssertion | undefined): StoredSourceLinkAssertion | null {\n return source?.assertion.kind === \"link\" ? (source as StoredSourceLinkAssertion) : null\n}\n\nfunction storedObjectOverride(row: ObjectOverrideRow): StoredObjectOverride {\n const ref = objectRefFromColumns(row)\n return {\n ref,\n value: parseJson<StoredObjectOverride[\"value\"]>(row.value),\n editedAt: parseJson<Readonly<Record<string, string>>>(row.edited_at),\n lastCommitId: row.last_commit_id,\n updatedAt: row.updated_at,\n }\n}\n\nfunction storedLinkOverride(row: LinkOverrideRow): StoredLinkOverride {\n const ref = linkRefFromOverrideColumns(row)\n return {\n ref,\n value: parseJson<StoredLinkOverride[\"value\"]>(row.value),\n lastCommitId: row.last_commit_id,\n updatedAt: row.updated_at,\n }\n}\n\nfunction storedLinkSlotOverride(row: LinkSlotOverrideRow): StoredLinkSlotOverride {\n const ref = {\n source: { objectTypeId: row.source_type_id, primaryId: row.source_primary_id },\n linkId: row.link_id,\n }\n return {\n ref,\n value: linkSlotOverrideValue(parseJson<unknown>(row.value), linkScopeLabel(ref)),\n lastCommitId: row.last_commit_id,\n updatedAt: row.updated_at,\n }\n}\n\nfunction linkRefFromOverrideColumns(row: LinkOverrideRow): OntologyLinkRef {\n return {\n source: { objectTypeId: row.source_type_id, primaryId: row.source_primary_id },\n linkId: row.link_id,\n target: { objectTypeId: row.target_type_id, primaryId: row.target_primary_id },\n }\n}\n\nfunction linkScopeLabel(scope: {\n readonly source: OntologyObjectRef\n readonly linkId: string\n}): string {\n return JSON.stringify([scope.source.objectTypeId, scope.source.primaryId, scope.linkId])\n}\n\nfunction storedSource(row: SqliteOntologySourceAssertionRow): StoredSourceAssertion {\n return {\n source: { projectionId: row.source_id },\n materializationId: row.materialization_id,\n ...sourceAssertion(row),\n } as StoredSourceAssertion\n}\n\nfunction effectiveObjectSnapshot(row: EffectiveObjectRow): EffectiveObjectSnapshot {\n if (!row.last_commit_id) {\n throw new MaterializationConflictError(\n \"effective-state\",\n `Effective object ${row.object_type_id}:${row.primary_id} lacks materializer provenance.`\n )\n }\n return {\n ref: objectRefFromColumns(row),\n properties: parseJson<EffectiveObjectSnapshot[\"properties\"]>(row.properties),\n version: row.version,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n lastCommitId: row.last_commit_id,\n }\n}\n\nfunction effectiveLinkSnapshot(row: EffectiveLinkRow): EffectiveLinkSnapshot {\n if (!row.last_commit_id) {\n throw new MaterializationConflictError(\n \"effective-state\",\n `Effective link ${linkRefKey(linkRefFromColumns(row))} lacks materializer provenance.`\n )\n }\n return {\n ref: linkRefFromColumns(row),\n ...(row.properties === null\n ? {}\n : {\n properties: parseJson<NonNullable<EffectiveLinkSnapshot[\"properties\"]>>(row.properties),\n }),\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n lastCommitId: row.last_commit_id,\n }\n}\n\nfunction storedPoint(row: TelemetryRow): StoredTelemetryPoint {\n if (!row.last_commit_id) {\n throw new MaterializationConflictError(\n \"timeseries-point\",\n `Telemetry point ${telemetryPointSortKey(\n {\n object: { objectTypeId: row.object_type_id, primaryId: row.object_id },\n propertyId: row.property_id,\n },\n row.at\n )} lacks materializer provenance.`\n )\n }\n return {\n series: {\n object: { objectTypeId: row.object_type_id, primaryId: row.object_id },\n propertyId: row.property_id,\n },\n value: parseJson<StoredTelemetryPoint[\"value\"]>(row.value),\n ...(row.unit === null ? {} : { unit: row.unit }),\n at: row.at,\n lastCommitId: row.last_commit_id,\n }\n}\n\nexport function linkSortExpression(alias?: string): string {\n const prefix = alias ? `${alias}.` : \"\"\n return `LOWER(HEX(CAST(json_array(${prefix}source_type_id, ${prefix}source_id, ${prefix}link_id, ${prefix}target_type_id, ${prefix}target_id) AS BLOB)))`\n}\n",
54
59
  "import type { Database } from \"bun:sqlite\"\nimport type { ProjectionEntityRef } from \"@sixb/core/internal/materialization\"\nimport {\n MaterializationConflictError,\n MaterializationValidationError,\n projectionEntityKey,\n} from \"@sixb/core/internal/materialization\"\nimport {\n sourceEntityColumns,\n sourceStageRoots,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type { SourceActivationWrite, StageSourceRowsInput } from \"@sixb/core/storage\"\nimport type { SqliteOntologySourceAssertionRow } from \"./shared\"\nimport { canonicalJson, type SqliteOntologySourceRow } from \"./shared\"\n\n/**\n * Source storage in three levels: a version (`ontology_sources`, one per run), its roots (one per\n * logical dataset row, keyed by the canonical entity key) and their rows (what each root asserts).\n *\n * A root is live while its version is published (active or superseded), it is not retired and it\n * is not a deletion. Activation retires the live roots its candidate replaces and flips the\n * version; the candidate's own roots are never rewritten. One live root per source and key holds\n * because activation, under the source fence, retires every root the candidate replaces.\n */\nexport const PUBLISHED = \"('active', 'superseded')\"\n\n/** The columns `sourceAssertion` reads, over `versions`, `roots` and `rows`. */\nexport const SOURCE_ASSERTION_COLUMNS = `versions.source_id, versions.materialization_id,\n roots.root_key, roots.staging_ordinal, rows.entity_kind, rows.object_type_id, rows.primary_id,\n rows.source_type_id, rows.source_primary_id, rows.link_id, rows.target_type_id,\n rows.target_primary_id, rows.payload`\n\n/**\n * Keeps `rows` to those of live roots, joined as `roots` and `versions`; binds the project id.\n * CROSS JOIN keeps it a filter on the rows already selected: as a plain JOIN, SQLite may start\n * from every live root of the project instead.\n */\nexport const LIVE_SOURCE_ROWS_JOIN = `\n CROSS JOIN ontology_source_roots AS roots ON roots.id = rows.root_id\n AND roots.project_id = ? AND roots.retired_at IS NULL AND roots.deleted = 0\n CROSS JOIN ontology_sources AS versions ON versions.version_id = roots.version_id\n AND versions.status IN ${PUBLISHED}`\n\n/** The typed identity of `rows` equals the one requested (`IS` matches NULLs). */\nconst ENTITY_MATCH = `rows.entity_kind = requested.entity_kind\n AND rows.object_type_id IS requested.object_type_id\n AND rows.primary_id IS requested.primary_id\n AND rows.source_type_id IS requested.source_type_id\n AND rows.source_primary_id IS requested.source_primary_id\n AND rows.link_id IS requested.link_id\n AND rows.target_type_id IS requested.target_type_id\n AND rows.target_primary_id IS requested.target_primary_id`\n\nconst REQUESTED_ENTITY = `json_extract(value, '$.entityKind') AS entity_kind,\n json_extract(value, '$.objectTypeId') AS object_type_id,\n json_extract(value, '$.primaryId') AS primary_id,\n json_extract(value, '$.sourceTypeId') AS source_type_id,\n json_extract(value, '$.sourcePrimaryId') AS source_primary_id,\n json_extract(value, '$.linkId') AS link_id,\n json_extract(value, '$.targetTypeId') AS target_type_id,\n json_extract(value, '$.targetPrimaryId') AS target_primary_id`\n\n/** An entity's own key, and for a link the key of the object root that may assert it. */\nfunction requestedEntity(ref: ProjectionEntityRef) {\n const key = projectionEntityKey(ref)\n return {\n entityKind: ref.kind,\n ...sourceEntityColumns(ref),\n rootKeys:\n ref.kind === \"object\"\n ? [key]\n : [key, projectionEntityKey({ kind: \"object\", ref: ref.ref.source })],\n }\n}\n\nfunction sourceVersionId(\n db: Database,\n input: {\n readonly projectId: string\n readonly sourceId: string\n readonly materializationId: string\n }\n): number | null {\n const version = db\n .query(`SELECT version_id FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?`)\n .get(input.projectId, input.sourceId, input.materializationId) as {\n readonly version_id: number\n } | null\n return version?.version_id ?? null\n}\n\n/** The candidate's rows, plus the rows of the live roots it may replace. */\nexport function replacementSourceRows(\n db: Database,\n input: {\n readonly projectId: string\n readonly sourceId: string\n readonly materializationId: string\n readonly incremental: boolean\n }\n): { readonly sql: string; readonly values: readonly (string | number | null)[] } {\n const version = sourceVersionId(db, input)\n const live = `live.retired_at IS NULL AND live.deleted = 0\n AND versions.source_id = ? AND versions.status IN ${PUBLISHED}`\n const replaced = input.incremental\n ? `SELECT live.id FROM ontology_source_roots AS changed\n CROSS JOIN ontology_source_roots AS live\n ON live.project_id = ? AND live.root_key = changed.root_key\n CROSS JOIN ontology_sources AS versions ON versions.version_id = live.version_id\n WHERE changed.version_id = ? AND ${live}`\n : `SELECT live.id FROM ontology_sources AS versions\n CROSS JOIN ontology_source_roots AS live ON live.version_id = versions.version_id\n WHERE versions.project_id = ? AND ${live}`\n return {\n sql: `SELECT rows.* FROM ontology_source_roots AS roots\n CROSS JOIN ontology_source_rows AS rows ON rows.root_id = roots.id\n WHERE roots.version_id = ?\n UNION ALL\n SELECT rows.* FROM (${replaced}) AS roots\n CROSS JOIN ontology_source_rows AS rows ON rows.root_id = roots.id`,\n values: [version, input.projectId, ...(input.incremental ? [version] : []), input.sourceId],\n }\n}\n\nexport function stageSourceRoots(\n db: Database,\n manifest: SqliteOntologySourceRow,\n input: StageSourceRowsInput\n): void {\n const roots = sourceStageRoots(manifest.projection_kind, input)\n if (!manifest.base_materialization_id && roots.some((root) => root.deleted)) {\n throw new MaterializationValidationError(\"Root deletions require a source delta base.\")\n }\n const existing = db.query(`SELECT staging_ordinal, deleted FROM ontology_source_roots\n WHERE version_id = ? AND root_key = ?`)\n const insert = db.query(`INSERT INTO ontology_source_roots (\n version_id, project_id, root_key, staging_ordinal, deleted\n ) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING RETURNING id`)\n for (const root of roots) {\n const inserted = insert.get(\n manifest.version_id,\n input.projectId,\n root.rootKey,\n root.stagingOrdinal,\n Number(root.deleted)\n )\n if (inserted) continue\n const previous = existing.get(manifest.version_id, root.rootKey) as {\n staging_ordinal: number\n deleted: number\n } | null\n if (\n !previous ||\n previous.staging_ordinal !== root.stagingOrdinal ||\n Boolean(previous.deleted) !== root.deleted\n ) {\n throw new MaterializationValidationError(\n \"Source materialization repeats root or stream ordinal with different content.\"\n )\n }\n }\n}\n\n/**\n * Retires what the candidate replaces; its own roots go live when its version turns active. Every\n * link those roots assert changes its live source, which commit `commitId` records as touched.\n */\nexport function activateSourceRoots(\n db: Database,\n projectId: string,\n commitId: string,\n candidate: SqliteOntologySourceRow,\n activation: SourceActivationWrite\n): void {\n if (\n candidate.base_materialization_id !== null &&\n (candidate.base_materialization_id !== activation.expected.activeMaterializationId ||\n candidate.base_commit_id !== activation.expected.lastCommitId)\n )\n throw new MaterializationConflictError(\n \"projection-fence\",\n \"Source delta base changed before activation.\"\n )\n if (candidate.base_materialization_id !== null && candidate.root_count === 0) return\n const delta = candidate.base_materialization_id !== null\n const replaced = `retired_at IS NULL AND deleted = 0\n AND version_id IN (SELECT version_id FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND status IN ${PUBLISHED})\n ${\n delta\n ? `AND project_id = ? AND root_key IN (\n SELECT root_key FROM ontology_source_roots WHERE version_id = ?)`\n : \"\"\n }`\n const replacedParams = [\n projectId,\n activation.source.projectionId,\n ...(delta ? [projectId, candidate.version_id] : []),\n ]\n db.query(`INSERT INTO ontology_commit_touches (project_id, commit_id, entity_kind, identity_key)\n SELECT DISTINCT ?, ?, 'link', json_array(\n rows.source_type_id, rows.source_primary_id, rows.link_id, rows.target_type_id,\n rows.target_primary_id\n )\n FROM (\n SELECT id FROM ontology_source_roots WHERE ${replaced}\n UNION ALL\n SELECT id FROM ontology_source_roots WHERE version_id = ?\n ) AS changed\n CROSS JOIN ontology_source_rows AS rows ON rows.root_id = changed.id\n WHERE rows.entity_kind = 'link'`).run(\n projectId,\n commitId,\n ...replacedParams,\n candidate.version_id\n )\n db.query(`UPDATE ontology_source_roots SET retired_at = ? WHERE ${replaced}`).run(\n activation.updatedAt,\n ...replacedParams\n )\n // Deletions are never live; retiring them lets cleanup remove them with their version.\n db.query(`UPDATE ontology_source_roots SET retired_at = ?\n WHERE version_id = ? AND deleted = 1`).run(activation.updatedAt, candidate.version_id)\n}\n\nexport function assertSourceRootCoverage(db: Database, manifest: SqliteOntologySourceRow): void {\n const invalid = db\n .query(`SELECT 1 FROM ontology_source_roots AS roots\n WHERE roots.version_id = ?\n AND roots.deleted = EXISTS (\n SELECT 1 FROM ontology_source_rows AS rows WHERE rows.root_id = roots.id\n ) LIMIT 1`)\n .get(manifest.version_id)\n if (invalid)\n throw new MaterializationValidationError(\n \"Source roots must have complete assertions or an explicit deletion, never both.\"\n )\n}\n\n/** The live assertions of `refs`, whichever source asserts them. */\nexport function activeSourceRows(\n db: Database,\n projectId: string,\n refs: readonly ProjectionEntityRef[]\n): SqliteOntologySourceAssertionRow[] {\n const requested = refs.flatMap((ref) => {\n const { rootKeys, ...entity } = requestedEntity(ref)\n return rootKeys.map((rootKey) => ({ ...entity, rootKey }))\n })\n return db\n .query(`WITH requested AS (\n SELECT DISTINCT json_extract(value, '$.rootKey') AS root_key, ${REQUESTED_ENTITY}\n FROM json_each(?)\n ) SELECT ${SOURCE_ASSERTION_COLUMNS} FROM requested\n CROSS JOIN ontology_source_roots AS roots ON roots.project_id = ?\n AND roots.root_key = requested.root_key AND roots.retired_at IS NULL AND roots.deleted = 0\n CROSS JOIN ontology_sources AS versions ON versions.version_id = roots.version_id\n AND versions.status IN ${PUBLISHED}\n CROSS JOIN ontology_source_rows AS rows ON rows.root_id = roots.id AND ${ENTITY_MATCH}`)\n .all(canonicalJson(requested), projectId) as SqliteOntologySourceAssertionRow[]\n}\n\n/** The candidate's assertions of `refs`, and optionally the live ones they would replace. */\nexport function replacementAssertionRows(\n db: Database,\n input: {\n projectId: string\n sourceId: string\n materializationId: string\n incremental: boolean\n includePrevious: boolean\n refs: readonly ProjectionEntityRef[]\n }\n): SqliteOntologySourceAssertionRow[] {\n const version = sourceVersionId(db, input)\n const previous = !input.includePrevious\n ? \"\"\n : `UNION ALL\n SELECT ${SOURCE_ASSERTION_COLUMNS} FROM requested_entities AS requested\n CROSS JOIN ontology_source_roots AS roots ON roots.project_id = ?\n AND roots.root_key IN (SELECT value FROM json_each(requested.root_keys))\n AND roots.retired_at IS NULL AND roots.deleted = 0\n CROSS JOIN ontology_sources AS versions ON versions.version_id = roots.version_id\n AND versions.source_id = ? AND versions.status IN ${PUBLISHED}\n CROSS JOIN ontology_source_rows AS rows ON rows.root_id = roots.id AND ${ENTITY_MATCH}\n ${\n !input.incremental\n ? \"\"\n : `WHERE EXISTS (SELECT 1 FROM ontology_source_roots AS changed\n WHERE changed.version_id = ? AND changed.root_key = roots.root_key)`\n }`\n return db\n .query(`WITH requested_entities AS (\n SELECT DISTINCT ${REQUESTED_ENTITY}, json_extract(value, '$.rootKeys') AS root_keys\n FROM json_each(?)\n ) SELECT ${SOURCE_ASSERTION_COLUMNS} FROM requested_entities AS requested\n CROSS JOIN ontology_source_roots AS roots ON roots.version_id = ?\n AND roots.root_key IN (SELECT value FROM json_each(requested.root_keys))\n CROSS JOIN ontology_sources AS versions ON versions.version_id = roots.version_id\n CROSS JOIN ontology_source_rows AS rows ON rows.root_id = roots.id AND ${ENTITY_MATCH}\n ${previous}`)\n .all(\n canonicalJson(input.refs.map(requestedEntity)),\n version,\n ...(input.includePrevious\n ? [input.projectId, input.sourceId, ...(input.incremental ? [version] : [])]\n : [])\n ) as SqliteOntologySourceAssertionRow[]\n}\n",
55
60
  "import type { Database } from \"bun:sqlite\"\nimport {\n type EffectiveChangeCounts,\n MaterializationConflictError,\n MaterializationValidationError,\n type OntologyLinkRef,\n type OntologyObjectRef,\n objectRefKey,\n} from \"@sixb/core/internal/materialization\"\nimport {\n assertNonblank,\n assertPageRows,\n assertPositiveInteger,\n assertReplacementPlanCommit,\n canonicalJson,\n duplicateMaterializationWork,\n invalidCorrelation,\n materializationWorkColumns,\n prepareReplacementIdentities,\n workUniquenessKey,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type {\n MaterializationObjectExistence,\n OntologyCommitWrite,\n OntologyReplacementPlanStorage,\n OpenedReplacementPlan,\n OpenReplacementPlanInput,\n PurgeReplacementPlansInput,\n ReplacementPlanRef,\n ReplacementPlanStatePage,\n ReplacementPlanStatus,\n StageReplacementPlanInput,\n StreamReplacementPlanStateInput,\n} from \"@sixb/core/storage\"\nimport { SqliteMaterializationStateReader } from \"./materialization-state\"\nimport {\n assertProjectionExecution,\n isSqliteConstraintError,\n parseJson,\n type SqliteOntologySourceRow,\n type SqliteRootOperation,\n} from \"./shared\"\nimport { PUBLISHED, replacementSourceRows } from \"./source-roots\"\n\nexport const SQLITE_PLAN_WORK_TABLE = \"ontology_replacement_plan_work\"\n\n/** The plan a session applies: its work rows carry the candidate's source version as `work_id`. */\nexport interface SqliteReplacementPlan {\n readonly versionId: number\n readonly projectionKind: \"object\" | \"link\"\n}\n\ninterface PlanRow {\n readonly version_id: number\n readonly commit_id: string\n readonly committed_at: string\n readonly replaced_materialization_id: string | null\n readonly replaced_last_commit_id: string | null\n readonly watermark: number\n}\n\ninterface IdentityRow {\n readonly identity_key: string\n readonly sort_key: string\n readonly diff_required: number\n}\n\nconst IDENTITIES = \"ontology_replacement_plan_identities\"\n/** An identity's planning order: its key's UTF-8 bytes, as `objectRefSortKey`/`linkRefSortKey`. */\nconst SORT_KEY = \"LOWER(HEX(CAST(identity_key AS BLOB)))\"\n\n/**\n * The revision of an object identity: its effective row, its override and the latest point of each\n * telemetry property. `type` and `id` are SQL expressions; `$projectId` is bound.\n */\nfunction objectRevision(type: string, id: string): string {\n const series = (alias: string) =>\n `${alias}.project_id = $projectId AND ${alias}.object_type_id = ${type} AND ${alias}.object_id = ${id}`\n // One seek per property for its next name and one for its latest point: never the history.\n return `json_array(\n (SELECT json_array(version, last_commit_id) FROM objects\n WHERE project_id = $projectId AND object_type_id = ${type} AND primary_id = ${id}),\n (SELECT last_commit_id FROM ontology_object_overrides\n WHERE project_id = $projectId AND object_type_id = ${type} AND primary_id = ${id}),\n (WITH RECURSIVE properties(property_id) AS (\n SELECT MIN(first.property_id) FROM timeseries AS first WHERE ${series(\"first\")}\n UNION ALL\n SELECT (SELECT MIN(next.property_id) FROM timeseries AS next\n WHERE ${series(\"next\")} AND next.property_id > properties.property_id)\n FROM properties WHERE properties.property_id IS NOT NULL\n )\n SELECT json_group_array(json((\n SELECT json_array(points.property_id, points.at, points.last_commit_id)\n FROM timeseries AS points\n WHERE ${series(\"points\")} AND points.property_id = properties.property_id\n ORDER BY points.at DESC LIMIT 1\n ))) FROM properties WHERE properties.property_id IS NOT NULL)\n )`\n}\n\n/**\n * The revision of a link endpoint, which a link plan reads only for its existence. One this plan\n * decides exists as planned, which follows its whole object revision; any other exists as it is.\n * `$versionId` is bound.\n */\nfunction endpointRevision(type: string, id: string): string {\n return `CASE WHEN EXISTS (\n SELECT 1 FROM ${IDENTITIES} AS endpoint\n WHERE endpoint.version_id = $versionId AND endpoint.entity_kind = 'object'\n AND endpoint.identity_key = json_array(${type}, ${id})\n ) THEN ${objectRevision(type, id)}\n ELSE json(CASE WHEN EXISTS (\n SELECT 1 FROM objects\n WHERE project_id = $projectId AND object_type_id = ${type} AND primary_id = ${id}\n ) THEN 'true' ELSE 'false' END)\n END`\n}\n\n/**\n * The revision of a link identity, from its qualified key column `key`: its effective row, its\n * edge and slot overrides, the live source root asserting it, and the existence of both\n * endpoints. A live root that asserts a link is keyed by the link or by its source object.\n */\nfunction linkRevision(key: string): string {\n const part = (index: number) => `json_extract(${key}, '$[${index}]')`\n return `json_array(\n (SELECT last_commit_id FROM links\n WHERE project_id = $projectId AND source_type_id = ${part(0)} AND source_id = ${part(1)}\n AND link_id = ${part(2)} AND target_type_id = ${part(3)} AND target_id = ${part(4)}),\n (SELECT overrides.last_commit_id FROM ontology_link_overrides AS overrides\n WHERE overrides.project_id = $projectId AND overrides.identity_kind = 'edge'\n AND overrides.identity_key = ${key}),\n (SELECT overrides.last_commit_id FROM ontology_link_overrides AS overrides\n WHERE overrides.project_id = $projectId AND overrides.identity_kind = 'slot'\n AND overrides.identity_key = json_array(${part(0)}, ${part(1)}, ${part(2)})),\n (SELECT MAX(roots.id) FROM ontology_source_roots AS roots\n CROSS JOIN ontology_sources AS versions ON versions.version_id = roots.version_id\n AND versions.status IN ${PUBLISHED}\n WHERE roots.project_id = $projectId AND roots.retired_at IS NULL AND roots.deleted = 0\n AND roots.root_key IN (\n '[\"link\",' || substr(${key}, 2),\n '[\"object\",' || substr(json_array(${part(0)}, ${part(1)}), 2)\n )\n AND EXISTS (\n -- \\`+\\` keeps the lookup on the root's few rows, not on every row of a hub source.\n SELECT 1 FROM ontology_source_rows AS rows\n WHERE rows.root_id = roots.id AND +rows.entity_kind = 'link'\n AND +rows.source_type_id = ${part(0)} AND +rows.source_primary_id = ${part(1)}\n AND +rows.link_id = ${part(2)} AND +rows.target_type_id = ${part(3)}\n AND +rows.target_primary_id = ${part(4)}\n )),\n ${endpointRevision(part(0), part(1))},\n ${endpointRevision(part(3), part(4))}\n )`\n}\n\n/** The revision of the identity rows aliased `identities`. */\nexport function identityRevision(kind: \"object\" | \"link\"): string {\n const key = \"identities.identity_key\"\n return kind === \"object\"\n ? objectRevision(`json_extract(${key}, '$[0]')`, `json_extract(${key}, '$[1]')`)\n : linkRevision(key)\n}\n\n/** The keys of the links of `relation` (columns as `links`), and of both their endpoints. */\nfunction linkKeys(relation: string): string {\n return `SELECT json_array(source_type_id, source_id, link_id, target_type_id, target_id)\n AS identity_key, json_array(source_type_id, source_id) AS source_key,\n json_array(target_type_id, target_id) AS target_key\n FROM ${relation}`\n}\n\n/** The run of link expansion an identity added now waits for: the next one. */\nconst NEXT_EXPANSION = `(\n SELECT expansions FROM ontology_replacement_plans WHERE version_id = $versionId\n)`\n\n/**\n * Inserts the links of `incident_links` as identities that need a diff, or makes an existing\n * member need one; the next expansion starts from each of them.\n */\nconst INSERT_INCIDENT_LINKS = `\n INSERT INTO ${IDENTITIES} (\n version_id, entity_kind, identity_key, sort_key, diff_required, expand_at, source_key,\n target_key\n )\n SELECT $versionId, 'link', identity_key, ${SORT_KEY}, 1, ${NEXT_EXPANSION}, source_key,\n target_key\n FROM (${linkKeys(\"incident_links\")}) WHERE true\n ON CONFLICT (version_id, entity_kind, identity_key) DO UPDATE\n SET diff_required = 1, read_revision = NULL, planned_revision = NULL, classified = 0,\n change = NULL, expand_at = excluded.expand_at\n WHERE ${IDENTITIES}.diff_required = 0`\n\n/** Inserts the links of `members` as identities planned without a diff. */\nconst INSERT_MEMBER_LINKS = `\n INSERT INTO ${IDENTITIES} (\n version_id, entity_kind, identity_key, sort_key, diff_required, source_key, target_key\n )\n SELECT $versionId, 'link', identity_key, ${SORT_KEY}, 0, source_key, target_key\n FROM (${linkKeys(\"members\")}) WHERE true\n ON CONFLICT (version_id, entity_kind, identity_key) DO NOTHING`\n\n/** Live source rows of `$projectId`, as `rows`, joined from `rows` to their root and version. */\nconst LIVE_ROWS = `CROSS JOIN ontology_source_roots AS roots ON roots.id = rows.root_id\n AND roots.project_id = $projectId AND roots.retired_at IS NULL AND roots.deleted = 0\n CROSS JOIN ontology_sources AS versions ON versions.version_id = roots.version_id\n AND versions.status IN ${PUBLISHED}`\n\n/**\n * The statements of `expandLinks`, `$versionId` and `$projectId` bound. They start from the\n * identities planned or added since the previous expansion: purge keeps every touch a ready plan\n * needs, so what commits add later always comes from their touches. Incident objects drive the\n * loop and each side seeks its own index: without statistics, SQLite would search every link and\n * override of the project once per object.\n */\nexport const EXPAND_LINK_STATEMENTS = {\n incident: `WITH incident_objects AS MATERIALIZED (\n SELECT json_extract(work.payload, '$.ref.objectTypeId') AS object_type_id,\n json_extract(work.payload, '$.ref.primaryId') AS primary_id\n FROM ${IDENTITIES} AS objects\n CROSS JOIN ${SQLITE_PLAN_WORK_TABLE} AS work ON work.work_id = $versionId\n AND work.unique_key = 'incident-object:' || objects.identity_key\n WHERE objects.version_id = $versionId AND objects.entity_kind = 'object'\n AND objects.expand_at = ${NEXT_EXPANSION}\n ), incident_links AS (\n SELECT links.source_type_id, links.source_id, links.link_id,\n links.target_type_id, links.target_id\n FROM incident_objects CROSS JOIN links\n ON links.project_id = $projectId\n AND links.source_type_id = incident_objects.object_type_id\n AND links.source_id = incident_objects.primary_id\n UNION\n SELECT links.source_type_id, links.source_id, links.link_id,\n links.target_type_id, links.target_id\n FROM incident_objects CROSS JOIN links INDEXED BY idx_links_target\n ON links.project_id = $projectId\n AND links.target_type_id = incident_objects.object_type_id\n AND links.target_id = incident_objects.primary_id\n UNION\n SELECT overrides.source_type_id, overrides.source_primary_id, overrides.link_id,\n overrides.target_type_id, overrides.target_primary_id\n FROM incident_objects CROSS JOIN ontology_link_overrides AS overrides\n ON overrides.project_id = $projectId AND overrides.identity_kind IN ('edge', 'slot')\n AND overrides.source_type_id = incident_objects.object_type_id\n AND overrides.source_primary_id = incident_objects.primary_id\n UNION\n SELECT overrides.source_type_id, overrides.source_primary_id, overrides.link_id,\n overrides.target_type_id, overrides.target_primary_id\n FROM incident_objects\n CROSS JOIN ontology_link_overrides AS overrides INDEXED BY idx_ontology_link_overrides_target\n ON overrides.project_id = $projectId\n AND overrides.target_type_id = incident_objects.object_type_id\n AND overrides.target_primary_id = incident_objects.primary_id\n UNION\n SELECT rows.source_type_id, rows.source_primary_id, rows.link_id,\n rows.target_type_id, rows.target_primary_id\n FROM incident_objects CROSS JOIN ontology_source_rows AS rows\n ON rows.entity_kind = 'link'\n AND rows.source_type_id = incident_objects.object_type_id\n AND rows.source_primary_id = incident_objects.primary_id\n ${LIVE_ROWS}\n UNION\n SELECT rows.source_type_id, rows.source_primary_id, rows.link_id,\n rows.target_type_id, rows.target_primary_id\n FROM incident_objects CROSS JOIN ontology_source_rows AS rows\n ON rows.entity_kind = 'link'\n AND rows.target_type_id = incident_objects.object_type_id\n AND rows.target_primary_id = incident_objects.primary_id\n ${LIVE_ROWS}\n )\n ${INSERT_INCIDENT_LINKS}`,\n members: `WITH scopes AS (\n SELECT DISTINCT json_extract(identity_key, '$[0]') AS source_type_id,\n json_extract(identity_key, '$[1]') AS source_id,\n json_extract(identity_key, '$[2]') AS link_id\n FROM ${IDENTITIES}\n WHERE version_id = $versionId AND entity_kind = 'link' AND diff_required = 1\n AND expand_at = ${NEXT_EXPANSION}\n ), members AS (\n SELECT links.source_type_id, links.source_id, links.link_id,\n links.target_type_id, links.target_id\n FROM scopes CROSS JOIN links\n ON links.project_id = $projectId\n AND links.source_type_id = scopes.source_type_id\n AND links.source_id = scopes.source_id AND links.link_id = scopes.link_id\n UNION\n SELECT overrides.source_type_id, overrides.source_primary_id, overrides.link_id,\n overrides.target_type_id, overrides.target_primary_id\n FROM scopes CROSS JOIN ontology_link_overrides AS overrides\n ON overrides.project_id = $projectId AND overrides.identity_kind = 'slot'\n AND overrides.source_type_id = scopes.source_type_id\n AND overrides.source_primary_id = scopes.source_id\n AND overrides.link_id = scopes.link_id\n )\n ${INSERT_MEMBER_LINKS}`,\n}\n\n/**\n * What the commits since the watermark of plan `$versionId` touched in project `$projectId`.\n * `+project_id` keeps the lookup on the rowid range instead of the project's whole history.\n */\nconst TOUCHED = `touched AS MATERIALIZED (\n SELECT DISTINCT touches.entity_kind, touches.identity_key\n FROM ontology_commits AS commits\n CROSS JOIN ontology_commit_touches AS touches\n ON touches.project_id = commits.project_id AND touches.commit_id = commits.id\n WHERE commits.rowid > (\n SELECT watermark FROM ontology_replacement_plans WHERE version_id = $versionId\n ) AND +commits.project_id = $projectId\n)`\n\n/**\n * The statements of `refresh`, `$versionId` and `$projectId` bound: each unplans the identities of\n * one kind whose revision reads something the commits since the watermark touched, and changed.\n * An object reads its own row, override and telemetry; a link its row and edge override, its\n * scope's slot override, its live source assertion and its endpoints. A scope's links are found\n * from its source object.\n */\nexport const TOUCHED_REFRESH_STATEMENTS = {\n object: `WITH ${TOUCHED}\n UPDATE ${IDENTITIES} AS identities\n SET read_revision = NULL, planned_revision = NULL, classified = 0, change = NULL\n WHERE identities.version_id = $versionId AND identities.entity_kind = 'object'\n AND identities.identity_key IN (SELECT identity_key FROM touched WHERE entity_kind = 'object')\n AND identities.planned_revision IS NOT ${identityRevision(\"object\")}`,\n link: `WITH ${TOUCHED}, candidates AS (\n SELECT identity_key FROM touched WHERE entity_kind = 'link'\n UNION\n SELECT links.identity_key FROM touched CROSS JOIN ${IDENTITIES} AS links\n ON links.version_id = $versionId\n AND links.source_key = json_array(\n json_extract(touched.identity_key, '$[0]'), json_extract(touched.identity_key, '$[1]')\n )\n WHERE touched.entity_kind IN ('object', 'scope')\n UNION\n SELECT links.identity_key FROM touched CROSS JOIN ${IDENTITIES} AS links\n ON links.version_id = $versionId AND links.target_key = touched.identity_key\n WHERE touched.entity_kind = 'object'\n )\n UPDATE ${IDENTITIES} AS identities\n SET read_revision = NULL, planned_revision = NULL, classified = 0, change = NULL\n WHERE identities.version_id = $versionId AND identities.entity_kind = 'link'\n AND identities.identity_key IN (SELECT identity_key FROM candidates)\n AND identities.planned_revision IS NOT ${identityRevision(\"link\")}`,\n}\n\nconst TOUCHED_LINKS = `touched_links AS (\n SELECT identity_key, json_extract(identity_key, '$[0]') AS source_type_id,\n json_extract(identity_key, '$[1]') AS source_id, json_extract(identity_key, '$[2]') AS link_id,\n json_extract(identity_key, '$[3]') AS target_type_id,\n json_extract(identity_key, '$[4]') AS target_id\n FROM touched WHERE entity_kind = 'link'\n), slot_targets AS (\n SELECT overrides.source_type_id, overrides.source_primary_id AS source_id, overrides.link_id,\n overrides.target_type_id, overrides.target_primary_id AS target_id\n FROM touched CROSS JOIN ontology_link_overrides AS overrides\n ON overrides.project_id = $projectId AND overrides.identity_kind = 'slot'\n AND overrides.identity_key = touched.identity_key\n WHERE touched.entity_kind = 'scope'\n)`\n\nconst LINK_COLUMNS = \"source_type_id, source_id, link_id, target_type_id, target_id\"\n\nconst EFFECTIVE_TOUCHED_LINK = `EXISTS (\n SELECT 1 FROM links AS stored\n WHERE stored.project_id = $projectId AND stored.source_type_id = touched_links.source_type_id\n AND stored.source_id = touched_links.source_id AND stored.link_id = touched_links.link_id\n AND stored.target_type_id = touched_links.target_type_id\n AND stored.target_id = touched_links.target_id\n)`\n\n/**\n * The statements of `expandTouched`, `$versionId` and `$projectId` bound: the links `expandLinks`\n * would find, among those the commits since the watermark touched.\n */\nexport const EXPAND_TOUCHED_STATEMENTS = {\n incident: `WITH ${TOUCHED}, ${TOUCHED_LINKS}, incident_links AS (\n SELECT candidates.* FROM (\n SELECT ${LINK_COLUMNS} FROM touched_links\n WHERE ${EFFECTIVE_TOUCHED_LINK} OR EXISTS (\n SELECT 1 FROM ontology_link_overrides AS overrides\n WHERE overrides.project_id = $projectId AND overrides.identity_kind = 'edge'\n AND overrides.identity_key = touched_links.identity_key\n ) OR EXISTS (\n SELECT 1 FROM ontology_source_rows AS rows ${LIVE_ROWS}\n WHERE rows.entity_kind = 'link' AND rows.source_type_id = touched_links.source_type_id\n AND rows.source_primary_id = touched_links.source_id\n AND rows.link_id = touched_links.link_id\n AND rows.target_type_id = touched_links.target_type_id\n AND rows.target_primary_id = touched_links.target_id\n )\n UNION\n SELECT ${LINK_COLUMNS} FROM slot_targets\n ) AS candidates\n WHERE EXISTS (\n SELECT 1 FROM ${SQLITE_PLAN_WORK_TABLE} AS work\n WHERE work.work_id = $versionId AND work.unique_key IN (\n 'incident-object:' || json_array(candidates.source_type_id, candidates.source_id),\n 'incident-object:' || json_array(candidates.target_type_id, candidates.target_id)\n )\n )\n )\n ${INSERT_INCIDENT_LINKS}`,\n members: `WITH ${TOUCHED}, ${TOUCHED_LINKS}, members AS (\n SELECT candidates.* FROM (\n SELECT ${LINK_COLUMNS} FROM touched_links WHERE ${EFFECTIVE_TOUCHED_LINK}\n UNION\n SELECT ${LINK_COLUMNS} FROM slot_targets\n ) AS candidates\n WHERE EXISTS (\n SELECT 1 FROM ${IDENTITIES} AS changed\n WHERE changed.version_id = $versionId\n AND changed.source_key = json_array(candidates.source_type_id, candidates.source_id)\n AND changed.diff_required = 1\n AND json_extract(changed.identity_key, '$[2]') = candidates.link_id\n )\n )\n ${INSERT_MEMBER_LINKS}`,\n}\n\n/**\n * Deletes up to `$limit` touches of `$projectId` that every ready plan's watermark has seen, or\n * all its touches when no plan is ready.\n */\nconst PURGE_TOUCHES_STATEMENT = `DELETE FROM ontology_commit_touches WHERE rowid IN (\n SELECT touches.rowid FROM ontology_commit_touches AS touches\n CROSS JOIN ontology_commits AS commits\n ON commits.project_id = touches.project_id AND commits.id = touches.commit_id\n WHERE touches.project_id = $projectId AND commits.rowid <= COALESCE(\n (SELECT MIN(plans.watermark) FROM ontology_replacement_plans AS plans\n JOIN ontology_sources AS versions USING (version_id)\n WHERE plans.project_id = $projectId AND versions.status = 'ready'),\n (SELECT COALESCE(MAX(rowid), 0) FROM ontology_commits)\n )\n LIMIT $limit\n)`\n\nexport class SqliteOntologyReplacementPlanStorage implements OntologyReplacementPlanStorage {\n constructor(\n private readonly db: Database,\n private readonly runRootOperation: SqliteRootOperation\n ) {}\n\n async open(input: OpenReplacementPlanInput): Promise<OpenedReplacementPlan> {\n return this.runRootOperation(() => {\n const { commit } = input\n assertReplacementPlanCommit(commit)\n const candidate = this.requireCandidate(input)\n const active = this.db\n .query(\n `SELECT materialization_id, last_commit_id FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND status = 'active'`\n )\n .get(input.projectId, input.source.projectionId) as {\n readonly materialization_id: string\n readonly last_commit_id: string | null\n } | null\n const replacedMaterializationId = active?.materialization_id ?? null\n const replacedLastCommitId = active?.last_commit_id ?? null\n const existing = planRow(this.db, candidate.version_id)\n // A plan decides the entities of the source it replaces: once that moved, it starts over.\n if (\n existing?.replaced_materialization_id === replacedMaterializationId &&\n existing.replaced_last_commit_id === replacedLastCommitId\n ) {\n return { committedAt: existing.committed_at }\n }\n if (existing) deletePlan(this.db, candidate.version_id)\n this.db\n .query(\n `INSERT INTO ontology_replacement_plans (\n version_id, project_id, commit_id, committed_at, replaced_materialization_id,\n replaced_last_commit_id, watermark\n ) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(rowid), 0) FROM ontology_commits))`\n )\n .run(\n candidate.version_id,\n input.projectId,\n commit.id,\n commit.committedAt,\n replacedMaterializationId,\n replacedLastCommitId\n )\n const rows = replacementSourceRows(this.db, {\n projectId: input.projectId,\n sourceId: input.source.projectionId,\n materializationId: input.materializationId,\n incremental: candidate.base_materialization_id !== null,\n })\n // Every entity of the candidate and of the roots it replaces needs a diff.\n this.db\n .query(\n `INSERT INTO ${IDENTITIES} (\n version_id, entity_kind, identity_key, sort_key, diff_required, expand_at,\n source_key, target_key\n )\n SELECT ?, entity_kind, identity_key, ${SORT_KEY}, 1,\n CASE entity_kind WHEN 'link' THEN 0 END, source_key, target_key\n FROM (\n SELECT entity_kind, CASE entity_kind\n WHEN 'object' THEN json_array(object_type_id, primary_id)\n ELSE json_array(\n source_type_id, source_primary_id, link_id, target_type_id, target_primary_id\n )\n END AS identity_key,\n CASE entity_kind\n WHEN 'link' THEN json_array(source_type_id, source_primary_id)\n END AS source_key,\n CASE entity_kind\n WHEN 'link' THEN json_array(target_type_id, target_primary_id)\n END AS target_key\n FROM (${rows.sql}) AS rows\n )\n GROUP BY entity_kind, identity_key`\n )\n .run(candidate.version_id, ...rows.values)\n return { committedAt: commit.committedAt }\n })\n }\n\n async *streamState(\n input: StreamReplacementPlanStateInput\n ): AsyncIterable<ReplacementPlanStatePage> {\n assertPageRows(input.pageRows)\n await this.runRootOperation(() => {\n const { candidate } = this.requirePlan(input)\n if (input.entityKind === \"object\" && candidate.projection_kind !== \"object\") {\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"Link projection replacement cannot stream object state.\"\n )\n }\n if (input.entityKind === \"link\") {\n if (unplannedCount(this.db, candidate.version_id, \"object\") > 0) {\n throw new MaterializationConflictError(\n \"effective-state\",\n \"Object projection replacement must plan every object before its links.\"\n )\n }\n this.expandLinks(candidate.version_id, input.projectId)\n }\n })\n let after = \"\"\n while (true) {\n const page = await this.runRootOperation(() => {\n const { candidate } = this.requirePlan(input)\n const rows = this.db\n .query(\n `SELECT identity_key, sort_key, diff_required FROM ${IDENTITIES}\n WHERE version_id = ? AND entity_kind = ? AND planned_revision IS NULL AND sort_key > ?\n ORDER BY sort_key\n LIMIT ?`\n )\n .all(candidate.version_id, input.entityKind, after, input.pageRows) as IdentityRow[]\n if (rows.length === 0) return null\n after = rows[rows.length - 1]!.sort_key\n const state = this.readPage(input, candidate, rows)\n this.db\n .query(\n `UPDATE ${IDENTITIES} AS identities SET read_revision = ${identityRevision(input.entityKind)}\n WHERE identities.version_id = $versionId AND identities.entity_kind = $entityKind\n AND identities.identity_key IN (SELECT value FROM json_each($keys))`\n )\n .run({\n $projectId: input.projectId,\n $versionId: candidate.version_id,\n $entityKind: input.entityKind,\n $keys: JSON.stringify(rows.map((row) => row.identity_key)),\n })\n return state\n })\n if (!page) return\n yield page\n }\n }\n\n async stage(input: StageReplacementPlanInput): Promise<void> {\n await this.runRootOperation(() => {\n const { plan, candidate } = this.requirePlan(input)\n const identities = prepareReplacementIdentities(input, {\n commitId: plan.commit_id,\n committedAt: plan.committed_at,\n })\n const versionId = candidate.version_id\n this.db.run(\"SAVEPOINT sixb_replacement_plan_stage\")\n let recordKey: string | undefined\n try {\n // Only an identity streamed and still to plan has the revision its work is planned\n // from, and holds no work: unplanning one deletes its work and forgets what it read.\n const known = this.db.query(\n `SELECT read_revision, planned_revision FROM ${IDENTITIES}\n WHERE version_id = ? AND entity_kind = ? AND identity_key = ?`\n )\n const insert = this.db.query(\n `INSERT INTO ${SQLITE_PLAN_WORK_TABLE} (\n work_id, entity_kind, identity_key, record_key, unique_key, kind, lane,\n major_order, minor_order, sort_one, sort_two,\n classification_entity_kind, classification_identity_key,\n cardinality_view, cardinality_occupied, cardinality_source_type_id,\n cardinality_source_primary_id, cardinality_link_id,\n cardinality_target_type_id, cardinality_target_primary_id, payload\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, json(?))`\n )\n // A planned object may flip its existence: the next link expansion starts from it.\n const planned = this.db.query(\n `UPDATE ${IDENTITIES}\n SET planned_revision = read_revision, classified = ?, change = ?,\n expand_at = CASE entity_kind\n WHEN 'object' THEN (\n SELECT expansions FROM ontology_replacement_plans WHERE version_id = ?\n )\n ELSE expand_at\n END\n WHERE version_id = ? AND entity_kind = ? AND identity_key = ?`\n )\n for (const identity of identities) {\n const row = known.get(versionId, identity.kind, identity.key) as {\n readonly read_revision: string | null\n readonly planned_revision: string | null\n } | null\n if (row?.read_revision == null || row.planned_revision !== null) {\n throw new MaterializationValidationError(\n `Replacement identity ${identity.entityKey} is not streamed and still to plan.`\n )\n }\n for (const record of identity.records) {\n recordKey = record.recordKey\n const columns = materializationWorkColumns(record)\n const classification = record.kind === \"classification\" ? record : null\n const cardinality = record.kind === \"cardinality\" ? record : null\n insert.run(\n versionId,\n identity.kind,\n identity.key,\n record.recordKey,\n workUniquenessKey(record),\n record.kind,\n columns.lane,\n columns.majorOrder,\n columns.minorOrder,\n columns.sortOne,\n columns.sortTwo,\n classification?.entityKind ?? null,\n classification?.identityKey ?? null,\n cardinality?.view ?? null,\n cardinality ? Number(cardinality.occupied) : null,\n cardinality?.ref.source.objectTypeId ?? null,\n cardinality?.ref.source.primaryId ?? null,\n cardinality?.ref.linkId ?? null,\n cardinality?.ref.target.objectTypeId ?? null,\n cardinality?.ref.target.primaryId ?? null,\n canonicalJson(record)\n )\n }\n planned.run(\n Number(identity.classified),\n identity.change,\n versionId,\n versionId,\n identity.kind,\n identity.key\n )\n }\n this.db.run(\"RELEASE SAVEPOINT sixb_replacement_plan_stage\")\n } catch (error) {\n this.db.run(\"ROLLBACK TO SAVEPOINT sixb_replacement_plan_stage\")\n this.db.run(\"RELEASE SAVEPOINT sixb_replacement_plan_stage\")\n if (isSqliteConstraintError(error)) throw duplicateMaterializationWork(recordKey)\n throw error\n }\n })\n }\n\n async refresh(input: ReplacementPlanRef): Promise<ReplacementPlanStatus> {\n return this.runRootOperation(() => {\n const { plan, candidate } = this.requirePlan(input)\n const versionId = candidate.version_id\n const pending = unplannedCount(this.db, versionId)\n if (pending > 0) return { fresh: false, unplanned: pending }\n if (!committedSince(this.db, plan, input.projectId)) {\n return { fresh: true, counts: replacementPlanCounts(this.db, versionId) }\n }\n // Purge keeps every touch past the watermark of a ready plan: only touched identities can\n // have changed.\n const params = { $projectId: input.projectId, $versionId: versionId }\n let unplanned = 0\n for (const kind of [\"object\", \"link\"] as const) {\n const stale = this.db.query(TOUCHED_REFRESH_STATEMENTS[kind]).run(params).changes\n if (stale === 0) continue\n dropUnplannedWork(this.db, versionId, kind)\n unplanned += stale\n }\n unplanned += this.expandTouched(versionId, input.projectId)\n this.db\n .query(\n `UPDATE ontology_replacement_plans\n SET watermark = (SELECT COALESCE(MAX(rowid), 0) FROM ontology_commits)\n WHERE version_id = ?`\n )\n .run(versionId)\n if (unplanned > 0) return { fresh: false, unplanned }\n return { fresh: true, counts: replacementPlanCounts(this.db, versionId) }\n })\n }\n\n async purge(input: PurgeReplacementPlansInput): Promise<number> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Replacement plan purge project id\")\n assertPositiveInteger(input.limit, \"Replacement plan purge limit\")\n const spentPlan = this.db.query(\n `SELECT plans.version_id FROM ontology_replacement_plans AS plans\n JOIN ontology_sources AS versions USING (version_id)\n WHERE plans.project_id = ? AND versions.status <> 'ready'\n ORDER BY plans.version_id\n LIMIT 1`\n )\n let deleted = 0\n // A plan's row goes last, so a plan whose rows outlast the budget is found again next time.\n while (deleted < input.limit) {\n const spent = spentPlan.get(input.projectId) as { readonly version_id: number } | null\n if (!spent) break\n for (const [table, column] of [\n [SQLITE_PLAN_WORK_TABLE, \"work_id\"],\n [IDENTITIES, \"version_id\"],\n ] as const) {\n deleted += this.db\n .query(\n `DELETE FROM ${table} WHERE rowid IN (\n SELECT rowid FROM ${table} WHERE ${column} = ? LIMIT ?\n )`\n )\n .run(spent.version_id, input.limit - deleted).changes\n if (deleted >= input.limit) return deleted\n }\n this.db\n .query(`DELETE FROM ontology_replacement_plans WHERE version_id = ?`)\n .run(spent.version_id)\n deleted += 1\n }\n if (deleted >= input.limit) return deleted\n // Every write holds the store's lock: a plan that opens later has seen all these commits.\n return (\n deleted +\n this.db\n .query(PURGE_TOUCHES_STATEMENT)\n .run({ $projectId: input.projectId, $limit: input.limit - deleted }).changes\n )\n })\n }\n\n private readPage(\n input: StreamReplacementPlanStateInput,\n candidate: SqliteOntologySourceRow,\n rows: readonly IdentityRow[]\n ): ReplacementPlanStatePage {\n const reader = new SqliteMaterializationStateReader(this.db, input.projectId)\n if (input.entityKind === \"object\") {\n const refs = rows.map((row) => {\n const [objectTypeId, primaryId] = parseJson<string[]>(row.identity_key)\n return { objectTypeId: objectTypeId!, primaryId: primaryId! }\n })\n return {\n objects: reader.replacementObjectStates(\n input.source.projectionId,\n input.materializationId,\n refs\n ),\n links: [],\n endpoints: [],\n }\n }\n const identities = rows.map((row) => {\n const parts = parseJson<string[]>(row.identity_key)\n const ref: OntologyLinkRef = {\n source: { objectTypeId: parts[0]!, primaryId: parts[1]! },\n linkId: parts[2]!,\n target: { objectTypeId: parts[3]!, primaryId: parts[4]! },\n }\n return {\n ref,\n sortKey: row.sort_key,\n diffRequired: row.diff_required === 1,\n }\n })\n const previous = this.db\n .query(\n `SELECT materialization_id FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND status = 'active'`\n )\n .get(input.projectId, input.source.projectionId) as {\n readonly materialization_id: string\n } | null\n const links = reader.replacementLinkStates(\n input.source.projectionId,\n input.materializationId,\n [input.materializationId, ...(previous ? [previous.materialization_id] : [])],\n identities,\n candidate.base_materialization_id !== null\n )\n return {\n objects: [],\n links,\n endpoints: this.endpoints(\n candidate.version_id,\n input.projectId,\n identities.flatMap(({ ref }) => [ref.source, ref.target])\n ),\n }\n }\n\n /** Planned existence where the plan decides an endpoint, effective existence elsewhere. */\n private endpoints(\n versionId: number,\n projectId: string,\n refs: readonly OntologyObjectRef[]\n ): MaterializationObjectExistence[] {\n const unique = [...new Map(refs.map((ref) => [objectRefKey(ref), ref] as const)).values()]\n const rows = this.db\n .query(\n `SELECT requested.value AS identity_key, (\n SELECT json_extract(work.payload, '$.exists') FROM ${SQLITE_PLAN_WORK_TABLE} AS work\n WHERE work.work_id = ? AND work.unique_key = 'object-existence:' || requested.value\n ) AS planned, EXISTS (\n SELECT 1 FROM objects\n WHERE project_id = ? AND object_type_id = json_extract(requested.value, '$[0]')\n AND primary_id = json_extract(requested.value, '$[1]')\n ) AS effective\n FROM json_each(?) AS requested`\n )\n .all(versionId, projectId, JSON.stringify(unique.map((ref) => objectRefKey(ref)))) as {\n readonly identity_key: string\n readonly planned: number | null\n readonly effective: number\n }[]\n const existence = new Map(\n rows.map((row) => [row.identity_key, (row.planned ?? row.effective) === 1] as const)\n )\n return unique.map((ref) => ({ ref, exists: existence.get(objectRefKey(ref)) ?? false }))\n }\n\n /**\n * Adds the links the plan must decide besides its own: those incident to an object it flips,\n * and every member of a scope it changes, from the identities planned or added since the\n * previous expansion. Returns how many identities this left to plan, counting an existing member\n * that now needs a diff. What commits add later is found from their touches by `expandTouched`.\n */\n private expandLinks(versionId: number, projectId: string): number {\n const added = this.expand(versionId, projectId, EXPAND_LINK_STATEMENTS)\n this.db\n .query(\n `UPDATE ontology_replacement_plans SET expansions = expansions + 1 WHERE version_id = ?`\n )\n .run(versionId)\n return added\n }\n\n /**\n * Adds the links commits brought within the plan's reach, from what they touched: a link that\n * now exists incident to an object the plan flips, or in a scope a planned link changes.\n */\n private expandTouched(versionId: number, projectId: string): number {\n return this.expand(versionId, projectId, EXPAND_TOUCHED_STATEMENTS)\n }\n\n private expand(\n versionId: number,\n projectId: string,\n statements: { readonly incident: string; readonly members: string }\n ): number {\n const run = (statement: string) =>\n this.db.query(statement).run({ $projectId: projectId, $versionId: versionId }).changes\n const diffLinks = run(statements.incident)\n // An upgraded member planned without a diff keeps no work from before.\n if (diffLinks > 0) dropUnplannedWork(this.db, versionId, \"link\")\n return diffLinks + run(statements.members)\n }\n\n private requireCandidate(input: ReplacementPlanRef): SqliteOntologySourceRow {\n const candidate = sourceRow(\n this.db,\n input.projectId,\n input.source.projectionId,\n input.materializationId\n )\n if (\n !candidate ||\n candidate.status !== \"ready\" ||\n candidate.projection_run_id !== input.execution.projectionRunId ||\n candidate.execution_token !== input.execution.executionToken\n ) {\n throw new MaterializationConflictError(\n \"source-materialization\",\n `Candidate source materialization '${input.materializationId}' is missing, not ready, or owned by another execution.`\n )\n }\n assertProjectionExecution(this.db, {\n projectId: input.projectId,\n sourceId: input.source.projectionId,\n projectionRunId: input.execution.projectionRunId,\n executionToken: input.execution.executionToken,\n })\n return candidate\n }\n\n private requirePlan(input: ReplacementPlanRef): {\n readonly plan: PlanRow\n readonly candidate: SqliteOntologySourceRow\n } {\n const candidate = this.requireCandidate(input)\n const plan = planRow(this.db, candidate.version_id)\n if (!plan) {\n throw new MaterializationConflictError(\n \"source-materialization\",\n `Candidate source materialization '${input.materializationId}' has no open plan.`\n )\n }\n return { plan, candidate }\n }\n}\n\n/**\n * Every identity the plan decides with a diff is classified, and nothing else is. Staging records\n * whether an identity's work holds its classification, so this reads identities only.\n */\nexport function assertReplacementPlanCoverage(db: Database, plan: SqliteReplacementPlan): void {\n const mismatch = db\n .query(\n `SELECT 1 FROM ${IDENTITIES}\n WHERE version_id = ?\n AND classified <> (diff_required AND (entity_kind = 'link' OR ? = 1))\n LIMIT 1`\n )\n .get(plan.versionId, plan.projectionKind === \"object\" ? 1 : 0)\n if (mismatch) {\n invalidCorrelation(\"Projection replacement classification coverage does not match its plan.\")\n }\n}\n\n/** The change counts of a plan, from what its identities planned. */\nexport function replacementPlanCounts(db: Database, versionId: number): EffectiveChangeCounts {\n const rows = db\n .query(\n `SELECT entity_kind, COALESCE(change, 'unchanged') AS change, COUNT(*) AS count\n FROM ${IDENTITIES}\n WHERE version_id = ? AND classified = 1\n GROUP BY entity_kind, COALESCE(change, 'unchanged')`\n )\n .all(versionId) as {\n readonly entity_kind: \"object\" | \"link\"\n readonly change: \"created\" | \"updated\" | \"deleted\" | \"unchanged\"\n readonly count: number\n }[]\n const count = (kind: \"object\" | \"link\", change: string) =>\n rows.find((row) => row.entity_kind === kind && row.change === change)?.count ?? 0\n return {\n objectsCreated: count(\"object\", \"created\"),\n objectsUpdated: count(\"object\", \"updated\"),\n objectsDeleted: count(\"object\", \"deleted\"),\n objectsUnchanged: count(\"object\", \"unchanged\"),\n linksCreated: count(\"link\", \"created\"),\n linksUpdated: count(\"link\", \"updated\"),\n linksDeleted: count(\"link\", \"deleted\"),\n linksUnchanged: count(\"link\", \"unchanged\"),\n }\n}\n\nfunction unplannedCount(db: Database, versionId: number, kind?: \"object\" | \"link\"): number {\n const row = db\n .query(\n `SELECT COUNT(*) AS count FROM ${IDENTITIES}\n WHERE version_id = ? AND planned_revision IS NULL AND (? IS NULL OR entity_kind = ?)`\n )\n .get(versionId, kind ?? null, kind ?? null) as { readonly count: number }\n return row.count\n}\n\n/**\n * Whether a commit of the project landed after the plan's watermark. Commit rows are never deleted\n * and every write holds the store's lock, so their rowids grow in commit order.\n */\nfunction committedSince(db: Database, plan: PlanRow, projectId: string): boolean {\n // `+project_id` keeps the lookup on the rowid range instead of the project's whole history.\n return (\n db\n .query(`SELECT 1 FROM ontology_commits WHERE rowid > ? AND +project_id = ? LIMIT 1`)\n .get(plan.watermark, projectId) !== null\n )\n}\n\n/** Deletes the work of the identities of `kind` left to plan: an identity to plan holds none. */\nfunction dropUnplannedWork(db: Database, versionId: number, kind: \"object\" | \"link\"): void {\n db.query(\n `DELETE FROM ${SQLITE_PLAN_WORK_TABLE}\n WHERE work_id = ? AND entity_kind = ? AND identity_key IN (\n SELECT identity_key FROM ${IDENTITIES}\n WHERE version_id = ? AND entity_kind = ? AND planned_revision IS NULL\n )`\n ).run(versionId, kind, versionId, kind)\n}\n\nfunction deletePlan(db: Database, versionId: number): void {\n db.query(`DELETE FROM ${SQLITE_PLAN_WORK_TABLE} WHERE work_id = ?`).run(versionId)\n db.query(`DELETE FROM ${IDENTITIES} WHERE version_id = ?`).run(versionId)\n db.query(`DELETE FROM ontology_replacement_plans WHERE version_id = ?`).run(versionId)\n}\n\nfunction planRow(db: Database, versionId: number): PlanRow | null {\n return db\n .query(`SELECT * FROM ontology_replacement_plans WHERE version_id = ?`)\n .get(versionId) as PlanRow | null\n}\n\nfunction sourceRow(\n db: Database,\n projectId: string,\n sourceId: string,\n materializationId: string\n): SqliteOntologySourceRow | null {\n return db\n .query(\n `SELECT * FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?`\n )\n .get(projectId, sourceId, materializationId) as SqliteOntologySourceRow | null\n}\n\n/** The fresh, fully planned plan a session applies, with exactly its commit. */\nexport function boundReplacementPlan(\n db: Database,\n header: {\n readonly commit: OntologyCommitWrite\n readonly plan?: {\n readonly source: { readonly projectionId: string }\n readonly materializationId: string\n }\n }\n): SqliteReplacementPlan {\n const ref = header.plan\n const candidate = ref\n ? sourceRow(db, header.commit.projectId, ref.source.projectionId, ref.materializationId)\n : null\n const plan = candidate ? planRow(db, candidate.version_id) : null\n if (!ref || !candidate || !plan || header.commit.intent.kind !== \"projection\") {\n throw new MaterializationConflictError(\n \"source-materialization\",\n \"A plan-bound session needs the open plan of a projection candidate.\"\n )\n }\n if (plan.commit_id !== header.commit.id || plan.committed_at !== header.commit.committedAt) {\n throw new MaterializationValidationError(\n \"A plan-bound session must begin with the commit its plan carries.\"\n )\n }\n if (\n committedSince(db, plan, header.commit.projectId) ||\n unplannedCount(db, candidate.version_id) > 0\n ) {\n throw new MaterializationValidationError(\n \"A replacement plan applies only fully planned and just refreshed.\"\n )\n }\n return { versionId: candidate.version_id, projectionKind: candidate.projection_kind }\n}\n",
56
- "import type { Database } from \"bun:sqlite\"\nimport {\n linkRefKey,\n MaterializationConflictError,\n objectRefKey,\n telemetryPointKey,\n} from \"@sixb/core/internal/materialization\"\nimport {\n effectiveConflict,\n type MaterializationPlanChunk,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type { ExactEffectiveLinkWrite, ExactEffectiveObjectWrite } from \"@sixb/core/storage\"\nimport { assertTimestamp, canonicalJson, isSqliteConstraintError, requireChanges } from \"./shared\"\n\nfunction linkOverrideConflictMessage(identityKind: \"edge\" | \"slot\"): string {\n return identityKind === \"edge\"\n ? \"Expected link edge override changed.\"\n : \"Expected link slot override changed.\"\n}\n\nfunction linkOverrideConflict(identityKind: \"edge\" | \"slot\"): MaterializationConflictError {\n return effectiveConflict(linkOverrideConflictMessage(identityKind))\n}\n\n/** Applies one already-validated exact plan chunk to SQLite authority tables. */\nexport class SqliteMaterializationWriter {\n constructor(private readonly db: Database) {}\n\n apply(projectId: string, commitId: string, chunk: MaterializationPlanChunk): void {\n this.applyOverrides(projectId, chunk)\n this.applyEffective(projectId, chunk)\n this.applyTimeseries(projectId, chunk)\n this.applyOutbox(projectId, commitId, chunk)\n }\n\n private applyOverrides(projectId: string, chunk: MaterializationPlanChunk): void {\n for (const item of chunk.overrides.objects.upserts) {\n if (item.expectedLastCommitId === null) {\n try {\n this.db\n .query(\n `INSERT INTO ontology_object_overrides (\n project_id, object_type_id, primary_id, value, edited_at,\n last_commit_id, updated_at\n ) VALUES (?, ?, ?, json(?), json(?), ?, ?)`\n )\n .run(\n projectId,\n item.ref.objectTypeId,\n item.ref.primaryId,\n canonicalJson(item.value),\n canonicalJson(item.editedAt),\n item.lastCommitId,\n item.updatedAt\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw effectiveConflict(\"Expected object override changed.\")\n }\n throw error\n }\n continue\n }\n requireChanges(\n this.db\n .query(\n `UPDATE ontology_object_overrides\n SET value = json(?), edited_at = json(?), last_commit_id = ?, updated_at = ?\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?\n AND last_commit_id = ?`\n )\n .run(\n canonicalJson(item.value),\n canonicalJson(item.editedAt),\n item.lastCommitId,\n item.updatedAt,\n projectId,\n item.ref.objectTypeId,\n item.ref.primaryId,\n item.expectedLastCommitId\n ).changes,\n \"effective-state\",\n \"Expected object override changed.\"\n )\n }\n for (const item of chunk.overrides.objects.deletes) {\n requireChanges(\n this.db\n .query(\n `DELETE FROM ontology_object_overrides\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?\n AND last_commit_id = ?`\n )\n .run(projectId, item.ref.objectTypeId, item.ref.primaryId, item.expectedLastCommitId)\n .changes,\n \"effective-state\",\n \"Expected object override changed.\"\n )\n }\n\n const upsertLink = (\n identityKind: \"edge\" | \"slot\",\n identityKey: string,\n ref: {\n readonly source: { readonly objectTypeId: string; readonly primaryId: string }\n readonly linkId: string\n readonly target: { readonly objectTypeId: string; readonly primaryId: string }\n },\n item:\n | (typeof chunk.overrides.links.edges.upserts)[number]\n | (typeof chunk.overrides.links.slots.upserts)[number]\n ): void => {\n if (item.expectedLastCommitId === null) {\n try {\n this.db\n .query(\n `INSERT INTO ontology_link_overrides (\n project_id, identity_kind, identity_key,\n source_type_id, source_primary_id, link_id,\n target_type_id, target_primary_id, value, last_commit_id, updated_at\n ) VALUES (?, ?, json(?), ?, ?, ?, ?, ?, json(?), ?, ?)`\n )\n .run(\n projectId,\n identityKind,\n identityKey,\n ref.source.objectTypeId,\n ref.source.primaryId,\n ref.linkId,\n ref.target.objectTypeId,\n ref.target.primaryId,\n canonicalJson(item.value),\n item.lastCommitId,\n item.updatedAt\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw linkOverrideConflict(identityKind)\n }\n throw error\n }\n return\n }\n requireChanges(\n this.db\n .query(\n `UPDATE ontology_link_overrides\n SET target_type_id = ?, target_primary_id = ?, value = json(?),\n last_commit_id = ?, updated_at = ?\n WHERE project_id = ? AND identity_kind = ? AND identity_key = json(?)\n AND last_commit_id = ?`\n )\n .run(\n ref.target.objectTypeId,\n ref.target.primaryId,\n canonicalJson(item.value),\n item.lastCommitId,\n item.updatedAt,\n projectId,\n identityKind,\n identityKey,\n item.expectedLastCommitId\n ).changes,\n \"effective-state\",\n linkOverrideConflictMessage(identityKind)\n )\n }\n\n for (const item of chunk.overrides.links.edges.upserts) {\n upsertLink(\"edge\", linkRefKey(item.ref), item.ref, item)\n }\n for (const item of chunk.overrides.links.slots.upserts) {\n upsertLink(\n \"slot\",\n JSON.stringify([item.ref.source.objectTypeId, item.ref.source.primaryId, item.ref.linkId]),\n { source: item.ref.source, linkId: item.ref.linkId, target: item.value.target },\n item\n )\n }\n\n const deleteLink = (\n identityKind: \"edge\" | \"slot\",\n identityKey: string,\n expectedLastCommitId: string\n ): void => {\n requireChanges(\n this.db\n .query(\n `DELETE FROM ontology_link_overrides\n WHERE project_id = ? AND identity_kind = ? AND identity_key = json(?)\n AND last_commit_id = ?`\n )\n .run(projectId, identityKind, identityKey, expectedLastCommitId).changes,\n \"effective-state\",\n linkOverrideConflictMessage(identityKind)\n )\n }\n for (const item of chunk.overrides.links.edges.deletes) {\n deleteLink(\"edge\", linkRefKey(item.ref), item.expectedLastCommitId)\n }\n for (const item of chunk.overrides.links.slots.deletes) {\n deleteLink(\n \"slot\",\n JSON.stringify([item.ref.source.objectTypeId, item.ref.source.primaryId, item.ref.linkId]),\n item.expectedLastCommitId\n )\n }\n }\n\n private applyEffective(projectId: string, chunk: MaterializationPlanChunk): void {\n for (const item of chunk.effective.linkDeletes) {\n requireChanges(\n this.db\n .query(\n `\n DELETE FROM links\n WHERE project_id = ? AND source_type_id = ? AND source_id = ? AND link_id = ?\n AND target_type_id = ? AND target_id = ? AND last_commit_id = ?\n `\n )\n .run(\n projectId,\n item.ref.source.objectTypeId,\n item.ref.source.primaryId,\n item.ref.linkId,\n item.ref.target.objectTypeId,\n item.ref.target.primaryId,\n item.expected.lastCommitId\n ).changes,\n \"effective-state\",\n `Expected link ${linkRefKey(item.ref)} changed.`\n )\n }\n for (const item of chunk.effective.objectDeletes) {\n requireChanges(\n this.db\n .query(\n `DELETE FROM objects\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?\n AND version = ? AND last_commit_id = ?`\n )\n .run(\n projectId,\n item.ref.objectTypeId,\n item.ref.primaryId,\n item.expected.version,\n item.expected.lastCommitId\n ).changes,\n \"effective-state\",\n `Expected object ${objectRefKey(item.ref)} changed.`\n )\n }\n for (const item of chunk.effective.objectUpserts) this.applyObject(projectId, item)\n for (const item of chunk.effective.linkUpserts) this.applyLink(projectId, item)\n }\n\n private applyObject(projectId: string, item: ExactEffectiveObjectWrite): void {\n const { row, expected } = item\n if (!expected.exists) {\n try {\n this.db\n .query(\n `\n INSERT INTO objects (\n project_id, object_type_id, primary_id, properties, created_at,\n updated_at, version, last_commit_id\n ) VALUES (?, ?, ?, json(?), ?, ?, ?, ?)\n `\n )\n .run(\n projectId,\n row.ref.objectTypeId,\n row.ref.primaryId,\n canonicalJson(row.properties),\n row.createdAt,\n row.updatedAt,\n row.version,\n row.lastCommitId\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw effectiveConflict(`Expected object ${objectRefKey(row.ref)} to be absent.`)\n }\n throw error\n }\n return\n }\n requireChanges(\n this.db\n .query(\n `\n UPDATE objects\n SET properties = json(?), created_at = ?, updated_at = ?, version = ?,\n last_commit_id = ?\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?\n AND version = ? AND last_commit_id = ?\n `\n )\n .run(\n canonicalJson(row.properties),\n row.createdAt,\n row.updatedAt,\n row.version,\n row.lastCommitId,\n projectId,\n row.ref.objectTypeId,\n row.ref.primaryId,\n expected.version,\n expected.lastCommitId\n ).changes,\n \"effective-state\",\n `Expected object ${objectRefKey(row.ref)} changed.`\n )\n }\n\n private applyLink(projectId: string, item: ExactEffectiveLinkWrite): void {\n const { row, expected } = item\n if (!expected.exists) {\n try {\n this.db\n .query(\n `\n INSERT INTO links (\n project_id, source_type_id, source_id, link_id, target_type_id, target_id,\n properties, created_at, updated_at, last_commit_id\n ) VALUES (?, ?, ?, ?, ?, ?, json(?), ?, ?, ?)\n `\n )\n .run(\n projectId,\n row.ref.source.objectTypeId,\n row.ref.source.primaryId,\n row.ref.linkId,\n row.ref.target.objectTypeId,\n row.ref.target.primaryId,\n row.properties === undefined ? null : canonicalJson(row.properties),\n row.createdAt,\n row.updatedAt,\n row.lastCommitId\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw effectiveConflict(`Expected link ${linkRefKey(row.ref)} to be absent.`)\n }\n throw error\n }\n return\n }\n requireChanges(\n this.db\n .query(\n `\n UPDATE links\n SET properties = json(?), created_at = ?, updated_at = ?,\n last_commit_id = ?\n WHERE project_id = ? AND source_type_id = ? AND source_id = ? AND link_id = ?\n AND target_type_id = ? AND target_id = ? AND last_commit_id = ?\n `\n )\n .run(\n row.properties === undefined ? null : canonicalJson(row.properties),\n row.createdAt,\n row.updatedAt,\n row.lastCommitId,\n projectId,\n row.ref.source.objectTypeId,\n row.ref.source.primaryId,\n row.ref.linkId,\n row.ref.target.objectTypeId,\n row.ref.target.primaryId,\n expected.lastCommitId\n ).changes,\n \"effective-state\",\n `Expected link ${linkRefKey(row.ref)} changed.`\n )\n }\n\n private applyTimeseries(projectId: string, chunk: MaterializationPlanChunk): void {\n for (const item of chunk.timeseries.pointUpserts) {\n const { point, expected } = item\n if (expected.lastCommitId === null) {\n try {\n this.db\n .query(\n `\n INSERT INTO timeseries (\n project_id, object_type_id, object_id, property_id,\n value, unit, at, last_commit_id\n ) VALUES (?, ?, ?, ?, json(?), ?, ?, ?)\n `\n )\n .run(\n projectId,\n point.series.object.objectTypeId,\n point.series.object.primaryId,\n point.series.propertyId,\n canonicalJson(point.value),\n point.unit ?? null,\n point.at,\n point.lastCommitId\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw new MaterializationConflictError(\n \"timeseries-point\",\n `Telemetry point ${telemetryPointKey(point.series, point.at)} changed.`\n )\n }\n throw error\n }\n } else {\n requireChanges(\n this.db\n .query(\n `\n UPDATE timeseries\n SET value = json(?), unit = ?, last_commit_id = ?\n WHERE project_id = ? AND object_type_id = ? AND object_id = ?\n AND property_id = ? AND at = ? AND last_commit_id = ?\n `\n )\n .run(\n canonicalJson(point.value),\n point.unit ?? null,\n point.lastCommitId,\n projectId,\n point.series.object.objectTypeId,\n point.series.object.primaryId,\n point.series.propertyId,\n point.at,\n expected.lastCommitId\n ).changes,\n \"timeseries-point\",\n `Telemetry point ${telemetryPointKey(point.series, point.at)} changed.`\n )\n }\n }\n }\n\n private applyOutbox(projectId: string, commitId: string, chunk: MaterializationPlanChunk): void {\n const insert = this.db.query(\n `\n INSERT INTO ontology_outbox (\n project_id, id, commit_id, commit_ordinal, event,\n available_at, attempts, lease_id, lease_expires_at,\n published_at, last_failure, created_at\n ) VALUES (?, ?, ?, ?, json(?), ?, 0, NULL, NULL, NULL, NULL, ?)\n `\n )\n for (const item of chunk.outbox) {\n assertTimestamp(item.createdAt, \"Outbox createdAt\")\n try {\n insert.run(\n projectId,\n item.id,\n commitId,\n item.commitOrdinal,\n canonicalJson(item.event),\n item.createdAt,\n item.createdAt\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw effectiveConflict(`Duplicate outbox event '${item.id}'.`)\n }\n throw error\n }\n }\n }\n}\n",
61
+ "import type { Database } from \"bun:sqlite\"\nimport {\n linkRefKey,\n MaterializationConflictError,\n objectRefKey,\n telemetryPointKey,\n} from \"@sixb/core/internal/materialization\"\nimport {\n effectiveConflict,\n type MaterializationPlanChunk,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type { ExactEffectiveLinkWrite, ExactEffectiveObjectWrite } from \"@sixb/core/storage\"\nimport { assertTimestamp, canonicalJson, isSqliteConstraintError, requireChanges } from \"./shared\"\nimport {\n assertSqliteUniquePrepared,\n claimSqliteUniqueValue,\n releaseSqliteUniqueValue,\n} from \"./unique-values\"\n\nfunction linkOverrideConflictMessage(identityKind: \"edge\" | \"slot\"): string {\n return identityKind === \"edge\"\n ? \"Expected link edge override changed.\"\n : \"Expected link slot override changed.\"\n}\n\nfunction linkOverrideConflict(identityKind: \"edge\" | \"slot\"): MaterializationConflictError {\n return effectiveConflict(linkOverrideConflictMessage(identityKind))\n}\n\n/** Applies one already-validated exact plan chunk to SQLite authority tables. */\nexport class SqliteMaterializationWriter {\n constructor(private readonly db: Database) {}\n\n apply(projectId: string, commitId: string, chunk: MaterializationPlanChunk): void {\n this.applyOverrides(projectId, chunk)\n this.applyEffective(projectId, chunk)\n this.applyTimeseries(projectId, chunk)\n this.applyUniqueValues(projectId, chunk)\n this.applyOutbox(projectId, commitId, chunk)\n }\n\n /** A chunk holds one phase: the commit's releases all apply before its first claim. */\n private applyUniqueValues(projectId: string, chunk: MaterializationPlanChunk): void {\n for (const item of chunk.unique.releases) releaseSqliteUniqueValue(this.db, projectId, item)\n\n assertSqliteUniquePrepared(this.db, projectId, chunk.unique.claims)\n for (const item of chunk.unique.claims) claimSqliteUniqueValue(this.db, projectId, item)\n }\n\n private applyOverrides(projectId: string, chunk: MaterializationPlanChunk): void {\n for (const item of chunk.overrides.objects.upserts) {\n if (item.expectedLastCommitId === null) {\n try {\n this.db\n .query(\n `INSERT INTO ontology_object_overrides (\n project_id, object_type_id, primary_id, value, edited_at,\n last_commit_id, updated_at\n ) VALUES (?, ?, ?, json(?), json(?), ?, ?)`\n )\n .run(\n projectId,\n item.ref.objectTypeId,\n item.ref.primaryId,\n canonicalJson(item.value),\n canonicalJson(item.editedAt),\n item.lastCommitId,\n item.updatedAt\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw effectiveConflict(\"Expected object override changed.\")\n }\n throw error\n }\n continue\n }\n requireChanges(\n this.db\n .query(\n `UPDATE ontology_object_overrides\n SET value = json(?), edited_at = json(?), last_commit_id = ?, updated_at = ?\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?\n AND last_commit_id = ?`\n )\n .run(\n canonicalJson(item.value),\n canonicalJson(item.editedAt),\n item.lastCommitId,\n item.updatedAt,\n projectId,\n item.ref.objectTypeId,\n item.ref.primaryId,\n item.expectedLastCommitId\n ).changes,\n \"effective-state\",\n \"Expected object override changed.\"\n )\n }\n for (const item of chunk.overrides.objects.deletes) {\n requireChanges(\n this.db\n .query(\n `DELETE FROM ontology_object_overrides\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?\n AND last_commit_id = ?`\n )\n .run(projectId, item.ref.objectTypeId, item.ref.primaryId, item.expectedLastCommitId)\n .changes,\n \"effective-state\",\n \"Expected object override changed.\"\n )\n }\n\n const upsertLink = (\n identityKind: \"edge\" | \"slot\",\n identityKey: string,\n ref: {\n readonly source: { readonly objectTypeId: string; readonly primaryId: string }\n readonly linkId: string\n readonly target: { readonly objectTypeId: string; readonly primaryId: string }\n },\n item:\n | (typeof chunk.overrides.links.edges.upserts)[number]\n | (typeof chunk.overrides.links.slots.upserts)[number]\n ): void => {\n if (item.expectedLastCommitId === null) {\n try {\n this.db\n .query(\n `INSERT INTO ontology_link_overrides (\n project_id, identity_kind, identity_key,\n source_type_id, source_primary_id, link_id,\n target_type_id, target_primary_id, value, last_commit_id, updated_at\n ) VALUES (?, ?, json(?), ?, ?, ?, ?, ?, json(?), ?, ?)`\n )\n .run(\n projectId,\n identityKind,\n identityKey,\n ref.source.objectTypeId,\n ref.source.primaryId,\n ref.linkId,\n ref.target.objectTypeId,\n ref.target.primaryId,\n canonicalJson(item.value),\n item.lastCommitId,\n item.updatedAt\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw linkOverrideConflict(identityKind)\n }\n throw error\n }\n return\n }\n requireChanges(\n this.db\n .query(\n `UPDATE ontology_link_overrides\n SET target_type_id = ?, target_primary_id = ?, value = json(?),\n last_commit_id = ?, updated_at = ?\n WHERE project_id = ? AND identity_kind = ? AND identity_key = json(?)\n AND last_commit_id = ?`\n )\n .run(\n ref.target.objectTypeId,\n ref.target.primaryId,\n canonicalJson(item.value),\n item.lastCommitId,\n item.updatedAt,\n projectId,\n identityKind,\n identityKey,\n item.expectedLastCommitId\n ).changes,\n \"effective-state\",\n linkOverrideConflictMessage(identityKind)\n )\n }\n\n for (const item of chunk.overrides.links.edges.upserts) {\n upsertLink(\"edge\", linkRefKey(item.ref), item.ref, item)\n }\n for (const item of chunk.overrides.links.slots.upserts) {\n upsertLink(\n \"slot\",\n JSON.stringify([item.ref.source.objectTypeId, item.ref.source.primaryId, item.ref.linkId]),\n { source: item.ref.source, linkId: item.ref.linkId, target: item.value.target },\n item\n )\n }\n\n const deleteLink = (\n identityKind: \"edge\" | \"slot\",\n identityKey: string,\n expectedLastCommitId: string\n ): void => {\n requireChanges(\n this.db\n .query(\n `DELETE FROM ontology_link_overrides\n WHERE project_id = ? AND identity_kind = ? AND identity_key = json(?)\n AND last_commit_id = ?`\n )\n .run(projectId, identityKind, identityKey, expectedLastCommitId).changes,\n \"effective-state\",\n linkOverrideConflictMessage(identityKind)\n )\n }\n for (const item of chunk.overrides.links.edges.deletes) {\n deleteLink(\"edge\", linkRefKey(item.ref), item.expectedLastCommitId)\n }\n for (const item of chunk.overrides.links.slots.deletes) {\n deleteLink(\n \"slot\",\n JSON.stringify([item.ref.source.objectTypeId, item.ref.source.primaryId, item.ref.linkId]),\n item.expectedLastCommitId\n )\n }\n }\n\n private applyEffective(projectId: string, chunk: MaterializationPlanChunk): void {\n for (const item of chunk.effective.linkDeletes) {\n requireChanges(\n this.db\n .query(\n `\n DELETE FROM links\n WHERE project_id = ? AND source_type_id = ? AND source_id = ? AND link_id = ?\n AND target_type_id = ? AND target_id = ? AND last_commit_id = ?\n `\n )\n .run(\n projectId,\n item.ref.source.objectTypeId,\n item.ref.source.primaryId,\n item.ref.linkId,\n item.ref.target.objectTypeId,\n item.ref.target.primaryId,\n item.expected.lastCommitId\n ).changes,\n \"effective-state\",\n `Expected link ${linkRefKey(item.ref)} changed.`\n )\n }\n for (const item of chunk.effective.objectDeletes) {\n requireChanges(\n this.db\n .query(\n `DELETE FROM objects\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?\n AND version = ? AND last_commit_id = ?`\n )\n .run(\n projectId,\n item.ref.objectTypeId,\n item.ref.primaryId,\n item.expected.version,\n item.expected.lastCommitId\n ).changes,\n \"effective-state\",\n `Expected object ${objectRefKey(item.ref)} changed.`\n )\n }\n for (const item of chunk.effective.objectUpserts) this.applyObject(projectId, item)\n for (const item of chunk.effective.linkUpserts) this.applyLink(projectId, item)\n }\n\n private applyObject(projectId: string, item: ExactEffectiveObjectWrite): void {\n const { row, expected } = item\n if (!expected.exists) {\n try {\n this.db\n .query(\n `\n INSERT INTO objects (\n project_id, object_type_id, primary_id, properties, created_at,\n updated_at, version, last_commit_id\n ) VALUES (?, ?, ?, json(?), ?, ?, ?, ?)\n `\n )\n .run(\n projectId,\n row.ref.objectTypeId,\n row.ref.primaryId,\n canonicalJson(row.properties),\n row.createdAt,\n row.updatedAt,\n row.version,\n row.lastCommitId\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw effectiveConflict(`Expected object ${objectRefKey(row.ref)} to be absent.`)\n }\n throw error\n }\n return\n }\n requireChanges(\n this.db\n .query(\n `\n UPDATE objects\n SET properties = json(?), created_at = ?, updated_at = ?, version = ?,\n last_commit_id = ?\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?\n AND version = ? AND last_commit_id = ?\n `\n )\n .run(\n canonicalJson(row.properties),\n row.createdAt,\n row.updatedAt,\n row.version,\n row.lastCommitId,\n projectId,\n row.ref.objectTypeId,\n row.ref.primaryId,\n expected.version,\n expected.lastCommitId\n ).changes,\n \"effective-state\",\n `Expected object ${objectRefKey(row.ref)} changed.`\n )\n }\n\n private applyLink(projectId: string, item: ExactEffectiveLinkWrite): void {\n const { row, expected } = item\n if (!expected.exists) {\n try {\n this.db\n .query(\n `\n INSERT INTO links (\n project_id, source_type_id, source_id, link_id, target_type_id, target_id,\n properties, created_at, updated_at, last_commit_id\n ) VALUES (?, ?, ?, ?, ?, ?, json(?), ?, ?, ?)\n `\n )\n .run(\n projectId,\n row.ref.source.objectTypeId,\n row.ref.source.primaryId,\n row.ref.linkId,\n row.ref.target.objectTypeId,\n row.ref.target.primaryId,\n row.properties === undefined ? null : canonicalJson(row.properties),\n row.createdAt,\n row.updatedAt,\n row.lastCommitId\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw effectiveConflict(`Expected link ${linkRefKey(row.ref)} to be absent.`)\n }\n throw error\n }\n return\n }\n requireChanges(\n this.db\n .query(\n `\n UPDATE links\n SET properties = json(?), created_at = ?, updated_at = ?,\n last_commit_id = ?\n WHERE project_id = ? AND source_type_id = ? AND source_id = ? AND link_id = ?\n AND target_type_id = ? AND target_id = ? AND last_commit_id = ?\n `\n )\n .run(\n row.properties === undefined ? null : canonicalJson(row.properties),\n row.createdAt,\n row.updatedAt,\n row.lastCommitId,\n projectId,\n row.ref.source.objectTypeId,\n row.ref.source.primaryId,\n row.ref.linkId,\n row.ref.target.objectTypeId,\n row.ref.target.primaryId,\n expected.lastCommitId\n ).changes,\n \"effective-state\",\n `Expected link ${linkRefKey(row.ref)} changed.`\n )\n }\n\n private applyTimeseries(projectId: string, chunk: MaterializationPlanChunk): void {\n for (const item of chunk.timeseries.pointUpserts) {\n const { point, expected } = item\n if (expected.lastCommitId === null) {\n try {\n this.db\n .query(\n `\n INSERT INTO timeseries (\n project_id, object_type_id, object_id, property_id,\n value, unit, at, last_commit_id\n ) VALUES (?, ?, ?, ?, json(?), ?, ?, ?)\n `\n )\n .run(\n projectId,\n point.series.object.objectTypeId,\n point.series.object.primaryId,\n point.series.propertyId,\n canonicalJson(point.value),\n point.unit ?? null,\n point.at,\n point.lastCommitId\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw new MaterializationConflictError(\n \"timeseries-point\",\n `Telemetry point ${telemetryPointKey(point.series, point.at)} changed.`\n )\n }\n throw error\n }\n } else {\n requireChanges(\n this.db\n .query(\n `\n UPDATE timeseries\n SET value = json(?), unit = ?, last_commit_id = ?\n WHERE project_id = ? AND object_type_id = ? AND object_id = ?\n AND property_id = ? AND at = ? AND last_commit_id = ?\n `\n )\n .run(\n canonicalJson(point.value),\n point.unit ?? null,\n point.lastCommitId,\n projectId,\n point.series.object.objectTypeId,\n point.series.object.primaryId,\n point.series.propertyId,\n point.at,\n expected.lastCommitId\n ).changes,\n \"timeseries-point\",\n `Telemetry point ${telemetryPointKey(point.series, point.at)} changed.`\n )\n }\n }\n }\n\n private applyOutbox(projectId: string, commitId: string, chunk: MaterializationPlanChunk): void {\n const insert = this.db.query(\n `\n INSERT INTO ontology_outbox (\n project_id, id, commit_id, commit_ordinal, event,\n available_at, attempts, lease_id, lease_expires_at,\n published_at, last_failure, created_at\n ) VALUES (?, ?, ?, ?, json(?), ?, 0, NULL, NULL, NULL, NULL, ?)\n `\n )\n for (const item of chunk.outbox) {\n assertTimestamp(item.createdAt, \"Outbox createdAt\")\n try {\n insert.run(\n projectId,\n item.id,\n commitId,\n item.commitOrdinal,\n canonicalJson(item.event),\n item.createdAt,\n item.createdAt\n )\n } catch (error) {\n if (isSqliteConstraintError(error)) {\n throw effectiveConflict(`Duplicate outbox event '${item.id}'.`)\n }\n throw error\n }\n }\n }\n}\n",
62
+ "import type { Database } from \"bun:sqlite\"\nimport {\n uniquePropertyNotPrepared,\n uniqueValueViolation,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type {\n ExactUniqueValueClaim,\n ExactUniqueValueWrite,\n OntologyUniqueValueStorage,\n PreparedUniqueProperty,\n UniqueValueEntry,\n UniqueValueRef,\n} from \"@sixb/core/storage\"\nimport type { SqliteRootOperation } from \"./shared\"\n\n/** The object holding a unique value, or null when none does. */\nexport function sqliteUniqueHolder(\n db: Database,\n projectId: string,\n value: UniqueValueRef\n): string | null {\n const row = db\n .query(\n `SELECT primary_id FROM object_unique_values\n WHERE project_id = ? AND object_type_id = ? AND property_id = ? AND value_key = ?`\n )\n .get(projectId, value.objectTypeId, value.propertyId, value.valueKey) as {\n readonly primary_id: string\n } | null\n return row?.primary_id ?? null\n}\n\n/** Gives the value to its object, unless another object holds it. */\nexport function claimSqliteUniqueValue(\n db: Database,\n projectId: string,\n value: ExactUniqueValueWrite\n): void {\n const holder = sqliteUniqueHolder(db, projectId, value)\n if (holder === value.primaryId) return\n if (holder !== null) throw uniqueValueViolation(value, holder, value.primaryId)\n\n db.query(\n `INSERT INTO object_unique_values (\n project_id, object_type_id, property_id, value_key, primary_id\n ) VALUES (?, ?, ?, ?, ?)`\n ).run(projectId, value.objectTypeId, value.propertyId, value.valueKey, value.primaryId)\n}\n\n/**\n * Refuses claims on a property whose values were not built with the claims' keys. Each property\n * is checked once per call, however many of its values the claims take.\n */\nexport function assertSqliteUniquePrepared(\n db: Database,\n projectId: string,\n claims: readonly ExactUniqueValueClaim[]\n): void {\n const checked = new Set<string>()\n const prepared = db.query(\n `SELECT 1 FROM object_unique_properties\n WHERE project_id = ? AND object_type_id = ? AND property_id = ?\n AND key_kind = ? AND key_version = ?`\n )\n\n for (const claim of claims) {\n const key = JSON.stringify([\n claim.objectTypeId,\n claim.propertyId,\n claim.keyKind,\n claim.keyVersion,\n ])\n if (checked.has(key)) continue\n checked.add(key)\n\n const row = prepared.get(\n projectId,\n claim.objectTypeId,\n claim.propertyId,\n claim.keyKind,\n claim.keyVersion\n )\n if (!row) throw uniquePropertyNotPrepared(claim)\n }\n}\n\n/** Drops the value if its object still holds it. */\nexport function releaseSqliteUniqueValue(\n db: Database,\n projectId: string,\n value: ExactUniqueValueWrite\n): void {\n db.query(\n `DELETE FROM object_unique_values\n WHERE project_id = ? AND object_type_id = ? AND property_id = ? AND value_key = ?\n AND primary_id = ?`\n ).run(projectId, value.objectTypeId, value.propertyId, value.valueKey, value.primaryId)\n}\n\nexport class SqliteOntologyUniqueValueStorage implements OntologyUniqueValueStorage {\n constructor(\n private readonly db: Database,\n private readonly runRootOperation: SqliteRootOperation\n ) {}\n\n /** A SQLite database has one writer at a time: preparers already take turns. */\n async lockPreparation(_input: { readonly projectId: string }): Promise<void> {}\n\n async listPrepared(input: {\n readonly projectId: string\n }): Promise<readonly PreparedUniqueProperty[]> {\n return this.runRootOperation(() => {\n const rows = this.db\n .query(\n `SELECT object_type_id, property_id, key_kind, key_version FROM object_unique_properties\n WHERE project_id = ?\n ORDER BY object_type_id, property_id`\n )\n .all(input.projectId) as {\n readonly object_type_id: string\n readonly property_id: string\n readonly key_kind: PreparedUniqueProperty[\"keyKind\"]\n readonly key_version: number\n }[]\n return rows.map((row) => ({\n objectTypeId: row.object_type_id,\n propertyId: row.property_id,\n keyKind: row.key_kind,\n keyVersion: row.key_version,\n }))\n })\n }\n\n async clear(input: {\n readonly projectId: string\n readonly objectTypeId: string\n readonly propertyId: string\n }): Promise<void> {\n await this.runRootOperation(() => {\n for (const table of [\"object_unique_values\", \"object_unique_properties\"]) {\n this.db\n .query(\n `DELETE FROM ${table} WHERE project_id = ? AND object_type_id = ? AND property_id = ?`\n )\n .run(input.projectId, input.objectTypeId, input.propertyId)\n }\n })\n }\n\n async insert(input: {\n readonly projectId: string\n readonly objectTypeId: string\n readonly propertyId: string\n readonly entries: readonly UniqueValueEntry[]\n }): Promise<void> {\n const { projectId, objectTypeId, propertyId } = input\n await this.runRootOperation(() => {\n for (const entry of input.entries) {\n claimSqliteUniqueValue(this.db, projectId, { objectTypeId, propertyId, ...entry })\n }\n })\n }\n\n async markPrepared(\n input: PreparedUniqueProperty & { readonly projectId: string; readonly preparedAt: string }\n ): Promise<void> {\n await this.runRootOperation(() => {\n this.db\n .query(\n `INSERT INTO object_unique_properties (\n project_id, object_type_id, property_id, key_kind, key_version, prepared_at\n ) VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT (project_id, object_type_id, property_id)\n DO UPDATE SET key_kind = excluded.key_kind, key_version = excluded.key_version,\n prepared_at = excluded.prepared_at`\n )\n .run(\n input.projectId,\n input.objectTypeId,\n input.propertyId,\n input.keyKind,\n input.keyVersion,\n input.preparedAt\n )\n })\n }\n}\n",
57
63
  "import type { Database } from \"bun:sqlite\"\nimport { serializeSixbFailure } from \"@sixb/core/internal/errors\"\nimport {\n MaterializationConflictError,\n MaterializationValidationError,\n} from \"@sixb/core/internal/materialization\"\nimport {\n claimedOutboxRows,\n type OutboxEventContext,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type {\n ClaimedOntologyOutboxRow,\n ClaimOntologyOutboxInput,\n CompleteOntologyOutboxLeaseInput,\n OntologyOutboxStorage,\n OntologyOutboxSummary,\n PurgePublishedOntologyOutboxInput,\n RescheduleOntologyOutboxLeaseInput,\n SummarizeOntologyOutboxInput,\n} from \"@sixb/core/storage\"\nimport { ONTOLOGY_OUTBOX_FAILURE_CODES } from \"@sixb/core/storage\"\nimport { type SqliteExecutionRow, sqliteExecutionRecord } from \"../execution-storage\"\nimport {\n assertNonblank,\n assertPositiveInteger,\n assertTimestamp,\n claimedOutboxDraft,\n parseJson,\n type SqliteOntologyOutboxRow,\n type SqliteRootOperation,\n} from \"./shared\"\n\n/** A commit's own fields, prefixed, beside every column of the execution it ran under. */\ninterface SqliteOutboxContextRow extends SqliteExecutionRow {\n readonly commit_id: string\n readonly commit_committed_at: string\n readonly commit_origin: string\n}\n\nexport class SqliteOntologyOutboxStorage implements OntologyOutboxStorage {\n constructor(\n private readonly db: Database,\n private readonly runRootOperation: SqliteRootOperation\n ) {}\n\n async claim(input: ClaimOntologyOutboxInput): Promise<readonly ClaimedOntologyOutboxRow[]> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n assertPositiveInteger(input.limit, \"Ontology outbox limit\")\n const now = assertTimestamp(input.now, \"Ontology outbox claim time\")\n const leaseExpiry = assertTimestamp(input.leaseExpiresAt, \"Ontology outbox lease expiry\")\n assertNonblank(input.leaseId, \"Ontology outbox lease id\")\n if (leaseExpiry <= now) {\n throw new MaterializationValidationError(\n \"Ontology outbox lease expiry must be later than the claim time.\"\n )\n }\n\n // Probe at most one page plus a sentinel through the eligibility index. Sparse retries\n // avoid scanning delayed rows; overflowing backlogs use publication order without a sort.\n const eligible = this.db\n .query(\n `SELECT CAST(rowid AS TEXT) AS rowId\n FROM ontology_outbox INDEXED BY idx_ontology_outbox_claim\n WHERE project_id = ? AND published_at IS NULL AND available_at <= ?\n AND (lease_expires_at IS NULL OR lease_expires_at <= ?)\n LIMIT ?`\n )\n .all(input.projectId, input.now, input.now, input.limit + 1) as { rowId: string }[]\n if (eligible.length === 0) return []\n const selected =\n eligible.length <= input.limit\n ? eligible\n : (this.db\n .query(\n `SELECT CAST(rowid AS TEXT) AS rowId\n FROM ontology_outbox INDEXED BY idx_ontology_outbox_publication_order\n WHERE project_id = ? AND published_at IS NULL AND available_at <= ?\n AND (lease_expires_at IS NULL OR lease_expires_at <= ?)\n ORDER BY created_at, commit_id, commit_ordinal\n LIMIT ?`\n )\n .all(input.projectId, input.now, input.now, input.limit) as { rowId: string }[])\n const rows = this.db\n .query(\n `\n UPDATE ontology_outbox\n SET attempts = attempts + 1, lease_id = ?, lease_expires_at = ?\n WHERE rowid IN (SELECT CAST(value AS INTEGER) FROM json_each(?))\n RETURNING id, commit_id, commit_ordinal, event, available_at, attempts, lease_id,\n lease_expires_at, published_at, last_failure, created_at\n `\n )\n .all(\n input.leaseId,\n input.leaseExpiresAt,\n JSON.stringify(selected.map((row) => row.rowId))\n ) as SqliteOntologyOutboxRow[]\n // Each commit and its execution are read once, however many of its events the batch holds.\n const contexts = this.db\n .query(\n `SELECT commits.id AS commit_id, commits.committed_at AS commit_committed_at,\n commits.origin AS commit_origin, executions.*\n FROM json_each(?) AS requested\n CROSS JOIN ontology_commits AS commits\n ON commits.project_id = ? AND commits.id = requested.value\n CROSS JOIN executions\n ON executions.project_id = commits.project_id AND executions.id = commits.execution_id`\n )\n .all(\n JSON.stringify([...new Set(rows.map((row) => row.commit_id))]),\n input.projectId\n ) as SqliteOutboxContextRow[]\n const contextOf = new Map(\n contexts.map((row) => [row.commit_id, outboxEventContext(input.projectId, row)])\n )\n const drafts = rows\n .map(claimedOutboxDraft)\n .sort(\n (left, right) =>\n left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id)\n )\n return claimedOutboxRows(drafts, (commitId) => contextOf.get(commitId))\n })\n }\n\n async markPublished(input: CompleteOntologyOutboxLeaseInput): Promise<void> {\n await this.runRootOperation(() => {\n assertLeaseInput(input)\n assertTimestamp(input.publishedAt, \"Ontology outbox publishedAt\")\n const ids = validateLeaseIds(input.ids)\n const changed = this.db\n .query(\n `\n WITH requested(id) AS MATERIALIZED (\n SELECT CAST(value AS TEXT) FROM json_each(?)\n ), leased(id) AS MATERIALIZED (\n -- Drive validation from the bounded ID list even before ANALYZE.\n SELECT outbox.id FROM requested\n CROSS JOIN ontology_outbox AS outbox USING (id)\n WHERE outbox.project_id = ? AND outbox.lease_id = ?\n AND outbox.lease_expires_at IS NOT NULL\n ), eligible(id) AS (\n SELECT id FROM leased WHERE (SELECT COUNT(*) FROM leased) = ?\n )\n UPDATE ontology_outbox\n SET published_at = ?, lease_id = NULL, lease_expires_at = NULL\n WHERE project_id = ? AND id IN (SELECT id FROM eligible)\n AND lease_id = ? AND lease_expires_at IS NOT NULL\n `\n )\n .run(\n JSON.stringify(ids),\n input.projectId,\n input.leaseId,\n ids.length,\n input.publishedAt,\n input.projectId,\n input.leaseId\n ).changes\n if (changed !== ids.length) throw leaseConflict()\n })\n }\n\n async reschedule(input: RescheduleOntologyOutboxLeaseInput): Promise<void> {\n await this.runRootOperation(() => {\n assertLeaseInput(input)\n assertTimestamp(input.availableAt, \"Ontology outbox availableAt\")\n const ids = validateLeaseIds(input.ids)\n const failure =\n input.failure === undefined\n ? null\n : serializeSixbFailure(input.failure, ONTOLOGY_OUTBOX_FAILURE_CODES)\n const changed = this.db\n .query(\n `\n WITH requested(id) AS MATERIALIZED (\n SELECT CAST(value AS TEXT) FROM json_each(?)\n ), leased(id) AS MATERIALIZED (\n -- Drive validation from the bounded ID list even before ANALYZE.\n SELECT outbox.id FROM requested\n CROSS JOIN ontology_outbox AS outbox USING (id)\n WHERE outbox.project_id = ? AND outbox.lease_id = ?\n AND outbox.lease_expires_at IS NOT NULL\n ), eligible(id) AS (\n SELECT id FROM leased WHERE (SELECT COUNT(*) FROM leased) = ?\n )\n UPDATE ontology_outbox\n SET available_at = ?, last_failure = COALESCE(?, last_failure),\n lease_id = NULL, lease_expires_at = NULL\n WHERE project_id = ? AND id IN (SELECT id FROM eligible)\n AND lease_id = ? AND lease_expires_at IS NOT NULL\n `\n )\n .run(\n JSON.stringify(ids),\n input.projectId,\n input.leaseId,\n ids.length,\n input.availableAt,\n failure,\n input.projectId,\n input.leaseId\n ).changes\n if (changed !== ids.length) throw leaseConflict()\n })\n }\n\n async purgePublished(input: PurgePublishedOntologyOutboxInput): Promise<number> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n assertPositiveInteger(input.limit, \"Ontology outbox limit\")\n assertTimestamp(input.publishedBefore, \"Ontology outbox purge cutoff\")\n return this.db\n .query(\n `\n DELETE FROM ontology_outbox\n WHERE rowid IN (\n SELECT rowid FROM ontology_outbox\n WHERE project_id = ? AND published_at IS NOT NULL AND published_at < ?\n ORDER BY published_at, id\n LIMIT ?\n )\n `\n )\n .run(input.projectId, input.publishedBefore, input.limit).changes\n })\n }\n\n async summarize(input: SummarizeOntologyOutboxInput): Promise<OntologyOutboxSummary> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n const summary = this.db\n .query(\n `\n SELECT COUNT(*) AS pending_count,\n MIN(created_at) AS oldest_pending_at,\n SUM(CASE WHEN attempts > 0 THEN 1 ELSE 0 END) AS retrying_count,\n COALESCE(MAX(attempts), 0) AS max_attempts\n FROM ontology_outbox\n WHERE project_id = ? AND published_at IS NULL\n `\n )\n .get(input.projectId) as {\n readonly pending_count: number\n readonly oldest_pending_at: string | null\n readonly retrying_count: number | null\n readonly max_attempts: number\n }\n return {\n pendingCount: summary.pending_count,\n oldestPendingAt: summary.oldest_pending_at,\n retryingCount: summary.retrying_count ?? 0,\n maxAttempts: summary.max_attempts,\n }\n })\n }\n}\n\nfunction outboxEventContext(projectId: string, row: SqliteOutboxContextRow): OutboxEventContext {\n return {\n commit: {\n projectId,\n id: row.commit_id,\n committedAt: row.commit_committed_at,\n origin: parseJson<OutboxEventContext[\"commit\"][\"origin\"]>(row.commit_origin),\n },\n execution: sqliteExecutionRecord(row),\n }\n}\n\nfunction validateLeaseIds(ids: readonly string[]): string[] {\n const seen = new Set<string>()\n for (const id of ids) {\n assertNonblank(id, \"Ontology outbox event id\")\n if (seen.has(id)) {\n throw new MaterializationValidationError(`Ontology outbox lease batch repeats event '${id}'.`)\n }\n seen.add(id)\n }\n return [...seen]\n}\n\nfunction assertLeaseInput(input: {\n readonly projectId: string\n readonly ids: readonly string[]\n readonly leaseId: string\n}): void {\n assertNonblank(input.projectId, \"Ontology outbox project id\")\n assertNonblank(input.leaseId, \"Ontology outbox lease id\")\n}\n\nfunction leaseConflict(): MaterializationConflictError {\n return new MaterializationConflictError(\"outbox-lease\", \"Ontology outbox lease does not match.\")\n}\n",
58
64
  "import type { Database } from \"bun:sqlite\"\nimport { MaterializationValidationError } from \"@sixb/core/internal/materialization\"\nimport {\n assertSourceBeginInput as assertBeginInput,\n assertSourceExecutionIdentity as assertExecutionIdentity,\n assertSourceProject as assertProjectAndSource,\n assertSourceCandidateOwner,\n assertSourceWriteIdentity as assertWriteIdentity,\n sourceEntityColumns as entityColumns,\n isExactStagingManifest,\n reconcileSourceStageRows,\n type SourceStageRow,\n sourceAssertionPayload,\n sourceConflict,\n sourceMaterializationIdentity,\n sourceStageRow,\n sourceStageRows,\n} from \"@sixb/core/internal/ontology-storage-provider\"\nimport type {\n AbandonRunSourceMaterializationInput,\n AbandonSourceMaterializationCandidateInput,\n AbandonSourceMaterializationInput,\n ActiveOntologySource,\n AdoptedSourceMaterialization,\n AdoptSourceMaterializationInput,\n AssertSourceMaterializationExecutionInput,\n BeginSourceMaterializationInput,\n CleanupTerminalSourceMaterializationsInput,\n CleanupTerminalSourceMaterializationsResult,\n GetActiveOntologySourceInput,\n ListActiveOntologySourcesInput,\n MarkSourceMaterializationReadyInput,\n OntologySourceRecord,\n OntologySourceStorage,\n PurgeAbandonedSourceMaterializationsInput,\n StageSourceRowsInput,\n StageSourceRowsResult,\n} from \"@sixb/core/storage\"\nimport { yieldSqliteEventLoop } from \"../transactions\"\nimport {\n assertNonblank,\n assertNonnegativeInteger,\n assertPositiveInteger,\n assertProjectionExecution,\n assertTimestamp,\n canonicalJson,\n type SqliteOntologySourceAssertionRow,\n type SqliteOntologySourceRow,\n type SqliteRootOperation,\n sourceAssertion,\n sourceRecord,\n} from \"./shared\"\nimport { cleanupSourceVersions, purgeAbandonedSourceVersions } from \"./source-cleanup\"\nimport {\n assertSourceRootCoverage,\n SOURCE_ASSERTION_COLUMNS,\n stageSourceRoots,\n} from \"./source-roots\"\n\nexport class SqliteOntologySourceStorage implements OntologySourceStorage {\n constructor(\n private readonly db: Database,\n private readonly runRootOperation: SqliteRootOperation\n ) {}\n\n async beginMaterialization(\n input: BeginSourceMaterializationInput\n ): Promise<OntologySourceRecord> {\n return this.runRootOperation(() => {\n assertBeginInput(input)\n this.assertExecution(input, sourceMaterializationIdentity(input))\n const existing = this.getManifest(\n input.projectId,\n input.source.projectionId,\n input.materializationId\n )\n if (existing) {\n if (isExactStagingManifest(sourceRecord(existing), input)) return sourceRecord(existing)\n throw sourceConflict(\n `Source materialization '${input.materializationId}' already exists with different identity or state.`\n )\n }\n\n const candidate = this.db\n .query(\n `\n SELECT 1\n FROM ontology_sources\n WHERE project_id = ? AND projection_run_id = ?\n AND status IN ('staging', 'ready')\n LIMIT 1\n `\n )\n .get(input.projectId, input.execution.projectionRunId)\n if (candidate) {\n throw sourceConflict(\n `Projection run '${input.execution.projectionRunId}' already has a nonterminal source materialization; adopt it before beginning another.`\n )\n }\n\n this.db\n .query(\n `\n INSERT INTO ontology_sources (\n project_id, source_id, materialization_id, projection_run_id,\n projection_kind, protocol, status, execution_token,\n dataset_id, dataset_version_id, dataset_version_created_at,\n projection_revision, ownership_hash, ontology_revision,\n root_count, assertion_count, created_at, ready_at, activated_at,\n terminal_at, last_commit_id, updated_at, base_materialization_id, base_commit_id\n ) VALUES (?, ?, ?, ?, ?, 'replacement', 'staging', ?, ?, ?, ?, ?, ?, ?,\n NULL, NULL, ?, NULL, NULL, NULL, NULL, ?, ?, ?)\n `\n )\n .run(\n input.projectId,\n input.source.projectionId,\n input.materializationId,\n input.execution.projectionRunId,\n input.projectionKind,\n input.execution.executionToken,\n input.datasetVersion.datasetId,\n input.datasetVersion.versionId,\n input.datasetVersion.createdAt,\n input.projectionRevision,\n input.ownershipHash,\n input.ontologyRevision,\n input.createdAt,\n input.createdAt,\n input.base?.materializationId ?? null,\n input.base?.lastCommitId ?? null\n )\n return sourceRecord(\n this.requireManifest(input.projectId, input.source.projectionId, input.materializationId)\n )\n })\n }\n\n async stageRows(input: StageSourceRowsInput): Promise<StageSourceRowsResult> {\n const result = await this.runRootOperation(() => {\n assertWriteIdentity(input)\n this.assertExecution(input)\n const manifest = this.requireManifest(\n input.projectId,\n input.source.projectionId,\n input.materializationId\n )\n assertSourceCandidateOwner(sourceRecord(manifest), input.execution)\n if (manifest.status !== \"staging\") {\n throw sourceConflict(\n `Source materialization '${input.materializationId}' is '${manifest.status}' and cannot accept rows.`\n )\n }\n\n const rows = sourceStageRows(manifest.projection_kind, input.rows)\n const existing = this.findStageRows(manifest, rows)\n const { pending, unchanged } = reconcileSourceStageRows(rows, existing)\n stageSourceRoots(this.db, manifest, input)\n this.insertStageRows(manifest, pending)\n return { inserted: pending.length, unchanged }\n })\n await yieldSqliteEventLoop()\n return result\n }\n\n async markReady(input: MarkSourceMaterializationReadyInput): Promise<OntologySourceRecord> {\n return this.runRootOperation(() => {\n assertWriteIdentity(input)\n assertTimestamp(input.readyAt, \"Source readyAt\", true)\n assertNonnegativeInteger(input.rootCount, \"Source root count\")\n assertNonnegativeInteger(input.assertionCount, \"Source assertion count\")\n this.assertExecution(input)\n const manifest = this.requireManifest(\n input.projectId,\n input.source.projectionId,\n input.materializationId\n )\n assertSourceCandidateOwner(sourceRecord(manifest), input.execution)\n if (manifest.status === \"ready\") {\n if (\n manifest.root_count === input.rootCount &&\n manifest.assertion_count === input.assertionCount &&\n manifest.ready_at === input.readyAt\n ) {\n return sourceRecord(manifest)\n }\n throw sourceConflict(\n `Source materialization '${input.materializationId}' was marked ready with different counts or time.`\n )\n }\n if (manifest.status !== \"staging\") {\n throw sourceConflict(\n `Source materialization '${input.materializationId}' cannot transition from '${manifest.status}' to 'ready'.`\n )\n }\n if (input.readyAt < manifest.created_at) {\n throw new MaterializationValidationError(\"Source readyAt cannot precede source createdAt.\")\n }\n this.assertReadyState(manifest, input.rootCount, input.assertionCount)\n const result = this.db\n .query(\n `\n UPDATE ontology_sources\n SET status = 'ready', root_count = ?, assertion_count = ?, ready_at = ?, updated_at = ?\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?\n AND status = 'staging' AND execution_token = ?\n `\n )\n .run(\n input.rootCount,\n input.assertionCount,\n input.readyAt,\n input.readyAt,\n input.projectId,\n input.source.projectionId,\n input.materializationId,\n input.execution.executionToken\n )\n if (result.changes !== 1) {\n throw sourceConflict(`Source materialization '${input.materializationId}' changed.`)\n }\n return sourceRecord(\n this.requireManifest(input.projectId, input.source.projectionId, input.materializationId)\n )\n })\n }\n\n async getActive(input: GetActiveOntologySourceInput): Promise<OntologySourceRecord | null> {\n return this.runRootOperation(() => {\n assertProjectAndSource(input)\n const row = this.db\n .query(\n `\n SELECT * FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND status = 'active'\n `\n )\n .get(input.projectId, input.source.projectionId) as SqliteOntologySourceRow | null\n return row ? sourceRecord(row) : null\n })\n }\n\n async listActive(\n input: ListActiveOntologySourcesInput\n ): Promise<readonly ActiveOntologySource[]> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Source project id\")\n\n // Served by the partial index on active sources.\n const rows = this.db\n .query(\n `\n SELECT source_id, dataset_id, dataset_version_id, dataset_version_created_at,\n projection_revision\n FROM ontology_sources\n WHERE project_id = ? AND status = 'active'\n `\n )\n .all(input.projectId) as ActiveSourceRow[]\n\n return rows.map((row) => ({\n source: { projectionId: row.source_id },\n datasetVersion: {\n datasetId: row.dataset_id,\n versionId: row.dataset_version_id,\n createdAt: row.dataset_version_created_at,\n },\n projectionRevision: row.projection_revision,\n }))\n })\n }\n\n async adopt(\n input: AdoptSourceMaterializationInput\n ): Promise<AdoptedSourceMaterialization | null> {\n return this.runRootOperation(() => {\n assertProjectAndSource(input)\n assertExecutionIdentity(input.execution.projectionRunId, input.execution.executionToken)\n assertTimestamp(input.adoptedAt, \"Source adoptedAt\", true)\n this.assertExecution(input)\n const candidate = this.findRunCandidate(input)\n if (!candidate) return null\n // Workers' clocks differ; adoption never moves the record back in time.\n const changed = this.db\n .query(\n `\n UPDATE ontology_sources SET execution_token = ?, updated_at = MAX(updated_at, ?)\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?\n AND status IN ('staging', 'ready')\n `\n )\n .run(\n input.execution.executionToken,\n input.adoptedAt,\n candidate.project_id,\n candidate.source_id,\n candidate.materialization_id\n ).changes\n if (changed !== 1) {\n throw sourceConflict(`Source materialization '${candidate.materialization_id}' changed.`)\n }\n const adopted = this.requireManifest(\n candidate.project_id,\n candidate.source_id,\n candidate.materialization_id\n )\n return {\n record: sourceRecord(adopted),\n resumeStagingOrdinal:\n adopted.status === \"ready\" ? Number(adopted.root_count) : this.lastStagedOrdinal(adopted),\n }\n })\n }\n\n async abandon(input: AbandonSourceMaterializationCandidateInput): Promise<OntologySourceRecord>\n async abandon(input: AbandonRunSourceMaterializationInput): Promise<OntologySourceRecord | null>\n async abandon(input: AbandonSourceMaterializationInput): Promise<OntologySourceRecord | null> {\n return this.runRootOperation(() => {\n assertProjectAndSource(input)\n assertExecutionIdentity(input.execution.projectionRunId, input.execution.executionToken)\n assertTimestamp(input.abandonedAt, \"Source abandonedAt\", true)\n this.assertExecution(input)\n if (input.kind === \"candidate\") return this.abandonCandidate(input)\n const candidate = this.findRunCandidate(input)\n return candidate ? this.transitionToAbandoned(candidate, input.abandonedAt) : null\n })\n }\n\n async cleanupTerminal(\n input: CleanupTerminalSourceMaterializationsInput\n ): Promise<CleanupTerminalSourceMaterializationsResult> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Terminal source cleanup project id\")\n assertTimestamp(input.terminalBefore, \"Terminal source cleanup cutoff\", true)\n assertPositiveInteger(input.limit, \"Terminal source cleanup limit\")\n return cleanupSourceVersions(this.db, input)\n })\n }\n\n async purgeAbandoned(\n input: PurgeAbandonedSourceMaterializationsInput\n ): Promise<CleanupTerminalSourceMaterializationsResult> {\n return this.runRootOperation(() => {\n assertNonblank(input.projectId, \"Abandoned source purge project id\")\n assertPositiveInteger(input.limit, \"Abandoned source purge limit\")\n return purgeAbandonedSourceVersions(this.db, input)\n })\n }\n\n private abandonCandidate(\n input: AbandonSourceMaterializationCandidateInput\n ): OntologySourceRecord {\n const manifest = this.requireManifest(\n input.projectId,\n input.source.projectionId,\n input.materializationId\n )\n if (manifest.status === \"abandoned\") {\n if (\n manifest.projection_run_id === input.execution.projectionRunId &&\n manifest.terminal_at === input.abandonedAt\n ) {\n return sourceRecord(manifest)\n }\n throw sourceConflict(\n `Source materialization '${input.materializationId}' was abandoned by another execution or at another time.`\n )\n }\n assertSourceCandidateOwner(sourceRecord(manifest), input.execution)\n return this.transitionToAbandoned(manifest, input.abandonedAt)\n }\n\n /** The run's one staging or ready candidate, whichever execution staged it. */\n private findRunCandidate(input: {\n readonly projectId: string\n readonly source: { readonly projectionId: string }\n readonly execution: { readonly projectionRunId: string }\n }): SqliteOntologySourceRow | null {\n const candidates = this.db\n .query(\n `\n SELECT * FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND projection_run_id = ?\n AND status IN ('staging', 'ready')\n `\n )\n .all(\n input.projectId,\n input.source.projectionId,\n input.execution.projectionRunId\n ) as SqliteOntologySourceRow[]\n if (candidates.length > 1) {\n throw sourceConflict(\n `Projection run '${input.execution.projectionRunId}' has multiple nonterminal source materializations.`\n )\n }\n return candidates[0] ?? null\n }\n\n private lastStagedOrdinal(manifest: SqliteOntologySourceRow): number {\n const last = this.db\n .query(\n \"SELECT MAX(staging_ordinal) AS ordinal FROM ontology_source_roots WHERE version_id = ?\"\n )\n .get(manifest.version_id) as {\n readonly ordinal: number | null\n } | null\n return last?.ordinal ?? 0\n }\n\n private transitionToAbandoned(\n manifest: SqliteOntologySourceRow,\n abandonedAt: string\n ): OntologySourceRecord {\n if (\n abandonedAt < manifest.created_at ||\n (manifest.ready_at !== null && abandonedAt < manifest.ready_at)\n ) {\n throw new MaterializationValidationError(\n \"Source abandonedAt cannot precede source creation or readiness.\"\n )\n }\n const changed = this.db\n .query(\n `\n UPDATE ontology_sources\n SET status = 'abandoned', execution_token = NULL, terminal_at = ?, updated_at = ?\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?\n AND status IN ('staging', 'ready')\n `\n )\n .run(\n abandonedAt,\n abandonedAt,\n manifest.project_id,\n manifest.source_id,\n manifest.materialization_id\n ).changes\n if (changed !== 1) {\n throw sourceConflict(\n `Source materialization '${manifest.materialization_id}' cannot transition to 'abandoned'.`\n )\n }\n // Its roots were never live and stay unpublished; purging removes them with the version.\n return sourceRecord(\n this.requireManifest(manifest.project_id, manifest.source_id, manifest.materialization_id)\n )\n }\n\n private assertReadyState(\n manifest: SqliteOntologySourceRow,\n rootCount: number,\n assertionCount: number\n ): void {\n const counts = this.db\n .query(\n `\n SELECT (SELECT COUNT(*) FROM ontology_source_roots AS roots\n JOIN ontology_source_rows AS rows ON rows.root_id = roots.id\n WHERE roots.version_id = ?1) AS assertions,\n COUNT(*) AS roots, COUNT(DISTINCT staging_ordinal) AS ordinals,\n MIN(staging_ordinal) AS min_ordinal, MAX(staging_ordinal) AS max_ordinal\n FROM ontology_source_roots\n WHERE version_id = ?1\n `\n )\n .get(manifest.version_id) as {\n assertions: number\n roots: number\n ordinals: number\n min_ordinal: number | null\n max_ordinal: number | null\n }\n if (\n counts.assertions !== assertionCount ||\n counts.roots !== rootCount ||\n counts.ordinals !== rootCount ||\n (rootCount > 0 && (counts.min_ordinal !== 0 || counts.max_ordinal !== rootCount - 1))\n ) {\n throw new MaterializationValidationError(\n \"Source ready counts do not match the staged roots and assertions.\"\n )\n }\n assertSourceRootCoverage(this.db, manifest)\n // Roots store only their canonical key; compare its parts with each row's typed identity.\n const invalid = this.db\n .query(\n manifest.projection_kind === \"link\"\n ? `\n SELECT roots.root_key\n FROM ontology_source_roots AS roots\n JOIN ontology_source_rows AS rows ON rows.root_id = roots.id\n WHERE roots.version_id = ?\n GROUP BY roots.id\n HAVING COUNT(*) <> 1\n OR MAX(json_extract(roots.root_key, '$[0]') <> 'link')\n OR MAX(rows.entity_kind <> 'link')\n OR MAX(rows.source_type_id <> json_extract(roots.root_key, '$[1]')\n OR rows.source_primary_id <> json_extract(roots.root_key, '$[2]')\n OR rows.link_id <> json_extract(roots.root_key, '$[3]')\n OR rows.target_type_id <> json_extract(roots.root_key, '$[4]')\n OR rows.target_primary_id <> json_extract(roots.root_key, '$[5]'))\n LIMIT 1\n `\n : `\n SELECT roots.root_key\n FROM ontology_source_roots AS roots\n JOIN ontology_source_rows AS rows ON rows.root_id = roots.id\n WHERE roots.version_id = ?\n GROUP BY roots.id\n HAVING MAX(json_extract(roots.root_key, '$[0]') <> 'object')\n OR SUM(rows.entity_kind = 'object'\n AND rows.object_type_id = json_extract(roots.root_key, '$[1]')\n AND rows.primary_id = json_extract(roots.root_key, '$[2]')) <> 1\n OR SUM(\n (rows.entity_kind = 'object' AND (\n rows.object_type_id <> json_extract(roots.root_key, '$[1]')\n OR rows.primary_id <> json_extract(roots.root_key, '$[2]')))\n OR (rows.entity_kind = 'link' AND (\n rows.source_type_id <> json_extract(roots.root_key, '$[1]')\n OR rows.source_primary_id <> json_extract(roots.root_key, '$[2]')))\n ) <> 0\n OR SUM(rows.entity_kind = 'link') <> COUNT(DISTINCT CASE\n WHEN rows.entity_kind = 'link'\n THEN json_array(rows.link_id, rows.target_type_id, rows.target_primary_id)\n END)\n LIMIT 1\n `\n )\n .get(manifest.version_id)\n if (invalid) {\n throw new MaterializationValidationError(\n manifest.projection_kind === \"link\"\n ? \"Link projection roots must contain exactly their matching link assertion.\"\n : \"Object projection roots must contain exactly their matching object assertion plus links sourced from that root.\"\n )\n }\n }\n\n /** Already staged assertions sharing a root or an ordinal with `rows`. */\n private findStageRows(\n manifest: SqliteOntologySourceRow,\n rows: readonly SourceStageRow[]\n ): readonly SourceStageRow[] {\n if (rows.length === 0) return []\n const rootKeys = [...new Set(rows.map((row) => row.rootKey))]\n const ordinals = [...new Set(rows.map((row) => row.row.stagingOrdinal))]\n // Two keyed lookups: an OR over both columns scans every root of the version per batch.\n const existing = this.db\n .query(\n `\n WITH selected AS (\n SELECT roots.id FROM json_each(?2) AS requested\n CROSS JOIN ontology_source_roots AS roots\n ON roots.version_id = ?1 AND roots.root_key = CAST(requested.value AS TEXT)\n UNION\n SELECT roots.id FROM json_each(?3) AS requested\n CROSS JOIN ontology_source_roots AS roots\n ON roots.version_id = ?1 AND roots.staging_ordinal = CAST(requested.value AS INTEGER)\n )\n SELECT ${SOURCE_ASSERTION_COLUMNS} FROM selected\n CROSS JOIN ontology_source_roots AS roots ON roots.id = selected.id\n CROSS JOIN ontology_sources AS versions ON versions.version_id = roots.version_id\n CROSS JOIN ontology_source_rows AS rows ON rows.root_id = roots.id\n `\n )\n .all(\n manifest.version_id,\n JSON.stringify(rootKeys),\n JSON.stringify(ordinals)\n ) as SqliteOntologySourceAssertionRow[]\n return existing.map((row) => sourceStageRow(sourceAssertion(row)))\n }\n\n private insertStageRows(\n manifest: SqliteOntologySourceRow,\n rows: readonly SourceStageRow[]\n ): void {\n if (rows.length === 0) return\n const payload = rows.map(({ rootKey, row }) => {\n const entity = entityColumns(row.assertion)\n return {\n rootKey,\n entityKind: row.assertion.kind,\n objectTypeId: entity.objectTypeId,\n primaryId: entity.primaryId,\n sourceTypeId: entity.sourceTypeId,\n sourcePrimaryId: entity.sourcePrimaryId,\n linkId: entity.linkId,\n targetTypeId: entity.targetTypeId,\n targetPrimaryId: entity.targetPrimaryId,\n payload: sourceAssertionPayload(row.assertion),\n }\n })\n const inserted = this.db\n .query(\n `\n WITH staged(value) AS (SELECT value FROM json_each(?))\n INSERT INTO ontology_source_rows (\n root_id, entity_kind, object_type_id, primary_id,\n source_type_id, source_primary_id, link_id, target_type_id, target_primary_id, payload\n )\n SELECT roots.id, json_extract(value, '$.entityKind'),\n json_extract(value, '$.objectTypeId'), json_extract(value, '$.primaryId'),\n json_extract(value, '$.sourceTypeId'), json_extract(value, '$.sourcePrimaryId'),\n json_extract(value, '$.linkId'), json_extract(value, '$.targetTypeId'),\n json_extract(value, '$.targetPrimaryId'), json_extract(value, '$.payload')\n FROM staged\n CROSS JOIN ontology_source_roots AS roots\n ON roots.version_id = ? AND roots.root_key = json_extract(value, '$.rootKey')\n `\n )\n .run(canonicalJson(payload), manifest.version_id).changes\n if (inserted !== rows.length) {\n throw sourceConflict(\"Staged source rows do not all belong to a staged root.\")\n }\n }\n\n private assertExecution(\n input: {\n readonly projectId: string\n readonly source: { readonly projectionId: string }\n readonly execution: { readonly projectionRunId: string; readonly executionToken: string }\n },\n identity?: AssertSourceMaterializationExecutionInput[\"identity\"]\n ): void {\n assertProjectionExecution(this.db, {\n projectId: input.projectId,\n sourceId: input.source.projectionId,\n projectionRunId: input.execution.projectionRunId,\n executionToken: input.execution.executionToken,\n ...(identity ? { identity } : {}),\n })\n }\n\n private getManifest(\n projectId: string,\n sourceId: string,\n materializationId: string\n ): SqliteOntologySourceRow | null {\n return this.db\n .query(\n `\n SELECT * FROM ontology_sources\n WHERE project_id = ? AND source_id = ? AND materialization_id = ?\n `\n )\n .get(projectId, sourceId, materializationId) as SqliteOntologySourceRow | null\n }\n\n private requireManifest(\n projectId: string,\n sourceId: string,\n materializationId: string\n ): SqliteOntologySourceRow {\n const row = this.getManifest(projectId, sourceId, materializationId)\n if (!row) throw sourceConflict(`Source materialization '${materializationId}' does not exist.`)\n return row\n }\n}\n\ntype ActiveSourceRow = Pick<\n SqliteOntologySourceRow,\n | \"source_id\"\n | \"dataset_id\"\n | \"dataset_version_id\"\n | \"dataset_version_created_at\"\n | \"projection_revision\"\n>\n",
59
65
  "import type { Database } from \"bun:sqlite\"\nimport type {\n CleanupTerminalSourceMaterializationsInput,\n CleanupTerminalSourceMaterializationsResult,\n PurgeAbandonedSourceMaterializationsInput,\n} from \"@sixb/core/storage\"\n\n/**\n * A version outlives its replacement plan, which references it: the next version may take a\n * deleted one's id, and would then resume the plan left under it.\n */\nconst PLAN_PURGED = `NOT EXISTS (\n SELECT 1 FROM ontology_replacement_plans AS plans WHERE plans.version_id = versions.version_id\n)`\n\n/**\n * Superseded versions can still hold live roots (a delta keeps unchanged roots where they were),\n * so they are cleaned root by root once retired. An abandoned candidate was never published:\n * everything it holds goes, one whole version at a time, each delete on its own version prefix.\n */\nexport function purgeAbandonedSourceVersions(\n db: Database,\n input: PurgeAbandonedSourceMaterializationsInput\n): CleanupTerminalSourceMaterializationsResult {\n let remaining = input.limit\n let rowsDeleted = 0\n let materializationsDeleted = 0\n const nextCandidate = db.query(`\n SELECT version_id FROM ontology_sources AS versions\n WHERE project_id = ? AND status = 'abandoned' AND ${PLAN_PURGED}\n ORDER BY terminal_at, source_id, materialization_id LIMIT 1\n `)\n const deleteRows = db.query(`DELETE FROM ontology_source_rows WHERE rowid IN (\n SELECT rows.rowid FROM ontology_source_roots AS roots\n CROSS JOIN ontology_source_rows AS rows ON rows.root_id = roots.id\n WHERE roots.version_id = ? LIMIT ?)`)\n const deleteRoots = db.query(`DELETE FROM ontology_source_roots WHERE id IN (\n SELECT id FROM ontology_source_roots WHERE version_id = ? LIMIT ?)`)\n const deleteManifest = db.query(\n \"DELETE FROM ontology_sources WHERE version_id = ? AND status = 'abandoned'\"\n )\n while (remaining > 0) {\n const candidate = nextCandidate.get(input.projectId) as { readonly version_id: number } | null\n if (!candidate) break\n const rows = deleteRows.run(candidate.version_id, remaining).changes\n rowsDeleted += rows\n remaining -= rows\n if (remaining === 0) break\n const roots = deleteRoots.run(candidate.version_id, remaining).changes\n rowsDeleted += roots\n remaining -= roots\n if (remaining === 0) break\n const manifest = deleteManifest.run(candidate.version_id).changes\n if (manifest === 0) break\n materializationsDeleted += manifest\n remaining -= manifest\n }\n return { rowsDeleted, materializationsDeleted }\n}\n\nexport function cleanupSourceVersions(\n db: Database,\n input: CleanupTerminalSourceMaterializationsInput\n): CleanupTerminalSourceMaterializationsResult {\n let remaining = input.limit\n const retired = `roots.project_id = ? AND roots.retired_at < ? AND versions.status = 'superseded'`\n let rowsDeleted = db\n .query(`DELETE FROM ontology_source_rows WHERE rowid IN (\n SELECT rows.rowid FROM ontology_source_roots AS roots\n JOIN ontology_sources AS versions ON versions.version_id = roots.version_id\n CROSS JOIN ontology_source_rows AS rows ON rows.root_id = roots.id\n WHERE ${retired}\n ORDER BY roots.retired_at, roots.id\n LIMIT ?\n )`)\n .run(input.projectId, input.terminalBefore, remaining).changes\n remaining -= rowsDeleted\n if (remaining > 0) {\n const removed = db\n .query(`DELETE FROM ontology_source_roots WHERE id IN (\n SELECT roots.id FROM ontology_source_roots AS roots\n JOIN ontology_sources AS versions ON versions.version_id = roots.version_id\n WHERE ${retired}\n AND NOT EXISTS (SELECT 1 FROM ontology_source_rows AS rows WHERE rows.root_id = roots.id)\n ORDER BY roots.retired_at, roots.id LIMIT ?\n ) RETURNING version_id`)\n .all(input.projectId, input.terminalBefore, remaining) as { readonly version_id: number }[]\n // Each version's root_count follows its roots down, so a drained version is found by index.\n const counts = new Map<number, number>()\n for (const root of removed) counts.set(root.version_id, (counts.get(root.version_id) ?? 0) + 1)\n const drain = db.query(\n \"UPDATE ontology_sources SET root_count = root_count - ? WHERE version_id = ?\"\n )\n // These commit with the delete: every ontology storage call runs in the caller's BEGIN IMMEDIATE.\n for (const [versionId, count] of counts) drain.run(count, versionId)\n rowsDeleted += removed.length\n remaining -= removed.length\n }\n const materializationsDeleted =\n remaining === 0\n ? 0\n : db\n .query(`DELETE FROM ontology_sources WHERE version_id IN (\n SELECT versions.version_id FROM ontology_sources AS versions\n WHERE project_id = ? AND status = 'superseded' AND root_count = 0 AND terminal_at < ?\n AND ${PLAN_PURGED}\n ORDER BY terminal_at, source_id, materialization_id LIMIT ?\n )`)\n .run(input.projectId, input.terminalBefore, remaining).changes\n return { rowsDeleted, materializationsDeleted }\n}\n",
60
66
  "import type { Database } from \"bun:sqlite\"\nimport { parseSixbFailure } from \"@sixb/core/internal/errors\"\nimport {\n type MaterializationSession,\n type OntologyVectorIndexingStorage,\n VECTOR_INDEXING_FAILURE_CODES,\n type VectorIndexingRequest,\n type VectorIndexingWork,\n} from \"@sixb/core/storage\"\nimport type { SqliteRootOperation } from \"./shared\"\n\ninterface WorkRow {\n batch_id: string | null\n request: string\n status: VectorIndexingWork[\"status\"]\n available_at: string\n values_json: string | null\n error: string | null\n}\nexport class SqliteVectorIndexingStorage implements OntologyVectorIndexingStorage {\n constructor(\n private readonly db: Database,\n private readonly run: SqliteRootOperation,\n private readonly assertSession: (session: MaterializationSession, projectId: string) => void\n ) {}\n async schedule(input: Parameters<OntologyVectorIndexingStorage[\"schedule\"]>[0]) {\n this.assertSession(input.session, input.projectId)\n for (const ref of input.deleted)\n this.db\n .query(\n `DELETE FROM object_vector_indexing WHERE project_id = ? AND object_type_id = ? AND primary_id = ?`\n )\n .run(input.projectId, ref.objectTypeId, ref.primaryId)\n const insert =\n this.db.query(`INSERT INTO object_vector_indexing (project_id, id, object_type_id, primary_id, profile, batch_id, request, status, available_at, dispatch_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)\n ON CONFLICT (project_id, object_type_id, primary_id, profile) DO UPDATE SET id = excluded.id, batch_id = excluded.batch_id, request = excluded.request, status = 'pending', available_at = excluded.available_at, dispatch_at = excluded.dispatch_at, values_json = NULL, error = NULL`)\n for (const { batchId, ...request } of input.requests)\n insert.run(\n input.projectId,\n request.id,\n request.ref.objectTypeId,\n request.ref.primaryId,\n request.profile,\n batchId ?? null,\n JSON.stringify(request),\n input.availableAt,\n input.availableAt\n )\n }\n async complete(input: Parameters<OntologyVectorIndexingStorage[\"complete\"]>[0]) {\n this.assertSession(input.session, input.projectId)\n const remove = this.db.query(\n `DELETE FROM object_vector_indexing WHERE project_id = ? AND object_type_id = ? AND primary_id = ? AND profile = ? AND json_extract(request, '$.configuration') = ? AND json_extract(request, '$.sourceFingerprint') = ?`\n )\n for (const entry of input.entries) {\n remove.run(\n input.projectId,\n entry.ref.objectTypeId,\n entry.ref.primaryId,\n entry.profile,\n entry.configuration,\n entry.sourceFingerprint\n )\n }\n }\n\n async dispatched(input: Parameters<OntologyVectorIndexingStorage[\"dispatched\"]>[0]) {\n await this.run(() => {\n const update = this.db.query(\n `UPDATE object_vector_indexing SET dispatch_at = ? WHERE project_id = ? AND id = ?`\n )\n for (const id of input.ids) update.run(input.nextDispatchAt, input.projectId, id)\n })\n }\n async get(input: Parameters<OntologyVectorIndexingStorage[\"get\"]>[0]) {\n return this.run(() => {\n const row = this.db\n .query<WorkRow, [string, string]>(\n `SELECT batch_id, request, status, available_at, values_json, error FROM object_vector_indexing WHERE project_id = ? AND id = ?`\n )\n .get(input.projectId, input.id)\n return row ? decode(row) : null\n })\n }\n async getBatch(input: Parameters<OntologyVectorIndexingStorage[\"getBatch\"]>[0]) {\n return this.run(() =>\n this.db\n .query<WorkRow, [string, string]>(`\n SELECT batch_id, request, status, available_at, values_json, error FROM object_vector_indexing\n WHERE project_id = ? AND batch_id = ? ORDER BY id`)\n .all(input.projectId, input.batchId)\n .map(decode)\n )\n }\n\n async getBatchMember(input: Parameters<OntologyVectorIndexingStorage[\"getBatchMember\"]>[0]) {\n return this.run(() => {\n const row = this.db\n .query<WorkRow, [string, string, string, string, string]>(`\n SELECT batch_id, request, status, available_at, values_json, error\n FROM object_vector_indexing WHERE project_id = ? AND object_type_id = ?\n AND primary_id = ? AND profile = ? AND batch_id = ?`)\n .get(\n input.projectId,\n input.ref.objectTypeId,\n input.ref.primaryId,\n input.profile,\n input.batchId\n )\n return row ? decode(row) : null\n })\n }\n\n async updateBatch(input: Parameters<OntologyVectorIndexingStorage[\"updateBatch\"]>[0]) {\n return this.run(() =>\n this.db.transaction(() => {\n const status = this.db.query<{ status: string }, [string, string]>(\n \"SELECT status FROM object_vector_indexing WHERE project_id = ? AND id = ?\"\n )\n if (\n input.requireAll &&\n input.updates.some(\n (update) => status.get(input.projectId, update.id)?.status !== update.expectedStatus\n )\n )\n return false\n const updateRow = this.db.query(`UPDATE object_vector_indexing\n SET status = ?, available_at = ?, values_json = COALESCE(?, values_json), error = ?\n WHERE project_id = ? AND id = ? AND status = ?`)\n for (const update of input.updates)\n updateRow.run(\n update.status,\n update.availableAt,\n update.values ? JSON.stringify(update.values) : null,\n update.error ? JSON.stringify(update.error) : null,\n input.projectId,\n update.id,\n update.expectedStatus\n )\n return true\n })()\n )\n }\n\n async listDue(input: Parameters<OntologyVectorIndexingStorage[\"listDue\"]>[0]) {\n return this.run(() =>\n this.db\n .query<WorkRow, [string, string, number]>(\n `SELECT batch_id, request, status, available_at, NULL AS values_json, error FROM object_vector_indexing WHERE project_id = ? AND status <> 'failed' AND dispatch_at <= ? ORDER BY dispatch_at, id LIMIT ?`\n )\n .all(input.projectId, input.now, input.limit)\n .map(decode)\n )\n }\n async update(input: Parameters<OntologyVectorIndexingStorage[\"update\"]>[0]) {\n return this.run(\n () =>\n this.db\n .query(\n `UPDATE object_vector_indexing SET status = ?, available_at = ?, values_json = COALESCE(?, values_json), error = ? WHERE project_id = ? AND id = ? AND status = ?`\n )\n .run(\n input.status,\n input.availableAt,\n input.values ? JSON.stringify(input.values) : null,\n input.error ? JSON.stringify(input.error) : null,\n input.projectId,\n input.id,\n input.expectedStatus\n ).changes === 1\n )\n }\n async remove(input: Parameters<OntologyVectorIndexingStorage[\"remove\"]>[0]) {\n await this.run(() => {\n this.db\n .query(`DELETE FROM object_vector_indexing WHERE project_id = ? AND id = ?`)\n .run(input.projectId, input.id)\n })\n }\n}\nfunction decode(row: WorkRow): VectorIndexingWork {\n const request = JSON.parse(row.request) as VectorIndexingRequest\n return {\n ...request,\n ...(row.batch_id ? { batchId: row.batch_id } : {}),\n status: row.status,\n availableAt: row.available_at,\n ...(row.values_json ? { values: JSON.parse(row.values_json) as number[] } : {}),\n ...(row.error\n ? {\n error: parseSixbFailure(row.error, VECTOR_INDEXING_FAILURE_CODES),\n }\n : {}),\n }\n}\n",
61
67
  "import type { Database } from \"bun:sqlite\"\nimport { MaterializationConflictError } from \"@sixb/core/internal/materialization\"\nimport type {\n MaterializationSession,\n ObjectVectorState,\n OntologyVectorStorage,\n} from \"@sixb/core/storage\"\nimport { encodeSqliteVector } from \"../vector-encoding\"\nimport type { SqliteRootOperation } from \"./shared\"\n\ninterface VectorMetadataRow {\n readonly profile: string\n readonly configuration: string\n readonly source: string\n readonly source_fingerprint: string\n readonly last_commit_id: string\n}\n\nexport class SqliteOntologyVectorStorage implements OntologyVectorStorage {\n constructor(\n private readonly db: Database,\n private readonly runRootOperation: SqliteRootOperation,\n private readonly assertSession: (\n session: MaterializationSession,\n projectId: string,\n commitId?: string\n ) => void\n ) {}\n\n async list(\n input: Parameters<OntologyVectorStorage[\"list\"]>[0]\n ): Promise<readonly ObjectVectorState[]> {\n return this.runRootOperation(() => {\n const rows = this.db\n .query<VectorMetadataRow, [string, string, string]>(`\n SELECT profile, configuration, source, source_fingerprint, last_commit_id\n FROM object_vectors\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?\n ORDER BY profile\n `)\n .all(input.projectId, input.ref.objectTypeId, input.ref.primaryId)\n return rows.map((row) => ({\n ref: { ...input.ref },\n profile: row.profile,\n configuration: row.configuration,\n source: JSON.parse(row.source) as string[],\n sourceFingerprint: row.source_fingerprint,\n lastCommitId: row.last_commit_id,\n }))\n })\n }\n\n async listBatch(\n input: Parameters<OntologyVectorStorage[\"listBatch\"]>[0]\n ): Promise<readonly ObjectVectorState[]> {\n if (!input.refs.length) return []\n return this.runRootOperation(() => {\n // Keep the bounded request set first so SQLite probes the composite object index.\n const rows = this.db\n .query<\n VectorMetadataRow & { object_type_id: string; primary_id: string },\n [string, string]\n >(`\n WITH requested AS (\n SELECT DISTINCT json_extract(value, '$.objectTypeId') AS object_type_id,\n json_extract(value, '$.primaryId') AS primary_id FROM json_each(?)\n )\n SELECT stored.object_type_id, stored.primary_id, stored.profile, stored.configuration,\n stored.source, stored.source_fingerprint, stored.last_commit_id\n FROM requested CROSS JOIN object_vectors AS stored\n WHERE stored.project_id = ? AND stored.object_type_id = requested.object_type_id\n AND stored.primary_id = requested.primary_id\n ORDER BY stored.object_type_id, stored.primary_id, stored.profile\n `)\n .all(JSON.stringify(input.refs), input.projectId)\n return rows.map((row) => ({\n ref: { objectTypeId: row.object_type_id, primaryId: row.primary_id },\n profile: row.profile,\n configuration: row.configuration,\n source: JSON.parse(row.source) as string[],\n sourceFingerprint: row.source_fingerprint,\n lastCommitId: row.last_commit_id,\n }))\n })\n }\n\n async removeBatch(input: Parameters<OntologyVectorStorage[\"removeBatch\"]>[0]): Promise<void> {\n this.assertSession(input.session, input.projectId)\n if (!input.entries.length) return\n const { changes } = this.db\n .query(`\n DELETE FROM object_vectors WHERE rowid IN (\n SELECT stored.rowid FROM json_each(?) AS requested CROSS JOIN object_vectors AS stored\n WHERE stored.project_id = ? AND stored.object_type_id = json_extract(requested.value, '$.ref.objectTypeId')\n AND stored.primary_id = json_extract(requested.value, '$.ref.primaryId')\n AND stored.profile = json_extract(requested.value, '$.profile')\n AND stored.last_commit_id = json_extract(requested.value, '$.expectedCommitId')\n )\n `)\n .run(JSON.stringify(input.entries), input.projectId)\n if (changes !== input.entries.length) throw vectorConflict()\n }\n\n async write(input: Parameters<OntologyVectorStorage[\"write\"]>[0]): Promise<void> {\n const { value } = input\n this.assertSession(input.session, input.projectId, value.lastCommitId)\n // The Materializer validates and normalizes float32 values before this boundary.\n const embedding = encodeSqliteVector(value.values)\n const changes =\n input.expectedCommitId === null\n ? this.db\n .query(`\n INSERT INTO object_vectors (\n project_id, object_type_id, primary_id, profile,\n configuration, source, source_fingerprint, embedding, last_commit_id\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT (project_id, object_type_id, primary_id, profile) DO NOTHING\n `)\n .run(\n input.projectId,\n value.ref.objectTypeId,\n value.ref.primaryId,\n value.profile,\n value.configuration,\n JSON.stringify(value.source),\n value.sourceFingerprint,\n embedding,\n value.lastCommitId\n ).changes\n : this.db\n .query(`\n UPDATE object_vectors\n SET configuration = ?, source = ?, source_fingerprint = ?, embedding = ?, last_commit_id = ?\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?\n AND profile = ? AND last_commit_id = ?\n `)\n .run(\n value.configuration,\n JSON.stringify(value.source),\n value.sourceFingerprint,\n embedding,\n value.lastCommitId,\n input.projectId,\n value.ref.objectTypeId,\n value.ref.primaryId,\n value.profile,\n input.expectedCommitId\n ).changes\n if (changes !== 1) throw vectorConflict()\n }\n\n async writeBatch(input: Parameters<OntologyVectorStorage[\"writeBatch\"]>[0]): Promise<void> {\n for (const entry of input.entries) {\n await this.write({ session: input.session, projectId: input.projectId, ...entry })\n }\n }\n\n async remove(input: Parameters<OntologyVectorStorage[\"remove\"]>[0]): Promise<void> {\n this.assertSession(input.session, input.projectId)\n const { changes } = this.db\n .query(`\n DELETE FROM object_vectors\n WHERE project_id = ? AND object_type_id = ? AND primary_id = ?\n AND profile = ? AND last_commit_id = ?\n `)\n .run(\n input.projectId,\n input.ref.objectTypeId,\n input.ref.primaryId,\n input.profile,\n input.expectedCommitId\n )\n if (changes !== 1) throw vectorConflict()\n }\n}\n\nfunction vectorConflict(): MaterializationConflictError {\n return new MaterializationConflictError(\n \"effective-state\",\n \"Vector changed since it was prepared.\"\n )\n}\n",
62
- "import type { Database } from \"bun:sqlite\"\nimport type { OntologyStorage } from \"@sixb/core/storage\"\nimport { SqliteOntologyCommitStorage } from \"./commits\"\nimport type { SqliteOntologyTransactionContext } from \"./materialization-session\"\nimport { SqliteOntologyMaterializationStorage } from \"./materializations\"\nimport { SqliteOntologyOutboxStorage } from \"./outbox\"\nimport { SqliteOntologyReplacementPlanStorage } from \"./replacement-plans\"\nimport type { SqliteRootOperation } from \"./shared\"\nimport { SqliteOntologySourceStorage } from \"./sources\"\nimport { SqliteVectorIndexingStorage } from \"./vector-indexing\"\nimport { SqliteOntologyVectorStorage } from \"./vectors\"\n\nexport class SqliteOntologyStorage implements OntologyStorage {\n readonly commits: SqliteOntologyCommitStorage\n readonly sources: SqliteOntologySourceStorage\n readonly materializations: SqliteOntologyMaterializationStorage\n readonly replacementPlans: SqliteOntologyReplacementPlanStorage\n readonly vectorIndexing: SqliteVectorIndexingStorage\n readonly vectors: SqliteOntologyVectorStorage\n readonly outbox: SqliteOntologyOutboxStorage\n\n constructor(input: {\n readonly db: Database\n readonly runRootOperation: SqliteRootOperation\n readonly transactionContext: SqliteOntologyTransactionContext | null\n }) {\n this.commits = new SqliteOntologyCommitStorage(input.db, input.runRootOperation)\n this.sources = new SqliteOntologySourceStorage(input.db, input.runRootOperation)\n this.materializations = new SqliteOntologyMaterializationStorage(\n input.db,\n input.transactionContext\n )\n this.replacementPlans = new SqliteOntologyReplacementPlanStorage(\n input.db,\n input.runRootOperation\n )\n this.vectorIndexing = new SqliteVectorIndexingStorage(\n input.db,\n input.runRootOperation,\n (session, projectId) => this.materializations.assertVectorSession(session, projectId)\n )\n this.vectors = new SqliteOntologyVectorStorage(\n input.db,\n input.runRootOperation,\n (session, projectId, commitId) =>\n this.materializations.assertVectorSession(session, projectId, commitId)\n )\n this.outbox = new SqliteOntologyOutboxStorage(input.db, input.runRootOperation)\n }\n\n deactivateSessions(): void {\n this.materializations.deactivateSessions()\n }\n}\n\nexport type { SqliteOntologyTransactionContext } from \"./materialization-session\"\n",
68
+ "import type { Database } from \"bun:sqlite\"\nimport type { OntologyStorage } from \"@sixb/core/storage\"\nimport { SqliteOntologyCommitStorage } from \"./commits\"\nimport type { SqliteOntologyTransactionContext } from \"./materialization-session\"\nimport { SqliteOntologyMaterializationStorage } from \"./materializations\"\nimport { SqliteOntologyOutboxStorage } from \"./outbox\"\nimport { SqliteOntologyReplacementPlanStorage } from \"./replacement-plans\"\nimport type { SqliteRootOperation } from \"./shared\"\nimport { SqliteOntologySourceStorage } from \"./sources\"\nimport { SqliteOntologyUniqueValueStorage } from \"./unique-values\"\nimport { SqliteVectorIndexingStorage } from \"./vector-indexing\"\nimport { SqliteOntologyVectorStorage } from \"./vectors\"\n\nexport class SqliteOntologyStorage implements OntologyStorage {\n readonly commits: SqliteOntologyCommitStorage\n readonly sources: SqliteOntologySourceStorage\n readonly materializations: SqliteOntologyMaterializationStorage\n readonly replacementPlans: SqliteOntologyReplacementPlanStorage\n readonly vectorIndexing: SqliteVectorIndexingStorage\n readonly vectors: SqliteOntologyVectorStorage\n readonly outbox: SqliteOntologyOutboxStorage\n readonly uniqueValues: SqliteOntologyUniqueValueStorage\n\n constructor(input: {\n readonly db: Database\n readonly runRootOperation: SqliteRootOperation\n readonly transactionContext: SqliteOntologyTransactionContext | null\n }) {\n this.commits = new SqliteOntologyCommitStorage(input.db, input.runRootOperation)\n this.sources = new SqliteOntologySourceStorage(input.db, input.runRootOperation)\n this.materializations = new SqliteOntologyMaterializationStorage(\n input.db,\n input.transactionContext\n )\n this.replacementPlans = new SqliteOntologyReplacementPlanStorage(\n input.db,\n input.runRootOperation\n )\n this.vectorIndexing = new SqliteVectorIndexingStorage(\n input.db,\n input.runRootOperation,\n (session, projectId) => this.materializations.assertVectorSession(session, projectId)\n )\n this.vectors = new SqliteOntologyVectorStorage(\n input.db,\n input.runRootOperation,\n (session, projectId, commitId) =>\n this.materializations.assertVectorSession(session, projectId, commitId)\n )\n this.outbox = new SqliteOntologyOutboxStorage(input.db, input.runRootOperation)\n this.uniqueValues = new SqliteOntologyUniqueValueStorage(input.db, input.runRootOperation)\n }\n\n deactivateSessions(): void {\n this.materializations.deactivateSessions()\n }\n}\n\nexport type { SqliteOntologyTransactionContext } from \"./materialization-session\"\n",
63
69
  "import type { Database } from \"bun:sqlite\"\nimport { parseSixbFailure, serializeSixbFailure } from \"@sixb/core/internal/errors\"\nimport { assertPipelineRunExecution } from \"@sixb/core/internal/pipeline-run-storage-provider\"\nimport { canRequeuePipelineRunAfterEnqueueFailure } from \"@sixb/core/internal/storage\"\nimport type { DatasetVersionRef } from \"@sixb/core/lake-storage\"\nimport type {\n ExecutionStorage,\n FinishPipelineRunInput,\n FinishPipelineStepRunInput,\n ListLatestPipelineRunsInput,\n ListLatestPipelineRunsResult,\n ListPipelineRunsInput,\n ListPipelineRunsResult,\n ListPipelineStepRunsInput,\n ListPipelineStepRunsResult,\n PipelineRunRecord,\n PipelineRunStorage,\n PipelineStepRunRecord,\n QueuePipelineRunInput,\n StartPipelineRunInput,\n StartPipelineStepRunInput,\n} from \"@sixb/core/storage\"\nimport { PIPELINE_RUN_FAILURE_CODES, PipelineRunError } from \"@sixb/core/storage\"\nimport { queryLatestRunsByOwnerId } from \"./latest-run-query\"\nimport {\n appendRunListFilters,\n hasEmptyStatuses,\n queryRunList,\n type SqliteValue,\n} from \"./run-list-query\"\nimport { isUniqueConstraintError } from \"./storage-errors\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n type SqliteStoreConnection,\n} from \"./transactions\"\n\nexport interface SqlitePipelineRunStorageOptions {\n /** Execution lookup sharing the same provider transaction. */\n executions: ExecutionStorage\n /** Path to SQLite database file. Defaults to ':memory:' for in-memory database. */\n path?: string\n /** Internal shared connection used by bundled SqliteStorage. */\n connection?: SqliteStoreConnection\n}\n\nexport class SqlitePipelineRunStorage implements PipelineRunStorage {\n private readonly connection: SqliteStoreConnection\n private readonly db: Database\n private readonly executions: ExecutionStorage\n\n constructor(options: SqlitePipelineRunStorageOptions) {\n this.connection = openSqliteStoreConnection(options)\n this.db = this.connection.db\n this.executions = options.executions\n }\n\n async queue(input: QueuePipelineRunInput): Promise<PipelineRunRecord> {\n const queuedAt = input.queuedAt ?? new Date()\n await assertPipelineRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n pipelineId: input.pipelineId,\n })\n\n try {\n this.db\n .query(\n `\n INSERT INTO pipeline_runs (\n project_id,\n id,\n execution_id,\n pipeline_id,\n status,\n queued_at,\n started_at\n ) VALUES (?, ?, ?, ?, ?, ?, NULL)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.executionId,\n input.pipelineId,\n \"queued\",\n queuedAt.toISOString()\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n return this.requeueAfterEnqueueFailure(input, queuedAt)\n }\n\n throw error\n }\n\n const record = await this.getById({ projectId: input.projectId, id: input.id })\n if (!record) {\n throw new PipelineRunError(\n `[SixbSqlite] Failed to load pipeline run '${input.id}' for project '${input.projectId}'.`\n )\n }\n\n return record\n }\n\n private async requeueAfterEnqueueFailure(\n input: QueuePipelineRunInput,\n queuedAt: Date\n ): Promise<PipelineRunRecord> {\n return this.db.transaction(() => {\n const existing = this.db\n .query(\"SELECT * FROM pipeline_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as PipelineRunDatabaseRow | null\n if (\n !existing ||\n !canRequeuePipelineRunAfterEnqueueFailure(rowToPipelineRunRecord(existing), input)\n ) {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE pipeline_runs\n SET status = ?, queued_at = ?, started_at = NULL, finished_at = NULL,\n output_dataset_id = NULL, output_version_id = NULL, error = NULL\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\"queued\", queuedAt.toISOString(), input.projectId, input.id)\n\n const updated = this.db\n .query(\"SELECT * FROM pipeline_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as PipelineRunDatabaseRow\n return rowToPipelineRunRecord(updated)\n })()\n }\n\n async start(input: StartPipelineRunInput): Promise<PipelineRunRecord> {\n const result = this.db\n .query(\n `\n UPDATE pipeline_runs\n SET status = ?, started_at = ?, error = NULL\n WHERE project_id = ? AND id = ? AND status = ?\n `\n )\n .run(\n \"running\",\n (input.startedAt ?? new Date()).toISOString(),\n input.projectId,\n input.id,\n \"queued\"\n )\n if (result.changes > 0) {\n const record = await this.getById({ projectId: input.projectId, id: input.id })\n if (record) return record\n }\n\n const existing = await this.getById({ projectId: input.projectId, id: input.id })\n if (!existing) {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline run '${input.id}' cannot start from status '${existing.status}'.`\n )\n }\n\n async finish(input: FinishPipelineRunInput): Promise<PipelineRunRecord> {\n return this.db.transaction(() => {\n const existing = this.db\n .query(\"SELECT * FROM pipeline_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as PipelineRunDatabaseRow | null\n\n if (!existing) {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n const enqueueFailure =\n input.status === \"failed\" && input.error.code === \"queue.enqueue_failed\"\n if (\n (enqueueFailure && existing.status !== \"queued\") ||\n (!enqueueFailure && existing.status !== \"running\")\n ) {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline run '${input.id}' cannot finish from status '${existing.status}'.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE pipeline_runs\n SET\n status = ?,\n finished_at = ?,\n output_dataset_id = ?,\n output_version_id = ?,\n error = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.status,\n (input.finishedAt ?? new Date()).toISOString(),\n input.status === \"succeeded\" ? (input.output?.datasetId ?? null) : null,\n input.status === \"succeeded\" ? (input.output?.versionId ?? null) : null,\n input.status === \"succeeded\" || input.error === undefined\n ? null\n : serializeSixbFailure(input.error, PIPELINE_RUN_FAILURE_CODES),\n input.projectId,\n input.id\n )\n\n const updated = this.db\n .query(\"SELECT * FROM pipeline_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as PipelineRunDatabaseRow\n\n return rowToPipelineRunRecord(updated)\n })()\n }\n\n async startStep(input: StartPipelineStepRunInput): Promise<PipelineStepRunRecord> {\n return this.db.transaction(() => {\n const pipelineRun = this.db\n .query(\"SELECT * FROM pipeline_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.pipelineRunId) as PipelineRunDatabaseRow | null\n\n if (!pipelineRun) {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline run '${input.pipelineRunId}' not found for project '${input.projectId}'.`\n )\n }\n\n if (pipelineRun.status !== \"running\") {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline run '${input.pipelineRunId}' for project '${input.projectId}' is already terminal.`\n )\n }\n\n if (pipelineRun.pipeline_id !== input.pipelineId) {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline step run '${input.id}' pipeline '${input.pipelineId}' does not match pipeline run '${input.pipelineRunId}' pipeline '${pipelineRun.pipeline_id}'.`\n )\n }\n\n const startedAt = input.startedAt ?? new Date()\n\n try {\n this.db\n .query(\n `\n INSERT INTO pipeline_step_runs (\n project_id,\n id,\n pipeline_run_id,\n pipeline_id,\n step_id,\n dataset_id,\n mode,\n status,\n started_at,\n inputs\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.pipelineRunId,\n input.pipelineId,\n input.stepId,\n input.datasetId,\n input.mode,\n \"running\",\n startedAt.toISOString(),\n serializeDatasetVersionRefs(input.inputs)\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline step run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n throw error\n }\n\n const row = this.db\n .query(\"SELECT * FROM pipeline_step_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as PipelineStepRunDatabaseRow | null\n\n if (!row) {\n throw new PipelineRunError(\n `[SixbSqlite] Failed to load pipeline step run '${input.id}' for project '${input.projectId}'.`\n )\n }\n\n return rowToPipelineStepRunRecord(row)\n })()\n }\n\n async finishStep(input: FinishPipelineStepRunInput): Promise<PipelineStepRunRecord> {\n assertOptionalNonNegativeInteger(input.rowsWritten, \"rowsWritten\")\n\n return this.db.transaction(() => {\n const existing = this.db\n .query(\"SELECT * FROM pipeline_step_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as PipelineStepRunDatabaseRow | null\n\n if (!existing) {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline step run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n if (existing.status !== \"running\") {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline step run '${input.id}' for project '${input.projectId}' is already terminal.`\n )\n }\n\n if (input.status === \"succeeded\" && input.output.datasetId !== existing.dataset_id) {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline step run '${input.id}' output dataset '${input.output.datasetId}' does not match '${existing.dataset_id}'.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE pipeline_step_runs\n SET\n status = ?,\n finished_at = ?,\n output_version_id = ?,\n rows_written = ?,\n error = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.status,\n (input.finishedAt ?? new Date()).toISOString(),\n input.status === \"succeeded\" ? input.output.versionId : null,\n input.rowsWritten ?? existing.rows_written ?? null,\n input.status === \"succeeded\" || input.error === undefined\n ? null\n : serializeSixbFailure(input.error, PIPELINE_RUN_FAILURE_CODES),\n input.projectId,\n input.id\n )\n\n const updated = this.db\n .query(\"SELECT * FROM pipeline_step_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as PipelineStepRunDatabaseRow\n\n return rowToPipelineStepRunRecord(updated)\n })()\n }\n\n async getById(params: { projectId: string; id: string }): Promise<PipelineRunRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM pipeline_runs WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as PipelineRunDatabaseRow | null\n\n return row ? rowToPipelineRunRecord(row) : null\n }\n\n async list(input: ListPipelineRunsInput): Promise<ListPipelineRunsResult> {\n if (hasEmptyStatuses(input) || input.pipelineIds?.length === 0) {\n return {\n runs: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n\n if (input.pipelineId) {\n whereClauses.push(\"pipeline_id = ?\")\n args.push(input.pipelineId)\n }\n\n if (input.pipelineIds) {\n whereClauses.push(`pipeline_id IN (${input.pipelineIds.map(() => \"?\").join(\", \")})`)\n args.push(...input.pipelineIds)\n }\n\n appendRunListFilters(whereClauses, args, input, \"COALESCE(started_at, queued_at)\")\n\n const { rows, total, hasMore } = queryRunList<PipelineRunDatabaseRow>({\n db: this.db,\n tableName: \"pipeline_runs\",\n whereClauses,\n args,\n order: input.order,\n limit: input.limit,\n offset: input.offset,\n })\n\n return {\n runs: rows.map(rowToPipelineRunRecord),\n hasMore,\n total,\n }\n }\n\n async listLatestByPipelineIds(\n input: ListLatestPipelineRunsInput\n ): Promise<ListLatestPipelineRunsResult> {\n const rows = queryLatestRunsByOwnerId<PipelineRunDatabaseRow>({\n db: this.db,\n tableName: \"pipeline_runs\",\n ownerColumn: \"pipeline_id\",\n ownerIds: input.pipelineIds,\n projectId: input.projectId,\n ownerIdFor: (row) => row.pipeline_id,\n })\n\n return {\n runs: rows.map(rowToPipelineRunRecord),\n }\n }\n\n async listSteps(input: ListPipelineStepRunsInput): Promise<ListPipelineStepRunsResult> {\n if (hasEmptyStatuses(input)) {\n return {\n steps: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n\n if (input.pipelineRunId) {\n whereClauses.push(\"pipeline_run_id = ?\")\n args.push(input.pipelineRunId)\n }\n\n if (input.pipelineId) {\n whereClauses.push(\"pipeline_id = ?\")\n args.push(input.pipelineId)\n }\n\n if (input.stepId) {\n whereClauses.push(\"step_id = ?\")\n args.push(input.stepId)\n }\n\n if (input.datasetId) {\n whereClauses.push(\"dataset_id = ?\")\n args.push(input.datasetId)\n }\n\n appendRunListFilters(whereClauses, args, input)\n\n const { rows, total, hasMore } = queryRunList<PipelineStepRunDatabaseRow>({\n db: this.db,\n tableName: \"pipeline_step_runs\",\n whereClauses,\n args,\n order: input.order,\n limit: input.limit,\n offset: input.offset,\n })\n\n return {\n steps: rows.map(rowToPipelineStepRunRecord),\n hasMore,\n total,\n }\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n}\n\nfunction serializeDatasetVersionRefs(refs: readonly DatasetVersionRef[]): string {\n return JSON.stringify(refs)\n}\n\nfunction parseDatasetVersionRefs(value: string): readonly DatasetVersionRef[] {\n return JSON.parse(value) as readonly DatasetVersionRef[]\n}\n\nfunction rowToPipelineRunRecord(row: PipelineRunDatabaseRow): PipelineRunRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n executionId: row.execution_id,\n pipelineId: row.pipeline_id,\n status: row.status,\n queuedAt: new Date(row.queued_at),\n startedAt: row.started_at ? new Date(row.started_at) : undefined,\n finishedAt: row.finished_at ? new Date(row.finished_at) : undefined,\n output:\n row.output_dataset_id && row.output_version_id\n ? {\n datasetId: row.output_dataset_id,\n versionId: row.output_version_id,\n }\n : undefined,\n error: row.error === null ? undefined : parseSixbFailure(row.error, PIPELINE_RUN_FAILURE_CODES),\n }\n}\n\nfunction rowToPipelineStepRunRecord(row: PipelineStepRunDatabaseRow): PipelineStepRunRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n pipelineRunId: row.pipeline_run_id,\n pipelineId: row.pipeline_id,\n stepId: row.step_id,\n datasetId: row.dataset_id,\n mode: row.mode,\n status: row.status,\n startedAt: new Date(row.started_at),\n finishedAt: row.finished_at ? new Date(row.finished_at) : undefined,\n inputs: parseDatasetVersionRefs(row.inputs),\n output: row.output_version_id\n ? {\n datasetId: row.dataset_id,\n versionId: row.output_version_id,\n }\n : undefined,\n rowsWritten: row.rows_written ?? undefined,\n error: row.error === null ? undefined : parseSixbFailure(row.error, PIPELINE_RUN_FAILURE_CODES),\n }\n}\n\nfunction assertOptionalNonNegativeInteger(value: number | undefined, fieldName: string): void {\n if (value !== undefined && (!Number.isInteger(value) || value < 0)) {\n throw new PipelineRunError(\n `[SixbSqlite] Pipeline run ${fieldName} must be a non-negative integer.`\n )\n }\n}\n\ninterface PipelineRunDatabaseRow {\n project_id: string\n id: string\n execution_id: string\n pipeline_id: string\n status: PipelineRunRecord[\"status\"]\n queued_at: string\n started_at: string | null\n finished_at: string | null\n output_dataset_id: string | null\n output_version_id: string | null\n error: string | null\n}\n\ninterface PipelineStepRunDatabaseRow {\n project_id: string\n id: string\n pipeline_run_id: string\n pipeline_id: string\n step_id: string\n dataset_id: string\n mode: PipelineStepRunRecord[\"mode\"]\n status: PipelineStepRunRecord[\"status\"]\n started_at: string\n finished_at: string | null\n inputs: string\n output_version_id: string | null\n rows_written: number | null\n error: string | null\n}\n",
64
70
  "import type { Database } from \"bun:sqlite\"\nimport type { SqliteValue } from \"./run-list-query\"\n\ntype SqliteLatestRunTarget =\n | { readonly tableName: \"pipeline_runs\"; readonly ownerColumn: \"pipeline_id\" }\n | { readonly tableName: \"projection_runs\"; readonly ownerColumn: \"projection_id\" }\n | { readonly tableName: \"sync_runs\"; readonly ownerColumn: \"sync_id\" }\n | { readonly tableName: \"workflow_runs\"; readonly ownerColumn: \"workflow_id\" }\n\nexport function queryLatestRunsByOwnerId<TRow>(\n input: {\n readonly db: Database\n readonly ownerIds: readonly string[]\n readonly projectId: string\n readonly ownerIdFor: (row: TRow) => string\n /** A status that never counts as the latest run, such as a run made stale by a newer one. */\n readonly excludedStatus?: string\n } & SqliteLatestRunTarget\n): readonly TRow[] {\n const ownerIds = [...new Set(input.ownerIds)]\n if (ownerIds.length === 0) {\n return []\n }\n\n const placeholders = ownerIds.map(() => \"?\").join(\", \")\n const statusFilter = input.excludedStatus === undefined ? \"\" : \" AND status <> ?\"\n const statusArgs = input.excludedStatus === undefined ? [] : [input.excludedStatus]\n const orderColumn =\n input.tableName === \"sync_runs\" ||\n input.tableName === \"pipeline_runs\" ||\n input.tableName === \"projection_runs\"\n ? \"COALESCE(started_at, queued_at)\"\n : \"started_at\"\n const rows = input.db\n .query(\n `\n SELECT *\n FROM (\n SELECT\n *,\n ROW_NUMBER() OVER (\n PARTITION BY ${input.ownerColumn}\n ORDER BY ${orderColumn} DESC, id DESC\n ) AS sixb_latest_rank\n FROM ${input.tableName}\n WHERE project_id = ? AND ${input.ownerColumn} IN (${placeholders})${statusFilter}\n )\n WHERE sixb_latest_rank = 1\n `\n )\n .all(input.projectId, ...ownerIds, ...statusArgs) as (TRow & {\n sixb_latest_rank: SqliteValue\n })[]\n\n const latestByOwnerId = new Map(rows.map((row) => [input.ownerIdFor(row), row]))\n\n return ownerIds.flatMap((ownerId) => {\n const row = latestByOwnerId.get(ownerId)\n return row ? [row] : []\n })\n}\n",
65
71
  "import type { Database } from \"bun:sqlite\"\nimport { randomUUID } from \"node:crypto\"\nimport { serializeSixbFailure } from \"@sixb/core/internal/errors\"\nimport {\n advanceProjectionTelemetry,\n assertGenericProgressDoesNotAdvanceTelemetry,\n assertProjectionMissingTarget,\n assertProjectionRunAttempt,\n assertProjectionRunDurableExecution,\n assertProjectionRunListWindow,\n assertProjectionRunNonEmpty,\n assertProjectionRunQueueInput,\n assertProjectionRunRunning,\n assertProjectionRunStartInput,\n canRequeueProjectionRunAfterEnqueueFailure,\n createProjectionRunClaim,\n createProjectionRunRecord,\n failProjectionRunEnqueue,\n immutableDatasetVersionConflict,\n mergeProjectionRunProgress,\n type PersistedProjectionRunRecord,\n parseProjectionAttemptFailure,\n planProjectionRunFinish,\n planProjectionRunReclaim,\n projectionRunNotFound,\n publicProjectionRunRecord,\n requireTelemetryProjectionRun,\n restoreProjectionRun,\n type StoredProjectionRunRecord,\n SUPERSEDING_PROJECTION_RUN_STATUSES,\n staleProjectionRunExecution,\n} from \"@sixb/core/internal/projection-run-storage-provider\"\nimport type {\n AdvanceProjectionTelemetryCheckpointInput,\n ExecutionStorage,\n FailProjectionRunEnqueueInput,\n FindSupersedingProjectionRunInput,\n FinishProjectionRunInput,\n ListLatestProjectionRunsInput,\n ListLatestProjectionRunsResult,\n ListProjectionRunsInput,\n ListProjectionRunsResult,\n LockProjectionRunForMaterializationInput,\n ProjectionKind,\n ProjectionRunClaim,\n ProjectionRunProgress,\n ProjectionRunRecord,\n ProjectionRunStatus,\n ProjectionRunStorage,\n QueueProjectionRunInput,\n RecordProjectionAttemptFailureInput,\n RecordProjectionMissingTargetInput,\n StartOrReclaimProjectionRunInput,\n TelemetryProjectionRunRecord,\n UpdateProjectionRunInput,\n} from \"@sixb/core/storage\"\nimport { PROJECTION_RUN_FAILURE_CODES, ProjectionRunError } from \"@sixb/core/storage\"\nimport { queryLatestRunsByOwnerId } from \"./latest-run-query\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n runImmediateTransaction,\n type SqliteStoreConnection,\n} from \"./transactions\"\n\nexport interface SqliteProjectionRunStorageOptions {\n /** Execution lookup sharing the same provider transaction. */\n executions: ExecutionStorage\n /** Path to SQLite database file. Defaults to ':memory:' for in-memory database. */\n path?: string\n /** Internal shared connection used by bundled SqliteStorage. */\n connection?: SqliteStoreConnection\n}\n\nexport class SqliteProjectionRunStorage implements ProjectionRunStorage {\n private readonly connection: SqliteStoreConnection\n private readonly db: Database\n private readonly executions: ExecutionStorage\n\n constructor(options: SqliteProjectionRunStorageOptions) {\n this.connection = openSqliteStoreConnection(options)\n this.db = this.connection.db\n this.executions = options.executions\n }\n\n async queue(input: QueueProjectionRunInput): Promise<ProjectionRunRecord> {\n assertProjectionRunQueueInput(input)\n await assertProjectionRunDurableExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n projectionId: input.identity.projectionId,\n datasetId: input.identity.datasetVersion.datasetId,\n datasetVersionId: input.identity.datasetVersion.versionId,\n })\n\n return runImmediateTransaction(this.db, () => {\n this.assertDatasetVersionIsImmutable(input)\n const existing = this.findRow(input.projectId, input.id)\n if (existing) {\n const restored = restoreProjectionRunRow(existing)\n if (!canRequeueProjectionRunAfterEnqueueFailure(restored, input)) {\n throw duplicateProjectionRun(input)\n }\n const queuedAt = input.queuedAt ?? new Date()\n const result = this.db\n .query(\n `\n UPDATE projection_runs\n SET status = 'queued', queued_at = ?, started_at = NULL, finished_at = NULL,\n attempt = 0, execution_token = NULL, next_batch_ordinal = ?, next_row_offset = ?,\n input_exhausted = ?, missing_target_object_type_id = NULL,\n missing_target_object_id = NULL, missing_target_batch_ordinal = NULL,\n missing_target_first_seen_at = NULL, source_rows_read = 0,\n source_rows_skipped = 0, source_changes_read = NULL, error = NULL\n WHERE project_id = ? AND id = ? AND status = 'failed'\n AND json_extract(error, '$.code') = 'queue.enqueue_failed'\n `\n )\n .run(\n queuedAt.toISOString(),\n input.fixedBatchSize === undefined ? null : 0,\n input.fixedBatchSize === undefined ? null : 0,\n input.fixedBatchSize === undefined ? null : 0,\n input.projectId,\n input.id\n )\n if (result.changes !== 1) throw duplicateProjectionRun(input)\n return rowToProjectionRunRecord(this.requireRow(input.projectId, input.id))\n }\n\n const record = createProjectionRunRecord(input)\n try {\n this.insertQueued(record)\n } catch (error) {\n if (isUniqueConstraintError(error)) throw duplicateProjectionRun(input)\n throw error\n }\n return rowToProjectionRunRecord(this.requireRow(input.projectId, input.id))\n })\n }\n\n async startOrReclaim(input: StartOrReclaimProjectionRunInput): Promise<ProjectionRunClaim> {\n return runImmediateTransaction(this.db, () => {\n assertProjectionRunStartInput(input)\n\n const metadataConflict = this.db\n .query(\n `\n SELECT 1 FROM projection_runs\n WHERE project_id = ? AND id <> ? AND dataset_id = ? AND dataset_version_id = ?\n AND dataset_version_created_at IS NOT NULL\n AND dataset_version_created_at <> ?\n LIMIT 1\n `\n )\n .get(\n input.projectId,\n input.id,\n input.identity.datasetVersion.datasetId,\n input.identity.datasetVersion.versionId,\n input.identity.datasetVersion.createdAt\n )\n if (metadataConflict) {\n throw immutableDatasetVersionConflict(input.identity)\n }\n\n const existing = this.requireRow(input.projectId, input.id)\n const existingRecord = restoreProjectionRunRow(existing)\n const attempt = planProjectionRunReclaim(existingRecord, input).attempt\n\n const executionToken = createFreshExecutionToken(existing.execution_token)\n const result = this.db\n .query(\n `\n UPDATE projection_runs\n SET status = 'running', started_at = COALESCE(started_at, ?), finished_at = NULL,\n attempt = ?, execution_token = ?\n WHERE project_id = ? AND id = ?\n AND (\n (status = 'queued' AND execution_token IS NULL)\n OR (status = 'running' AND execution_token = ?)\n )\n `\n )\n .run(\n (input.startedAt ?? new Date()).toISOString(),\n attempt,\n executionToken,\n input.projectId,\n input.id,\n existing.execution_token\n )\n if (result.changes !== 1) throw staleProjectionRunExecution(input.id)\n\n return projectionRunClaim(this.requireRow(input.projectId, input.id))\n })\n }\n\n async failEnqueue(input: FailProjectionRunEnqueueInput): Promise<ProjectionRunRecord> {\n return runImmediateTransaction(this.db, () => {\n const existing = restoreProjectionRunRow(this.requireRow(input.projectId, input.id))\n const failed = failProjectionRunEnqueue(existing, input)\n if (!failed.finishedAt || !failed.error) {\n throw new ProjectionRunError(`[SixbSqlite] Projection run '${input.id}' did not finish.`)\n }\n const result = this.db\n .query(\n `\n UPDATE projection_runs\n SET status = 'failed', finished_at = ?, error = ?\n WHERE project_id = ? AND id = ? AND status = 'queued'\n `\n )\n .run(\n failed.finishedAt.toISOString(),\n serializeSixbFailure(failed.error, PROJECTION_RUN_FAILURE_CODES),\n input.projectId,\n input.id\n )\n if (result.changes !== 1) throw duplicateProjectionRun(input)\n return rowToProjectionRunRecord(this.requireRow(input.projectId, input.id))\n })\n }\n\n async lockForMaterialization(\n input: LockProjectionRunForMaterializationInput\n ): Promise<ProjectionRunRecord> {\n return rowToProjectionRunRecord(this.requireMaterializationExecution(input))\n }\n\n async update(input: UpdateProjectionRunInput): Promise<ProjectionRunRecord> {\n return runImmediateTransaction(this.db, () => {\n const existingRow = this.requireMaterializationExecution(input)\n const existing = restoreProjectionRunRow(existingRow)\n assertGenericProgressDoesNotAdvanceTelemetry(existing, input.progress)\n const progress = mergeProjectionRunProgress(existing.progress, input.progress)\n const result = this.updateProgress(existingRow, progress, input.executionToken)\n if (result !== 1) throw staleProjectionRunExecution(input.id)\n return rowToProjectionRunRecord(this.requireRow(input.projectId, input.id))\n })\n }\n\n async recordAttemptFailure(\n input: RecordProjectionAttemptFailureInput\n ): Promise<ProjectionRunRecord> {\n return runImmediateTransaction(this.db, () => {\n const existingRow = this.requireMaterializationExecution(input)\n const error = parseProjectionAttemptFailure(restoreProjectionRunRow(existingRow), input.error)\n const result = this.db\n .query(\n `\n UPDATE projection_runs\n SET error = ?\n WHERE project_id = ? AND id = ? AND status = 'running' AND execution_token = ?\n `\n )\n .run(\n serializeSixbFailure(error, PROJECTION_RUN_FAILURE_CODES),\n input.projectId,\n input.id,\n input.executionToken\n )\n if (result.changes !== 1) throw staleProjectionRunExecution(input.id)\n return rowToProjectionRunRecord(this.requireRow(input.projectId, input.id))\n })\n }\n\n async finish(input: FinishProjectionRunInput): Promise<ProjectionRunRecord> {\n return runImmediateTransaction(this.db, () => {\n const existingRow = this.requireMaterializationExecution(input)\n const plan = planProjectionRunFinish(restoreProjectionRunRow(existingRow), input)\n const result = this.db\n .query(\n `\n UPDATE projection_runs\n SET\n status = ?,\n finished_at = ?,\n execution_token = NULL,\n source_rows_read = ?,\n source_rows_skipped = ?,\n source_changes_read = ?,\n input_exhausted = ?,\n error = ?\n WHERE project_id = ? AND id = ? AND status = 'running' AND execution_token = ?\n `\n )\n .run(\n input.status,\n plan.finishedAt.toISOString(),\n plan.progress.sourceRowsRead,\n plan.progress.sourceRowsSkipped,\n plan.progress.sourceChangesRead ?? null,\n plan.inputExhausted ? 1 : existingRow.input_exhausted,\n plan.error === undefined\n ? null\n : serializeSixbFailure(plan.error, PROJECTION_RUN_FAILURE_CODES),\n input.projectId,\n input.id,\n input.executionToken\n )\n if (result.changes !== 1) throw staleProjectionRunExecution(input.id)\n return rowToProjectionRunRecord(this.requireRow(input.projectId, input.id))\n })\n }\n\n async advanceTelemetryCheckpoint(\n input: AdvanceProjectionTelemetryCheckpointInput\n ): Promise<TelemetryProjectionRunRecord> {\n return runImmediateTransaction(this.db, () => {\n const existing = this.requireMaterializationExecution(input)\n const advance = advanceProjectionTelemetry(restoreProjectionRunRow(existing), input)\n const result = this.db\n .query(\n `\n UPDATE projection_runs\n SET\n next_batch_ordinal = ?,\n next_row_offset = ?,\n input_exhausted = ?,\n source_rows_read = ?,\n source_rows_skipped = ?,\n missing_target_object_type_id = NULL,\n missing_target_object_id = NULL,\n missing_target_batch_ordinal = NULL,\n missing_target_first_seen_at = NULL\n WHERE project_id = ? AND id = ? AND status = 'running' AND execution_token = ?\n AND next_batch_ordinal = ? AND input_exhausted = 0\n `\n )\n .run(\n advance.checkpoint.nextBatchOrdinal,\n advance.checkpoint.nextRowOffset,\n advance.checkpoint.inputExhausted ? 1 : 0,\n advance.progress.sourceRowsRead,\n advance.progress.sourceRowsSkipped,\n input.projectId,\n input.id,\n input.executionToken,\n input.batchOrdinal\n )\n if (result.changes !== 1) throw staleProjectionRunExecution(input.id)\n return rowToTelemetryProjectionRunRecord(this.requireRow(input.projectId, input.id))\n })\n }\n\n async recordMissingTarget(\n input: RecordProjectionMissingTargetInput\n ): Promise<TelemetryProjectionRunRecord> {\n return runImmediateTransaction(this.db, () => {\n const existing = this.requireMaterializationExecution(input)\n const missingTarget = assertProjectionMissingTarget(\n requireTelemetryProjectionRun(restoreProjectionRunRow(existing)),\n input.missingTarget\n )\n const result = this.db\n .query(\n `\n UPDATE projection_runs\n SET\n missing_target_object_type_id = ?,\n missing_target_object_id = ?,\n missing_target_batch_ordinal = ?,\n missing_target_first_seen_at = ?\n WHERE project_id = ? AND id = ? AND status = 'running' AND execution_token = ?\n AND next_batch_ordinal = ?\n `\n )\n .run(\n missingTarget.objectTypeId,\n missingTarget.objectId,\n missingTarget.batchOrdinal,\n missingTarget.firstSeenAt.toISOString(),\n input.projectId,\n input.id,\n input.executionToken,\n missingTarget.batchOrdinal\n )\n if (result.changes !== 1) throw staleProjectionRunExecution(input.id)\n return rowToTelemetryProjectionRunRecord(this.requireRow(input.projectId, input.id))\n })\n }\n\n async getById(params: { projectId: string; id: string }): Promise<ProjectionRunRecord | null> {\n const row = this.findRow(params.projectId, params.id)\n return row ? rowToProjectionRunRecord(row) : null\n }\n\n async list(input: ListProjectionRunsInput): Promise<ListProjectionRunsResult> {\n assertProjectionRunNonEmpty(input.projectId, \"projectId\")\n\n if (input.statuses?.length === 0 || input.errorCodes?.length === 0) {\n return { runs: [], hasMore: false, total: 0 }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: (string | number)[] = [input.projectId]\n\n if (input.projectionId) {\n whereClauses.push(\"projection_id = ?\")\n args.push(input.projectionId)\n }\n if (input.projectionKind) {\n whereClauses.push(\"projection_kind = ?\")\n args.push(input.projectionKind)\n }\n if (input.datasetId) {\n whereClauses.push(\"dataset_id = ?\")\n args.push(input.datasetId)\n }\n if (input.datasetVersionId) {\n whereClauses.push(\"dataset_version_id = ?\")\n args.push(input.datasetVersionId)\n }\n if (input.objectTypeIds) {\n if (input.objectTypeIds.length === 0) {\n return { runs: [], hasMore: false, total: 0 }\n }\n const placeholders = input.objectTypeIds.map(() => \"?\").join(\", \")\n whereClauses.push(\n `(object_type_id IN (${placeholders})` +\n ` OR (source_object_type_id IN (${placeholders})` +\n ` AND target_object_type_id IN (${placeholders})))`\n )\n args.push(...input.objectTypeIds, ...input.objectTypeIds, ...input.objectTypeIds)\n }\n if (input.statuses) {\n whereClauses.push(`status IN (${input.statuses.map(() => \"?\").join(\", \")})`)\n args.push(...input.statuses)\n }\n if (input.errorCodes) {\n whereClauses.push(\n `json_extract(error, '$.code') IN (${input.errorCodes.map(() => \"?\").join(\", \")})`\n )\n args.push(...input.errorCodes)\n }\n if (input.startedAfter) {\n whereClauses.push(\"COALESCE(started_at, queued_at) >= ?\")\n args.push(input.startedAfter.toISOString())\n }\n if (input.startedBefore) {\n whereClauses.push(\"COALESCE(started_at, queued_at) <= ?\")\n args.push(input.startedBefore.toISOString())\n }\n\n const where = `WHERE ${whereClauses.join(\" AND \")}`\n const order = input.order === \"asc\" ? \"ASC\" : \"DESC\"\n const offset = input.offset ?? 0\n const limit = input.limit\n\n const totalRow = this.db\n .query(`SELECT COUNT(*) AS count FROM projection_runs ${where}`)\n .get(...args) as { count: number }\n\n let query = `\n SELECT * FROM projection_runs\n ${where}\n ORDER BY COALESCE(started_at, queued_at) ${order}, id ${order}\n `\n const queryArgs = [...args]\n\n if (limit !== undefined) {\n assertProjectionRunListWindow(limit, \"limit\")\n assertProjectionRunListWindow(offset, \"offset\")\n query += \" LIMIT ? OFFSET ?\"\n queryArgs.push(limit, offset)\n } else if (offset > 0) {\n assertProjectionRunListWindow(offset, \"offset\")\n query += \" LIMIT -1 OFFSET ?\"\n queryArgs.push(offset)\n }\n\n const rows = this.db.query(query).all(...queryArgs) as DatabaseRow[]\n const runs = rows.map(rowToProjectionRunRecord)\n return { runs, hasMore: offset + runs.length < totalRow.count, total: totalRow.count }\n }\n\n async findSupersedingRun(\n input: FindSupersedingProjectionRunInput\n ): Promise<ProjectionRunRecord | null> {\n const run = this.requireRow(input.projectId, input.id)\n if (run.materialization_protocol !== \"replacement\") return null\n // SQLite compares TEXT with the binary collation, under which canonical UTC ISO timestamps\n // order chronologically.\n const statuses = SUPERSEDING_PROJECTION_RUN_STATUSES\n const newer = this.db\n .query(\n `\n SELECT * FROM projection_runs\n WHERE project_id = ? AND projection_id = ? AND materialization_protocol = 'replacement'\n AND status IN (${statuses.map(() => \"?\").join(\", \")})\n AND dataset_version_created_at > ?\n ORDER BY dataset_version_created_at DESC, id DESC\n LIMIT 1\n `\n )\n .get(\n input.projectId,\n run.projection_id,\n ...statuses,\n run.dataset_version_created_at\n ) as DatabaseRow | null\n return newer ? rowToProjectionRunRecord(newer) : null\n }\n\n async listLatestByProjectionIds(\n input: ListLatestProjectionRunsInput\n ): Promise<ListLatestProjectionRunsResult> {\n const rows = queryLatestRunsByOwnerId<DatabaseRow>({\n db: this.db,\n tableName: \"projection_runs\",\n ownerColumn: \"projection_id\",\n ownerIds: input.projectionIds,\n projectId: input.projectId,\n ownerIdFor: (row) => row.projection_id,\n excludedStatus: \"superseded\",\n })\n return { runs: rows.map(rowToProjectionRunRecord) }\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n\n private assertDatasetVersionIsImmutable(input: QueueProjectionRunInput): void {\n const conflict = this.db\n .query(\n `\n SELECT 1 FROM projection_runs\n WHERE project_id = ? AND id <> ? AND dataset_id = ? AND dataset_version_id = ?\n AND dataset_version_created_at <> ?\n LIMIT 1\n `\n )\n .get(\n input.projectId,\n input.id,\n input.identity.datasetVersion.datasetId,\n input.identity.datasetVersion.versionId,\n input.identity.datasetVersion.createdAt\n )\n if (conflict) throw immutableDatasetVersionConflict(input.identity)\n }\n\n private insertQueued(record: ProjectionRunRecord): void {\n const checkpoint = record.telemetryCheckpoint\n this.db\n .query(\n `\n INSERT INTO projection_runs (\n project_id, id, execution_id, projection_id, projection_kind,\n materialization_protocol, dataset_id, dataset_version_id,\n dataset_version_created_at, ontology_revision, projection_revision, ownership_hash,\n object_type_id, source_object_type_id, target_object_type_id, status, queued_at,\n started_at, finished_at, attempt, execution_token, fixed_batch_size,\n next_batch_ordinal, next_row_offset, input_exhausted, source_rows_read,\n source_rows_skipped\n ) VALUES (\n ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, NULL, NULL, 0, NULL,\n ?, ?, ?, ?, 0, 0\n )\n `\n )\n .run(\n record.projectId,\n record.id,\n record.executionId,\n record.identity.projectionId,\n record.identity.projectionKind,\n record.identity.protocol,\n record.identity.datasetVersion.datasetId,\n record.identity.datasetVersion.versionId,\n record.identity.datasetVersion.createdAt,\n record.identity.ontologyRevision,\n record.identity.projectionRevision,\n record.identity.ownershipHash,\n \"objectTypeId\" in record.target ? record.target.objectTypeId : null,\n \"sourceObjectTypeId\" in record.target ? record.target.sourceObjectTypeId : null,\n \"sourceObjectTypeId\" in record.target ? record.target.targetObjectTypeId : null,\n record.queuedAt.toISOString(),\n checkpoint?.fixedBatchSize ?? null,\n checkpoint?.nextBatchOrdinal ?? null,\n checkpoint?.nextRowOffset ?? null,\n checkpoint === undefined ? null : checkpoint.inputExhausted ? 1 : 0\n )\n }\n\n private updateProgress(\n existing: DatabaseRow,\n progress: ProjectionRunProgress,\n executionToken: string\n ): number {\n const args: (string | number | null)[] = [\n progress.sourceRowsRead,\n progress.sourceRowsSkipped,\n progress.sourceChangesRead ?? null,\n existing.project_id,\n existing.id,\n executionToken,\n ]\n const result = this.db\n .query(\n `\n UPDATE projection_runs\n SET\n source_rows_read = ?,\n source_rows_skipped = ?,\n source_changes_read = ?\n WHERE project_id = ? AND id = ? AND status = 'running'\n AND execution_token = ?\n `\n )\n .run(...args)\n return result.changes\n }\n\n private requireMaterializationExecution(\n input: LockProjectionRunForMaterializationInput\n ): DatabaseRow {\n const row = this.requireRunning(input.projectId, input.id)\n assertProjectionRunAttempt(restoreProjectionRunRow(row), input)\n return row\n }\n\n private requireRunning(projectId: string, id: string): DatabaseRow {\n const row = this.requireRow(projectId, id)\n assertProjectionRunRunning(restoreProjectionRunRow(row))\n return row\n }\n\n private findRow(projectId: string, id: string): DatabaseRow | null {\n return this.db\n .query(\"SELECT * FROM projection_runs WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as DatabaseRow | null\n }\n\n private requireRow(projectId: string, id: string): DatabaseRow {\n assertProjectionRunNonEmpty(projectId, \"projectId\")\n assertProjectionRunNonEmpty(id, \"id\")\n const row = this.findRow(projectId, id)\n if (!row) throw projectionRunNotFound(projectId, id)\n return row\n }\n}\n\nfunction createFreshExecutionToken(previous: string | null): string {\n let token = randomUUID()\n while (token === previous) token = randomUUID()\n return token\n}\n\nfunction rowToProjectionRunRecord(row: DatabaseRow): ProjectionRunRecord {\n return publicProjectionRunRecord(restoreProjectionRunRow(row))\n}\n\nfunction restoreProjectionRunRow(row: DatabaseRow): StoredProjectionRunRecord {\n const persisted: PersistedProjectionRunRecord = {\n id: row.id,\n projectId: row.project_id,\n executionId: row.execution_id,\n projectionId: row.projection_id,\n projectionKind: row.projection_kind,\n protocol: row.materialization_protocol ?? undefined,\n datasetId: row.dataset_id,\n datasetVersionId: row.dataset_version_id,\n datasetVersionCreatedAt: row.dataset_version_created_at ?? undefined,\n ontologyRevision: row.ontology_revision ?? undefined,\n projectionRevision: row.projection_revision ?? undefined,\n ownershipHash: row.ownership_hash ?? undefined,\n objectTypeId: row.object_type_id ?? undefined,\n sourceObjectTypeId: row.source_object_type_id ?? undefined,\n targetObjectTypeId: row.target_object_type_id ?? undefined,\n status: row.status,\n queuedAt: new Date(row.queued_at),\n startedAt: row.started_at ? new Date(row.started_at) : undefined,\n finishedAt: row.finished_at ? new Date(row.finished_at) : undefined,\n attempt: databaseSafeInteger(row.attempt, \"attempt\"),\n executionToken: row.execution_token ?? undefined,\n fixedBatchSize: optionalDatabaseSafeInteger(row.fixed_batch_size, \"fixedBatchSize\"),\n nextBatchOrdinal: optionalDatabaseSafeInteger(row.next_batch_ordinal, \"nextBatchOrdinal\"),\n nextRowOffset: optionalDatabaseSafeInteger(row.next_row_offset, \"nextRowOffset\"),\n inputExhausted: row.input_exhausted === null ? undefined : row.input_exhausted === 1,\n missingTargetObjectTypeId: row.missing_target_object_type_id ?? undefined,\n missingTargetObjectId: row.missing_target_object_id ?? undefined,\n missingTargetBatchOrdinal: optionalDatabaseSafeInteger(\n row.missing_target_batch_ordinal,\n \"missingTargetBatchOrdinal\"\n ),\n missingTargetFirstSeenAt: row.missing_target_first_seen_at\n ? new Date(row.missing_target_first_seen_at)\n : undefined,\n progress: {\n sourceRowsRead: databaseSafeInteger(row.source_rows_read, \"sourceRowsRead\"),\n sourceRowsSkipped: databaseSafeInteger(row.source_rows_skipped, \"sourceRowsSkipped\"),\n ...(row.source_changes_read == null\n ? {}\n : { sourceChangesRead: databaseSafeInteger(row.source_changes_read, \"sourceChangesRead\") }),\n },\n error: row.error ?? undefined,\n }\n return restoreProjectionRun(persisted)\n}\n\nfunction projectionRunClaim(row: DatabaseRow): ProjectionRunClaim {\n return createProjectionRunClaim(restoreProjectionRunRow(row))\n}\n\nfunction rowToTelemetryProjectionRunRecord(row: DatabaseRow): TelemetryProjectionRunRecord {\n return requireTelemetryProjectionRun(rowToProjectionRunRecord(row))\n}\n\nfunction optionalDatabaseSafeInteger(value: number | null, fieldName: string): number | undefined {\n return value === null ? undefined : databaseSafeInteger(value, fieldName)\n}\n\nfunction databaseSafeInteger(value: number, fieldName: string): number {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new ProjectionRunError(\n `[SixbSqlite] Projection run persisted ${fieldName} is not a non-negative safe integer.`\n )\n }\n return value\n}\n\nfunction isUniqueConstraintError(error: unknown): boolean {\n return error instanceof Error && error.message.includes(\"UNIQUE constraint failed\")\n}\n\ninterface DatabaseRow {\n project_id: string\n id: string\n execution_id: string\n projection_id: string\n projection_kind: ProjectionKind\n materialization_protocol: \"replacement\" | \"telemetry\" | null\n dataset_id: string\n dataset_version_id: string\n dataset_version_created_at: string | null\n ontology_revision: string | null\n projection_revision: string | null\n ownership_hash: string | null\n object_type_id: string | null\n source_object_type_id: string | null\n target_object_type_id: string | null\n status: ProjectionRunStatus\n queued_at: string\n started_at: string | null\n finished_at: string | null\n attempt: number\n execution_token: string | null\n fixed_batch_size: number | null\n next_batch_ordinal: number | null\n next_row_offset: number | null\n input_exhausted: 0 | 1 | null\n missing_target_object_type_id: string | null\n missing_target_object_id: string | null\n missing_target_batch_ordinal: number | null\n missing_target_first_seen_at: string | null\n source_rows_read: number\n source_rows_skipped: number\n source_changes_read: number | null\n error: string | null\n}\n\nfunction duplicateProjectionRun(input: { readonly projectId: string; readonly id: string }) {\n return new ProjectionRunError(\n `[SixbSqlite] Projection run '${input.id}' already exists for project '${input.projectId}'.`\n )\n}\n",
@@ -73,7 +79,7 @@
73
79
  "import type { Database } from \"bun:sqlite\"\nimport type { WorkflowIOSnapshot } from \"@sixb/core/internal/workflows\"\nimport type {\n CancelWorkflowInterventionInput,\n CreateWorkflowInterventionInput,\n ExpireWorkflowInterventionInput,\n ListWorkflowInterventionsInput,\n ListWorkflowInterventionsResult,\n Principal,\n SubmitWorkflowInterventionInput,\n WorkflowInterventionRecord,\n WorkflowInterventionStorage,\n} from \"@sixb/core/storage\"\nimport { WorkflowInterventionError } from \"@sixb/core/storage\"\nimport { isUniqueConstraintError } from \"./storage-errors\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n type SqliteStoreConnection,\n} from \"./transactions\"\n\nexport interface SqliteWorkflowInterventionStorageOptions {\n /** Path to SQLite database file. Defaults to ':memory:' for in-memory database. */\n path?: string\n /** Internal shared connection used by bundled SqliteStorage. */\n connection?: SqliteStoreConnection\n}\n\nexport class SqliteWorkflowInterventionStorage implements WorkflowInterventionStorage {\n private readonly connection: SqliteStoreConnection\n private readonly db: Database\n\n constructor(options: SqliteWorkflowInterventionStorageOptions = {}) {\n this.connection = openSqliteStoreConnection(options)\n this.db = this.connection.db\n }\n\n async create(input: CreateWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n assertNonNegativeInteger(input.nodeIndex, \"nodeIndex\")\n\n try {\n this.db\n .query(\n `\n INSERT INTO workflow_interventions (\n project_id,\n id,\n workflow_id,\n workflow_run_id,\n node_run_id,\n node_index,\n node_id,\n node_key,\n intervention_id,\n input,\n default_response,\n status,\n requested_at,\n expires_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.workflowId,\n input.workflowRunId,\n input.nodeRunId,\n input.nodeIndex,\n input.nodeId,\n input.nodeKey,\n input.interventionId,\n serializeRecord(input.input),\n serializeRecord(input.defaultResponse),\n \"pending\",\n (input.requestedAt ?? new Date()).toISOString(),\n input.expiresAt?.toISOString() ?? null\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new WorkflowInterventionError(\n `[SixbSqlite] Workflow intervention '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n throw error\n }\n\n return this.requireIntervention(input.projectId, input.id)\n }\n\n async submit(input: SubmitWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n return this.db.transaction(() => {\n const existing = this.requirePendingIntervention(input.projectId, input.id)\n\n this.db\n .query(\n `\n UPDATE workflow_interventions\n SET\n status = ?,\n submitted_at = ?,\n submitted_by = ?,\n response = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n \"submitted\",\n (input.submittedAt ?? new Date()).toISOString(),\n serializePrincipal(input.submittedBy),\n serializeRecord(input.response),\n existing.project_id,\n existing.id\n )\n\n return this.requireIntervention(input.projectId, input.id)\n })()\n }\n\n async cancel(input: CancelWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n return this.db.transaction(() => {\n const existing = this.requirePendingIntervention(input.projectId, input.id)\n\n this.db\n .query(\n `\n UPDATE workflow_interventions\n SET\n status = ?,\n cancelled_at = ?,\n cancelled_by = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n \"cancelled\",\n (input.cancelledAt ?? new Date()).toISOString(),\n serializePrincipal(input.cancelledBy),\n existing.project_id,\n existing.id\n )\n\n return this.requireIntervention(input.projectId, input.id)\n })()\n }\n\n async expire(input: ExpireWorkflowInterventionInput): Promise<WorkflowInterventionRecord> {\n return this.db.transaction(() => {\n const existing = this.requirePendingIntervention(input.projectId, input.id)\n\n this.db\n .query(\n `\n UPDATE workflow_interventions\n SET\n status = ?,\n expired_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n \"expired\",\n (input.expiredAt ?? new Date()).toISOString(),\n existing.project_id,\n existing.id\n )\n\n return this.requireIntervention(input.projectId, input.id)\n })()\n }\n\n async getById(params: {\n projectId: string\n id: string\n }): Promise<WorkflowInterventionRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM workflow_interventions WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as WorkflowInterventionDatabaseRow | null\n\n return row ? rowToWorkflowInterventionRecord(row) : null\n }\n\n async list(input: ListWorkflowInterventionsInput): Promise<ListWorkflowInterventionsResult> {\n if ((input.statuses && input.statuses.length === 0) || input.workflowIds?.length === 0) {\n return {\n interventions: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n\n if (input.statuses) {\n whereClauses.push(`status IN (${input.statuses.map(() => \"?\").join(\", \")})`)\n args.push(...input.statuses)\n }\n\n if (input.workflowId) {\n whereClauses.push(\"workflow_id = ?\")\n args.push(input.workflowId)\n }\n\n if (input.workflowIds) {\n whereClauses.push(`workflow_id IN (${input.workflowIds.map(() => \"?\").join(\", \")})`)\n args.push(...input.workflowIds)\n }\n\n if (input.workflowRunId) {\n whereClauses.push(\"workflow_run_id = ?\")\n args.push(input.workflowRunId)\n }\n\n if (input.nodeRunId) {\n whereClauses.push(\"node_run_id = ?\")\n args.push(input.nodeRunId)\n }\n\n if (input.nodeId) {\n whereClauses.push(\"node_id = ?\")\n args.push(input.nodeId)\n }\n\n if (input.nodeKey) {\n whereClauses.push(\"node_key = ?\")\n args.push(input.nodeKey)\n }\n\n if (input.interventionId) {\n whereClauses.push(\"intervention_id = ?\")\n args.push(input.interventionId)\n }\n\n if (input.requestedAfter) {\n whereClauses.push(\"requested_at >= ?\")\n args.push(input.requestedAfter.toISOString())\n }\n\n if (input.requestedBefore) {\n whereClauses.push(\"requested_at <= ?\")\n args.push(input.requestedBefore.toISOString())\n }\n\n const where = `WHERE ${whereClauses.join(\" AND \")}`\n const order = input.order === \"asc\" ? \"ASC\" : \"DESC\"\n const offset = input.offset ?? 0\n const totalRow = this.db\n .query(`SELECT COUNT(*) AS count FROM workflow_interventions ${where}`)\n .get(...args) as { count: number }\n\n let query = `\n SELECT * FROM workflow_interventions\n ${where}\n ORDER BY requested_at ${order}, id ${order}\n `\n const queryArgs = [...args]\n\n if (input.limit !== undefined) {\n query += \" LIMIT ? OFFSET ?\"\n queryArgs.push(input.limit, offset)\n } else if (offset > 0) {\n query += \" LIMIT -1 OFFSET ?\"\n queryArgs.push(offset)\n }\n\n const rows = this.db.query(query).all(...queryArgs) as WorkflowInterventionDatabaseRow[]\n\n return {\n interventions: rows.map(rowToWorkflowInterventionRecord),\n hasMore: offset + rows.length < totalRow.count,\n total: totalRow.count,\n }\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n\n private requirePendingIntervention(\n projectId: string,\n id: string\n ): WorkflowInterventionDatabaseRow {\n const row = this.db\n .query(\"SELECT * FROM workflow_interventions WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as WorkflowInterventionDatabaseRow | null\n\n if (!row) {\n throw new WorkflowInterventionError(\n `[SixbSqlite] Workflow intervention '${id}' not found for project '${projectId}'.`\n )\n }\n\n if (row.status !== \"pending\") {\n throw new WorkflowInterventionError(\n `[SixbSqlite] Workflow intervention '${id}' for project '${projectId}' is not pending.`\n )\n }\n\n return row\n }\n\n private requireIntervention(projectId: string, id: string): WorkflowInterventionRecord {\n const row = this.db\n .query(\"SELECT * FROM workflow_interventions WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as WorkflowInterventionDatabaseRow | null\n\n if (!row) {\n throw new WorkflowInterventionError(\n `[SixbSqlite] Failed to load workflow intervention '${id}' for project '${projectId}'.`\n )\n }\n\n return rowToWorkflowInterventionRecord(row)\n }\n}\n\ntype SqliteValue = string | number | null\n\nfunction serializeRecord(value: WorkflowIOSnapshot): string {\n return JSON.stringify(value)\n}\n\nfunction parseRecord(value: string): WorkflowIOSnapshot {\n return JSON.parse(value) as WorkflowIOSnapshot\n}\n\nfunction serializePrincipal(principal: Principal | undefined): string | null {\n return principal ? JSON.stringify(principal) : null\n}\n\nfunction parsePrincipal(value: string | null): Principal | undefined {\n return value ? (JSON.parse(value) as Principal) : undefined\n}\n\nfunction rowToWorkflowInterventionRecord(\n row: WorkflowInterventionDatabaseRow\n): WorkflowInterventionRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n workflowId: row.workflow_id,\n workflowRunId: row.workflow_run_id,\n nodeRunId: row.node_run_id,\n nodeIndex: row.node_index,\n nodeId: row.node_id,\n nodeKey: row.node_key,\n interventionId: row.intervention_id,\n input: parseRecord(row.input),\n defaultResponse: parseRecord(row.default_response),\n status: row.status,\n requestedAt: new Date(row.requested_at),\n expiresAt: row.expires_at ? new Date(row.expires_at) : undefined,\n submittedAt: row.submitted_at ? new Date(row.submitted_at) : undefined,\n submittedBy: parsePrincipal(row.submitted_by),\n response: row.response ? parseRecord(row.response) : undefined,\n cancelledAt: row.cancelled_at ? new Date(row.cancelled_at) : undefined,\n cancelledBy: parsePrincipal(row.cancelled_by),\n expiredAt: row.expired_at ? new Date(row.expired_at) : undefined,\n }\n}\n\nfunction assertNonNegativeInteger(value: number, fieldName: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new WorkflowInterventionError(\n `[SixbSqlite] Workflow intervention ${fieldName} must be a non-negative integer.`\n )\n }\n}\n\ninterface WorkflowInterventionDatabaseRow {\n project_id: string\n id: string\n workflow_id: string\n workflow_run_id: string\n node_run_id: string\n node_index: number\n node_id: string\n node_key: string\n intervention_id: string\n input: string\n default_response: string\n status: WorkflowInterventionRecord[\"status\"]\n requested_at: string\n expires_at: string | null\n submitted_at: string | null\n submitted_by: string | null\n response: string | null\n cancelled_at: string | null\n cancelled_by: string | null\n expired_at: string | null\n}\n",
74
80
  "import type { Database } from \"bun:sqlite\"\nimport { parseSixbFailure, serializeSixbFailure } from \"@sixb/core/internal/errors\"\nimport {\n assertWorkflowAgentNodeRunExecution,\n assertWorkflowRunExecution,\n} from \"@sixb/core/internal/workflow-run-storage-provider\"\nimport type { WorkflowIOSnapshot } from \"@sixb/core/internal/workflows\"\nimport type {\n CancelWorkflowAgentNodeRunInput,\n ConfirmWorkflowAgentNodeRunExecutionOwnershipInput,\n ConfirmWorkflowRunExecutionOwnershipInput,\n CreateWorkflowAgentNodeRunInput,\n ExecutionStorage,\n FinishWorkflowAgentNodeRunInput,\n FinishWorkflowNodeRunInput,\n FinishWorkflowRunInput,\n ListLatestWorkflowRunsInput,\n ListLatestWorkflowRunsResult,\n ListWorkflowAgentNodeRunsInput,\n ListWorkflowAgentNodeRunsResult,\n ListWorkflowNodeRunsInput,\n ListWorkflowNodeRunsResult,\n ListWorkflowRunsInput,\n ListWorkflowRunsResult,\n QueueWorkflowRunInput,\n ReclaimWorkflowAgentNodeRunInput,\n ReclaimWorkflowRunInput,\n ResumeWorkflowRunInput,\n StartWorkflowAgentNodeRunInput,\n StartWorkflowNodeRunInput,\n StartWorkflowRunInput,\n WaitWorkflowNodeRunInput,\n WaitWorkflowRunInput,\n WorkflowAgentNodeRunRecord,\n WorkflowAgentNodeRunStorage,\n WorkflowNodeRunRecord,\n WorkflowNodeRunStorage,\n WorkflowRunRecord,\n WorkflowRunStorage,\n} from \"@sixb/core/storage\"\nimport {\n AGENT_RUN_FAILURE_CODES,\n WORKFLOW_RUN_FAILURE_CODES,\n WorkflowRunError,\n} from \"@sixb/core/storage\"\nimport { queryLatestRunsByOwnerId } from \"./latest-run-query\"\nimport {\n appendRunListFilters,\n hasEmptyStatuses,\n queryRunList,\n type SqliteValue,\n} from \"./run-list-query\"\nimport { isUniqueConstraintError } from \"./storage-errors\"\nimport {\n closeSqliteStoreConnection,\n openSqliteStoreConnection,\n type SqliteStoreConnection,\n} from \"./transactions\"\n\nexport interface SqliteWorkflowRunStorageOptions {\n /** Execution lookup sharing the same provider transaction. */\n executions: ExecutionStorage\n /** Path to SQLite database file. Defaults to ':memory:' for in-memory database. */\n path?: string\n /** Internal shared connection used by bundled SqliteStorage. */\n connection?: SqliteStoreConnection\n}\n\nexport class SqliteWorkflowRunStorage implements WorkflowRunStorage {\n readonly nodes: SqliteWorkflowNodeRunStorage\n readonly agentNodes: SqliteWorkflowAgentNodeRunStorage\n\n private readonly connection: SqliteStoreConnection\n private readonly db: Database\n private readonly executions: ExecutionStorage\n\n constructor(options: SqliteWorkflowRunStorageOptions) {\n this.connection = openSqliteStoreConnection(options)\n this.db = this.connection.db\n this.executions = options.executions\n\n this.nodes = new SqliteWorkflowNodeRunStorage(this.db)\n this.agentNodes = new SqliteWorkflowAgentNodeRunStorage(this.db, this.executions)\n }\n\n async queue(input: QueueWorkflowRunInput): Promise<WorkflowRunRecord> {\n const queuedAt = input.queuedAt ?? new Date()\n await assertWorkflowRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n runId: input.id,\n workflowId: input.workflowId,\n })\n\n try {\n this.db\n .query(\n `\n INSERT INTO workflow_runs (\n project_id,\n id,\n execution_id,\n workflow_id,\n status,\n input,\n queued_at,\n started_at,\n attempt\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.executionId,\n input.workflowId,\n \"queued\",\n serializeRecord(input.input),\n queuedAt.toISOString(),\n queuedAt.toISOString(),\n 0\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow run '${input.id}' or execution '${input.executionId}' is already linked for project '${input.projectId}'.`\n )\n }\n\n throw error\n }\n\n return this.requireWorkflowRun(input.projectId, input.id)\n }\n\n async start(input: StartWorkflowRunInput): Promise<WorkflowRunRecord> {\n const startedAt = input.startedAt ?? new Date()\n\n return this.db.transaction(() => {\n const existing = this.db\n .query(\"SELECT * FROM workflow_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as WorkflowRunDatabaseRow | null\n\n if (!existing || existing.status !== \"queued\") {\n throw new WorkflowRunError(\n existing\n ? `[SixbSqlite] Workflow run '${input.id}' cannot start from status '${existing.status}'.`\n : `[SixbSqlite] Workflow run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE workflow_runs\n SET\n status = ?,\n started_at = ?,\n finished_at = NULL,\n error = NULL,\n attempt = attempt + 1,\n execution_token = ?, execution_queue_lease_expires_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n \"running\",\n startedAt.toISOString(),\n input.execution?.token ?? null,\n input.execution?.queueLeaseExpiresAt.toISOString() ?? null,\n input.projectId,\n input.id\n )\n\n return this.requireWorkflowRun(input.projectId, input.id)\n })()\n }\n\n async reclaim(input: ReclaimWorkflowRunInput): Promise<WorkflowRunRecord> {\n return this.db.transaction(() => {\n const row = this.requireStatus(input.projectId, input.id, \"running\")\n this.db\n .query(`\n UPDATE workflow_runs SET attempt = ?, execution_token = ?,\n execution_queue_lease_expires_at = ? WHERE project_id = ? AND id = ?\n `)\n .run(\n row.attempt + 1,\n input.execution.token,\n input.execution.queueLeaseExpiresAt.toISOString(),\n input.projectId,\n input.id\n )\n return this.requireWorkflowRun(input.projectId, input.id)\n })()\n }\n\n async confirmExecutionOwnership(\n input: ConfirmWorkflowRunExecutionOwnershipInput\n ): Promise<WorkflowRunRecord> {\n return this.db.transaction(() => {\n const row = this.requireStatus(input.projectId, input.id, \"running\")\n assertSqliteWorkflowRunOwnership(row, input.executionToken)\n const current = row.execution_queue_lease_expires_at\n ? new Date(row.execution_queue_lease_expires_at)\n : input.queueLeaseExpiresAt\n this.db\n .query(`\n UPDATE workflow_runs SET execution_queue_lease_expires_at = ?\n WHERE project_id = ? AND id = ?\n `)\n .run(\n new Date(Math.max(current.getTime(), input.queueLeaseExpiresAt.getTime())).toISOString(),\n input.projectId,\n input.id\n )\n return this.requireWorkflowRun(input.projectId, input.id)\n })()\n }\n\n async finish(input: FinishWorkflowRunInput): Promise<WorkflowRunRecord> {\n return this.db.transaction(() => {\n const existing = this.db\n .query(\"SELECT * FROM workflow_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as WorkflowRunDatabaseRow | null\n\n if (!existing) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n if (!canFinishWorkflowRun(existing.status, input.status)) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow run '${input.id}' for project '${input.projectId}' cannot be finished from status '${existing.status}'.`\n )\n }\n assertSqliteWorkflowRunOwnership(existing, input.executionToken)\n\n this.db\n .query(\n `\n UPDATE workflow_runs\n SET\n status = ?,\n finished_at = ?,\n output = ?,\n error = ?,\n execution_token = NULL,\n execution_queue_lease_expires_at = NULL\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.status,\n (input.finishedAt ?? new Date()).toISOString(),\n input.status === \"succeeded\" ? serializeRecord(input.output) : null,\n input.status === \"succeeded\" || input.error === undefined\n ? null\n : serializeSixbFailure(input.error, WORKFLOW_RUN_FAILURE_CODES),\n input.projectId,\n input.id\n )\n\n const updated = this.db\n .query(\"SELECT * FROM workflow_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as WorkflowRunDatabaseRow\n\n return rowToWorkflowRunRecord(updated)\n })()\n }\n\n async wait(input: WaitWorkflowRunInput): Promise<WorkflowRunRecord> {\n return this.db.transaction(() => {\n const existing = this.db\n .query(\"SELECT * FROM workflow_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as WorkflowRunDatabaseRow | null\n\n if (!existing) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n if (existing.status !== \"running\") {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow run '${input.id}' for project '${input.projectId}' must be running.`\n )\n }\n assertSqliteWorkflowRunOwnership(existing, input.executionToken)\n\n this.db\n .query(\n `\n UPDATE workflow_runs\n SET\n status = ?,\n finished_at = NULL,\n error = NULL\n , execution_token = NULL, execution_queue_lease_expires_at = NULL\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\"waiting\", input.projectId, input.id)\n\n return this.requireWorkflowRun(input.projectId, input.id)\n })()\n }\n\n async resume(input: ResumeWorkflowRunInput): Promise<WorkflowRunRecord> {\n return this.db.transaction(() => {\n const existing = this.db\n .query(\"SELECT * FROM workflow_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as WorkflowRunDatabaseRow | null\n\n if (!existing) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n\n if (existing.status !== \"waiting\") {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow run '${input.id}' for project '${input.projectId}' must be waiting.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE workflow_runs\n SET\n status = ?,\n finished_at = NULL,\n error = NULL\n , attempt = attempt + 1, execution_token = ?, execution_queue_lease_expires_at = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n \"running\",\n input.execution?.token ?? null,\n input.execution?.queueLeaseExpiresAt.toISOString() ?? null,\n input.projectId,\n input.id\n )\n\n return this.requireWorkflowRun(input.projectId, input.id)\n })()\n }\n\n async getById(params: { projectId: string; id: string }): Promise<WorkflowRunRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM workflow_runs WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as WorkflowRunDatabaseRow | null\n\n return row ? rowToWorkflowRunRecord(row) : null\n }\n\n async getByExecutionIds(params: {\n readonly projectId: string\n readonly executionIds: readonly string[]\n }): Promise<readonly WorkflowRunRecord[]> {\n const executionIds = [...new Set(params.executionIds)]\n if (executionIds.length === 0) {\n return []\n }\n\n const rows = this.db\n .query(\n `\n SELECT *\n FROM workflow_runs\n WHERE project_id = ?\n AND execution_id IN (SELECT value FROM json_each(?))\n `\n )\n .all(params.projectId, JSON.stringify(executionIds)) as WorkflowRunDatabaseRow[]\n\n const byExecution = new Map(rows.map((row) => [row.execution_id, row]))\n return executionIds.flatMap((executionId) => {\n const row = byExecution.get(executionId)\n return row ? [rowToWorkflowRunRecord(row)] : []\n })\n }\n\n async list(input: ListWorkflowRunsInput): Promise<ListWorkflowRunsResult> {\n if (hasEmptyStatuses(input) || input.workflowIds?.length === 0) {\n return {\n runs: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n\n if (input.workflowId) {\n whereClauses.push(\"workflow_id = ?\")\n args.push(input.workflowId)\n }\n\n if (input.workflowIds) {\n whereClauses.push(`workflow_id IN (${input.workflowIds.map(() => \"?\").join(\", \")})`)\n args.push(...input.workflowIds)\n }\n\n appendRunListFilters(whereClauses, args, input)\n\n const { rows, total, hasMore } = queryRunList<WorkflowRunDatabaseRow>({\n db: this.db,\n tableName: \"workflow_runs\",\n whereClauses,\n args,\n order: input.order,\n limit: input.limit,\n offset: input.offset,\n })\n\n return {\n runs: rows.map(rowToWorkflowRunRecord),\n hasMore,\n total,\n }\n }\n\n async listLatestByWorkflowIds(\n input: ListLatestWorkflowRunsInput\n ): Promise<ListLatestWorkflowRunsResult> {\n const rows = queryLatestRunsByOwnerId<WorkflowRunDatabaseRow>({\n db: this.db,\n tableName: \"workflow_runs\",\n ownerColumn: \"workflow_id\",\n ownerIds: input.workflowIds,\n projectId: input.projectId,\n ownerIdFor: (row) => row.workflow_id,\n })\n\n return {\n runs: rows.map(rowToWorkflowRunRecord),\n }\n }\n\n close(): void {\n closeSqliteStoreConnection(this.connection)\n }\n\n private requireWorkflowRun(projectId: string, id: string): WorkflowRunRecord {\n const record = this.db\n .query(\"SELECT * FROM workflow_runs WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as WorkflowRunDatabaseRow | null\n\n if (!record) {\n throw new WorkflowRunError(\n `[SixbSqlite] Failed to load workflow run '${id}' for project '${projectId}'.`\n )\n }\n\n return rowToWorkflowRunRecord(record)\n }\n\n private requireStatus(\n projectId: string,\n id: string,\n status: WorkflowRunRecord[\"status\"]\n ): WorkflowRunDatabaseRow {\n const row = this.db\n .query(\"SELECT * FROM workflow_runs WHERE project_id = ? AND id = ?\")\n .get(projectId, id) as WorkflowRunDatabaseRow | null\n if (!row) throw new WorkflowRunError(`[SixbSqlite] Workflow run '${id}' not found.`)\n if (row.status !== status) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow run '${id}' must be ${status} (status '${row.status}').`\n )\n }\n return row\n }\n}\n\nexport class SqliteWorkflowAgentNodeRunStorage implements WorkflowAgentNodeRunStorage {\n constructor(\n private readonly db: Database,\n private readonly executions: ExecutionStorage\n ) {}\n\n async create(input: CreateWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n const parent = this.db\n .query(\n `\n SELECT workflow_runs.execution_id\n FROM workflow_node_runs\n JOIN workflow_runs\n ON workflow_runs.project_id = workflow_node_runs.project_id\n AND workflow_runs.id = workflow_node_runs.workflow_run_id\n WHERE workflow_node_runs.project_id = ?\n AND workflow_node_runs.id = ?\n AND workflow_node_runs.node_type = 'agent'\n `\n )\n .get(input.projectId, input.nodeRunId) as { execution_id: string } | null\n if (!parent) {\n throw new WorkflowRunError(\n `[SixbSqlite] Agent workflow node run '${input.nodeRunId}' was not found.`\n )\n }\n await assertWorkflowAgentNodeRunExecution({\n executions: this.executions,\n projectId: input.projectId,\n executionId: input.executionId,\n nodeRunId: input.nodeRunId,\n actorId: input.actorId,\n workflowExecutionId: parent.execution_id,\n })\n\n try {\n this.db\n .query(`\n INSERT INTO workflow_agent_node_runs (\n project_id, node_run_id, execution_id, actor_id, status, prompt, attempt, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)\n `)\n .run(\n input.projectId,\n input.nodeRunId,\n input.executionId,\n input.actorId,\n \"queued\",\n input.prompt,\n 0,\n (input.createdAt ?? new Date()).toISOString()\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new WorkflowRunError(\n `[SixbSqlite] Agent execution already exists for workflow node run '${input.nodeRunId}'.`\n )\n }\n throw error\n }\n return this.require(input.projectId, input.nodeRunId)\n }\n\n async start(input: StartWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n return this.db.transaction(() => {\n this.requireStatus(input.projectId, input.nodeRunId, \"queued\")\n this.db\n .query(`\n UPDATE workflow_agent_node_runs SET\n status = ?, model_id = ?, attempt = 1, execution_token = ?,\n execution_queue_lease_expires_at = ?, started_at = ?\n WHERE project_id = ? AND node_run_id = ?\n `)\n .run(\n \"running\",\n input.modelId ?? null,\n input.execution.token,\n input.execution.queueLeaseExpiresAt.toISOString(),\n (input.startedAt ?? new Date()).toISOString(),\n input.projectId,\n input.nodeRunId\n )\n return this.require(input.projectId, input.nodeRunId)\n })()\n }\n\n async reclaim(input: ReclaimWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n return this.db.transaction(() => {\n const row = this.requireStatus(input.projectId, input.nodeRunId, \"running\")\n this.db\n .query(`\n UPDATE workflow_agent_node_runs SET\n attempt = ?, execution_token = ?, execution_queue_lease_expires_at = ?\n WHERE project_id = ? AND node_run_id = ?\n `)\n .run(\n Number(row.attempt) + 1,\n input.execution.token,\n input.execution.queueLeaseExpiresAt.toISOString(),\n input.projectId,\n input.nodeRunId\n )\n return this.require(input.projectId, input.nodeRunId)\n })()\n }\n\n async confirmExecutionOwnership(\n input: ConfirmWorkflowAgentNodeRunExecutionOwnershipInput\n ): Promise<WorkflowAgentNodeRunRecord> {\n return this.db.transaction(() => {\n const row = this.requireStatus(input.projectId, input.nodeRunId, \"running\")\n assertSqliteWorkflowAgentNodeOwnership(row, input.executionToken)\n const current = row.execution_queue_lease_expires_at\n ? new Date(row.execution_queue_lease_expires_at)\n : input.queueLeaseExpiresAt\n this.db\n .query(`\n UPDATE workflow_agent_node_runs SET execution_queue_lease_expires_at = ?\n WHERE project_id = ? AND node_run_id = ?\n `)\n .run(\n new Date(Math.max(current.getTime(), input.queueLeaseExpiresAt.getTime())).toISOString(),\n input.projectId,\n input.nodeRunId\n )\n return this.require(input.projectId, input.nodeRunId)\n })()\n }\n\n async finish(input: FinishWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n return this.db.transaction(() => {\n const row = this.requireStatus(input.projectId, input.nodeRunId, \"running\")\n assertSqliteWorkflowAgentNodeOwnership(row, input.executionToken)\n this.db\n .query(`\n UPDATE workflow_agent_node_runs SET\n status = ?, model_id = COALESCE(?, model_id), finish_reason = ?, trace = ?,\n diagnostics = ?, error = ?, execution_token = NULL,\n execution_queue_lease_expires_at = NULL, completed_at = ?\n WHERE project_id = ? AND node_run_id = ?\n `)\n .run(\n input.status,\n input.modelId ?? null,\n input.finishReason ?? null,\n input.trace ? JSON.stringify(input.trace) : null,\n input.diagnostics ? JSON.stringify(input.diagnostics) : null,\n input.status === \"succeeded\" || input.error === undefined\n ? null\n : serializeSixbFailure(input.error, AGENT_RUN_FAILURE_CODES),\n (input.completedAt ?? new Date()).toISOString(),\n input.projectId,\n input.nodeRunId\n )\n return this.require(input.projectId, input.nodeRunId)\n })()\n }\n\n async cancel(input: CancelWorkflowAgentNodeRunInput): Promise<WorkflowAgentNodeRunRecord> {\n return this.db.transaction(() => {\n const row = this.require(input.projectId, input.nodeRunId)\n if (row.status !== \"queued\" && row.status !== \"running\") {\n throw new WorkflowRunError(\n `[SixbSqlite] Agent workflow node run '${input.nodeRunId}' cannot be cancelled from status '${row.status}'.`\n )\n }\n this.db\n .query(\n `UPDATE workflow_agent_node_runs SET status = ?, error = ?, execution_token = NULL,\n execution_queue_lease_expires_at = NULL, completed_at = ?\n WHERE project_id = ? AND node_run_id = ?`\n )\n .run(\n \"cancelled\",\n input.error === undefined\n ? null\n : serializeSixbFailure(input.error, AGENT_RUN_FAILURE_CODES),\n (input.completedAt ?? new Date()).toISOString(),\n input.projectId,\n input.nodeRunId\n )\n return this.require(input.projectId, input.nodeRunId)\n })()\n }\n\n async getByNodeRunId(params: {\n projectId: string\n nodeRunId: string\n }): Promise<WorkflowAgentNodeRunRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM workflow_agent_node_runs WHERE project_id = ? AND node_run_id = ?\")\n .get(params.projectId, params.nodeRunId) as WorkflowAgentNodeRunDatabaseRow | null\n return row ? rowToWorkflowAgentNodeRunRecord(row) : null\n }\n\n async list(input: ListWorkflowAgentNodeRunsInput): Promise<ListWorkflowAgentNodeRunsResult> {\n if (hasEmptyStatuses(input)) return { runs: [], total: 0, hasMore: false }\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n if (input.actorId) {\n whereClauses.push(\"actor_id = ?\")\n args.push(input.actorId)\n }\n appendRunListFilters(whereClauses, args, input)\n const result = queryRunList<WorkflowAgentNodeRunDatabaseRow>({\n db: this.db,\n tableName: \"workflow_agent_node_runs\",\n whereClauses,\n args,\n order: input.order,\n limit: input.limit,\n offset: input.offset,\n })\n return { ...result, runs: result.rows.map(rowToWorkflowAgentNodeRunRecord) }\n }\n\n private require(projectId: string, nodeRunId: string): WorkflowAgentNodeRunRecord {\n const row = this.db\n .query(\"SELECT * FROM workflow_agent_node_runs WHERE project_id = ? AND node_run_id = ?\")\n .get(projectId, nodeRunId) as WorkflowAgentNodeRunDatabaseRow | null\n if (!row) {\n throw new WorkflowRunError(\n `[SixbSqlite] Agent workflow node run '${nodeRunId}' not found for project '${projectId}'.`\n )\n }\n return rowToWorkflowAgentNodeRunRecord(row)\n }\n\n private requireStatus(\n projectId: string,\n nodeRunId: string,\n status: WorkflowAgentNodeRunRecord[\"status\"]\n ): WorkflowAgentNodeRunDatabaseRow {\n const row = this.db\n .query(\"SELECT * FROM workflow_agent_node_runs WHERE project_id = ? AND node_run_id = ?\")\n .get(projectId, nodeRunId) as WorkflowAgentNodeRunDatabaseRow | null\n if (!row) {\n throw new WorkflowRunError(\n `[SixbSqlite] Agent workflow node run '${nodeRunId}' not found for project '${projectId}'.`\n )\n }\n if (row.status !== status) {\n throw new WorkflowRunError(\n `[SixbSqlite] Agent workflow node run '${nodeRunId}' must be ${status} (status '${row.status}').`\n )\n }\n return row\n }\n}\n\nexport class SqliteWorkflowNodeRunStorage implements WorkflowNodeRunStorage {\n constructor(private readonly db: Database) {}\n\n async start(input: StartWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord> {\n assertNonNegativeInteger(input.nodeIndex, \"nodeIndex\")\n\n return this.db.transaction(() => {\n const workflowRun = this.db\n .query(\"SELECT * FROM workflow_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.workflowRunId) as WorkflowRunDatabaseRow | null\n\n if (!workflowRun) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow run '${input.workflowRunId}' not found for project '${input.projectId}'.`\n )\n }\n\n if (workflowRun.status !== \"running\") {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow run '${input.workflowRunId}' for project '${input.projectId}' must be running.`\n )\n }\n assertSqliteWorkflowRunOwnership(workflowRun, input.executionToken)\n\n if (workflowRun.workflow_id !== input.workflowId) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow node run '${input.id}' workflow '${input.workflowId}' does not match workflow run '${input.workflowRunId}' workflow '${workflowRun.workflow_id}'.`\n )\n }\n\n const startedAt = input.startedAt ?? new Date()\n\n try {\n this.db\n .query(\n `\n INSERT INTO workflow_node_runs (\n project_id,\n id,\n workflow_run_id,\n workflow_id,\n node_index,\n node_type,\n node_id,\n node_key,\n status,\n input,\n started_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `\n )\n .run(\n input.projectId,\n input.id,\n input.workflowRunId,\n input.workflowId,\n input.nodeIndex,\n input.nodeType,\n input.nodeId,\n input.nodeKey,\n \"running\",\n serializeRecord(input.input),\n startedAt.toISOString()\n )\n } catch (error) {\n if (isUniqueConstraintError(error)) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow node run '${input.id}' already exists for project '${input.projectId}'.`\n )\n }\n\n throw error\n }\n\n const row = this.db\n .query(\"SELECT * FROM workflow_node_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as WorkflowNodeRunDatabaseRow | null\n\n if (!row) {\n throw new WorkflowRunError(\n `[SixbSqlite] Failed to load workflow node run '${input.id}' for project '${input.projectId}'.`\n )\n }\n\n return rowToWorkflowNodeRunRecord(row)\n })()\n }\n\n async finish(input: FinishWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord> {\n return this.db.transaction(() => {\n const existing = this.db\n .query(\"SELECT * FROM workflow_node_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as WorkflowNodeRunDatabaseRow | null\n\n if (!existing) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow node run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n this.assertNodeParentOwnership(existing, input.executionToken)\n\n if (existing.status !== \"running\" && existing.status !== \"waiting\") {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow node run '${input.id}' for project '${input.projectId}' is already terminal.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE workflow_node_runs\n SET\n status = ?,\n finished_at = ?,\n output = ?,\n error = ?\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\n input.status,\n (input.finishedAt ?? new Date()).toISOString(),\n input.status === \"succeeded\" && input.output ? serializeRecord(input.output) : null,\n input.status === \"succeeded\" || input.error === undefined\n ? null\n : serializeSixbFailure(input.error, WORKFLOW_RUN_FAILURE_CODES),\n input.projectId,\n input.id\n )\n\n const updated = this.db\n .query(\"SELECT * FROM workflow_node_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as WorkflowNodeRunDatabaseRow\n\n return rowToWorkflowNodeRunRecord(updated)\n })()\n }\n\n async wait(input: WaitWorkflowNodeRunInput): Promise<WorkflowNodeRunRecord> {\n return this.db.transaction(() => {\n const existing = this.db\n .query(\"SELECT * FROM workflow_node_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as WorkflowNodeRunDatabaseRow | null\n\n if (!existing) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow node run '${input.id}' not found for project '${input.projectId}'.`\n )\n }\n this.assertNodeParentOwnership(existing, input.executionToken)\n\n if (existing.status !== \"running\") {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow node run '${input.id}' for project '${input.projectId}' must be running.`\n )\n }\n\n this.db\n .query(\n `\n UPDATE workflow_node_runs\n SET\n status = ?,\n finished_at = NULL,\n output = NULL,\n error = NULL\n WHERE project_id = ? AND id = ?\n `\n )\n .run(\"waiting\", input.projectId, input.id)\n\n const updated = this.db\n .query(\"SELECT * FROM workflow_node_runs WHERE project_id = ? AND id = ?\")\n .get(input.projectId, input.id) as WorkflowNodeRunDatabaseRow\n\n return rowToWorkflowNodeRunRecord(updated)\n })()\n }\n\n async getById(params: { projectId: string; id: string }): Promise<WorkflowNodeRunRecord | null> {\n const row = this.db\n .query(\"SELECT * FROM workflow_node_runs WHERE project_id = ? AND id = ?\")\n .get(params.projectId, params.id) as WorkflowNodeRunDatabaseRow | null\n\n return row ? rowToWorkflowNodeRunRecord(row) : null\n }\n\n async list(input: ListWorkflowNodeRunsInput): Promise<ListWorkflowNodeRunsResult> {\n if (hasEmptyStatuses(input)) {\n return {\n nodes: [],\n hasMore: false,\n total: 0,\n }\n }\n\n const whereClauses = [\"project_id = ?\"]\n const args: SqliteValue[] = [input.projectId]\n\n if (input.workflowRunId) {\n whereClauses.push(\"workflow_run_id = ?\")\n args.push(input.workflowRunId)\n }\n\n if (input.workflowId) {\n whereClauses.push(\"workflow_id = ?\")\n args.push(input.workflowId)\n }\n\n if (input.nodeType) {\n whereClauses.push(\"node_type = ?\")\n args.push(input.nodeType)\n }\n\n if (input.nodeId) {\n whereClauses.push(\"node_id = ?\")\n args.push(input.nodeId)\n }\n\n if (input.nodeKey) {\n whereClauses.push(\"node_key = ?\")\n args.push(input.nodeKey)\n }\n\n appendRunListFilters(whereClauses, args, input)\n\n const { rows, total, hasMore } = queryRunList<WorkflowNodeRunDatabaseRow>({\n db: this.db,\n tableName: \"workflow_node_runs\",\n whereClauses,\n args,\n order: input.order,\n limit: input.limit,\n offset: input.offset,\n })\n\n return {\n nodes: rows.map(rowToWorkflowNodeRunRecord),\n hasMore,\n total,\n }\n }\n\n private assertNodeParentOwnership(node: WorkflowNodeRunDatabaseRow, token?: string): void {\n const run = this.db\n .query(\"SELECT * FROM workflow_runs WHERE project_id = ? AND id = ?\")\n .get(node.project_id, node.workflow_run_id) as WorkflowRunDatabaseRow | null\n if (!run) throw new WorkflowRunError(\"[SixbSqlite] Parent workflow run was not found.\")\n assertSqliteWorkflowRunOwnership(run, token)\n }\n}\n\nfunction serializeRecord(value: WorkflowIOSnapshot): string {\n return JSON.stringify(value)\n}\n\nfunction parseRecord(value: string): WorkflowIOSnapshot {\n return JSON.parse(value) as WorkflowIOSnapshot\n}\n\nfunction rowToWorkflowRunRecord(row: WorkflowRunDatabaseRow): WorkflowRunRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n executionId: row.execution_id,\n workflowId: row.workflow_id,\n status: row.status,\n input: parseRecord(row.input),\n output: row.output ? parseRecord(row.output) : undefined,\n queuedAt: row.queued_at ? new Date(row.queued_at) : undefined,\n startedAt: new Date(row.started_at),\n finishedAt: row.finished_at ? new Date(row.finished_at) : undefined,\n error: row.error === null ? undefined : parseSixbFailure(row.error, WORKFLOW_RUN_FAILURE_CODES),\n attempt: row.attempt,\n ...(row.execution_token && row.execution_queue_lease_expires_at\n ? {\n execution: {\n token: row.execution_token,\n queueLeaseExpiresAt: new Date(row.execution_queue_lease_expires_at),\n },\n }\n : {}),\n }\n}\n\nfunction rowToWorkflowNodeRunRecord(row: WorkflowNodeRunDatabaseRow): WorkflowNodeRunRecord {\n return {\n id: row.id,\n projectId: row.project_id,\n workflowRunId: row.workflow_run_id,\n workflowId: row.workflow_id,\n nodeIndex: row.node_index,\n nodeType: row.node_type,\n nodeId: row.node_id,\n nodeKey: row.node_key,\n status: row.status,\n input: parseRecord(row.input),\n startedAt: new Date(row.started_at),\n finishedAt: row.finished_at ? new Date(row.finished_at) : undefined,\n output: row.output ? parseRecord(row.output) : undefined,\n error: row.error === null ? undefined : parseSixbFailure(row.error, WORKFLOW_RUN_FAILURE_CODES),\n }\n}\n\nfunction assertNonNegativeInteger(value: number, fieldName: string): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new WorkflowRunError(\n `[SixbSqlite] Workflow run ${fieldName} must be a non-negative integer.`\n )\n }\n}\n\nfunction canFinishWorkflowRun(\n current: WorkflowRunRecord[\"status\"],\n next: FinishWorkflowRunInput[\"status\"]\n): boolean {\n return (\n current === \"running\" ||\n (current === \"waiting\" && next !== \"succeeded\") ||\n (current === \"queued\" && next !== \"succeeded\")\n )\n}\n\ninterface WorkflowRunDatabaseRow {\n project_id: string\n id: string\n execution_id: string\n workflow_id: string\n status: WorkflowRunRecord[\"status\"]\n input: string\n output: string | null\n queued_at: string | null\n started_at: string\n finished_at: string | null\n error: string | null\n attempt: number\n execution_token: string | null\n execution_queue_lease_expires_at: string | null\n}\n\ninterface WorkflowNodeRunDatabaseRow {\n project_id: string\n id: string\n workflow_run_id: string\n workflow_id: string\n node_index: number\n node_type: WorkflowNodeRunRecord[\"nodeType\"]\n node_id: string\n node_key: string\n status: WorkflowNodeRunRecord[\"status\"]\n input: string\n started_at: string\n finished_at: string | null\n output: string | null\n error: string | null\n}\n\ninterface WorkflowAgentNodeRunDatabaseRow {\n project_id: string\n node_run_id: string\n execution_id: string\n actor_id: string\n status: WorkflowAgentNodeRunRecord[\"status\"]\n prompt: string\n model_id: string | null\n finish_reason: WorkflowAgentNodeRunRecord[\"finishReason\"] | null\n trace: string | null\n diagnostics: string | null\n error: string | null\n attempt: number\n execution_token: string | null\n execution_queue_lease_expires_at: string | null\n created_at: string\n started_at: string | null\n completed_at: string | null\n}\n\nfunction assertSqliteWorkflowAgentNodeOwnership(\n row: WorkflowAgentNodeRunDatabaseRow,\n token: string\n): void {\n if (row.execution_token !== token) {\n throw new WorkflowRunError(\n `[SixbSqlite] Execution token is no longer current on agent workflow node run '${row.node_run_id}'.`\n )\n }\n}\n\nfunction rowToWorkflowAgentNodeRunRecord(\n row: WorkflowAgentNodeRunDatabaseRow\n): WorkflowAgentNodeRunRecord {\n return {\n projectId: row.project_id,\n nodeRunId: row.node_run_id,\n executionId: row.execution_id,\n actorId: row.actor_id,\n status: row.status,\n prompt: row.prompt,\n ...(row.model_id ? { modelId: row.model_id } : {}),\n ...(row.finish_reason ? { finishReason: row.finish_reason } : {}),\n ...(row.trace ? { trace: JSON.parse(row.trace) } : {}),\n ...(row.diagnostics ? { diagnostics: JSON.parse(row.diagnostics) } : {}),\n ...(row.error ? { error: parseSixbFailure(row.error, AGENT_RUN_FAILURE_CODES) } : {}),\n attempt: row.attempt,\n ...(row.execution_token && row.execution_queue_lease_expires_at\n ? {\n execution: {\n token: row.execution_token,\n queueLeaseExpiresAt: new Date(row.execution_queue_lease_expires_at),\n },\n }\n : {}),\n createdAt: new Date(row.created_at),\n ...(row.started_at ? { startedAt: new Date(row.started_at) } : {}),\n ...(row.completed_at ? { completedAt: new Date(row.completed_at) } : {}),\n }\n}\n\nfunction assertSqliteWorkflowRunOwnership(row: WorkflowRunDatabaseRow, token?: string): void {\n if (row.execution_token !== (token ?? null)) {\n throw new WorkflowRunError(\n `[SixbSqlite] Execution token is no longer current on workflow run '${row.id}'.`\n )\n }\n}\n"
75
81
  ],
76
- "mappings": ";;AAIA;AAOA;AACA;AAAA;AAAA;AAAA;AAIA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA;AAAA;AAAA;;;ACvBA;AAAA;AAAA;AAAA;AAIA;AACA;AAcA;;;ACp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