@sixb/pg 0.1.11 → 0.1.13

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 (74) hide show
  1. package/README.md +34 -0
  2. package/dist/agents/rows.d.ts +3 -1
  3. package/dist/agents/rows.d.ts.map +1 -1
  4. package/dist/agents/threads.d.ts +3 -2
  5. package/dist/agents/threads.d.ts.map +1 -1
  6. package/dist/auth-storage/access-tokens.d.ts.map +1 -1
  7. package/dist/auth-storage/device-authorizations.d.ts.map +1 -1
  8. package/dist/auth-storage/rows.d.ts +6 -3
  9. package/dist/auth-storage/rows.d.ts.map +1 -1
  10. package/dist/auth-storage/sessions.d.ts +8 -1
  11. package/dist/auth-storage/sessions.d.ts.map +1 -1
  12. package/dist/auth-storage/shared.d.ts.map +1 -1
  13. package/dist/index.d.ts +2 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +917 -122
  16. package/dist/index.js.map +26 -23
  17. package/dist/migrations.d.ts.map +1 -1
  18. package/dist/objects/query-compiler.d.ts +8 -1
  19. package/dist/objects/query-compiler.d.ts.map +1 -1
  20. package/dist/objects/read-scope.d.ts +1 -0
  21. package/dist/objects/read-scope.d.ts.map +1 -1
  22. package/dist/objects/reader.d.ts +1 -0
  23. package/dist/objects/reader.d.ts.map +1 -1
  24. package/dist/objects/rows.d.ts +1 -0
  25. package/dist/objects/rows.d.ts.map +1 -1
  26. package/dist/objects/storage.d.ts +1 -1
  27. package/dist/objects/storage.d.ts.map +1 -1
  28. package/dist/ontology-storage/index.d.ts +4 -0
  29. package/dist/ontology-storage/index.d.ts.map +1 -1
  30. package/dist/ontology-storage/materializations.d.ts +1 -2
  31. package/dist/ontology-storage/materializations.d.ts.map +1 -1
  32. package/dist/ontology-storage/shared.d.ts +2 -1
  33. package/dist/ontology-storage/shared.d.ts.map +1 -1
  34. package/dist/ontology-storage/vector-indexing.d.ts +20 -0
  35. package/dist/ontology-storage/vector-indexing.d.ts.map +1 -0
  36. package/dist/ontology-storage/vectors.d.ts +16 -0
  37. package/dist/ontology-storage/vectors.d.ts.map +1 -0
  38. package/dist/pg-ai-cost-storage.d.ts.map +1 -1
  39. package/dist/pg-file-upload-session-storage.d.ts +6 -0
  40. package/dist/pg-file-upload-session-storage.d.ts.map +1 -0
  41. package/dist/pg-workflow-intervention-storage.d.ts.map +1 -1
  42. package/package.json +3 -3
  43. package/src/agents/rows.ts +21 -0
  44. package/src/agents/threads.ts +47 -2
  45. package/src/auth-storage/access-tokens.ts +10 -14
  46. package/src/auth-storage/auth-storage.ts +4 -6
  47. package/src/auth-storage/device-authorizations.ts +3 -4
  48. package/src/auth-storage/rows.ts +17 -7
  49. package/src/auth-storage/sessions.ts +82 -4
  50. package/src/auth-storage/shared.ts +8 -2
  51. package/src/index.ts +5 -0
  52. package/src/migrations/041-agent-thread-workspaces.sql +2 -0
  53. package/src/migrations/042-vector-profiles.sql +28 -0
  54. package/src/migrations/043-vector-indexing.sql +24 -0
  55. package/src/migrations/044-vector-batching.sql +3 -0
  56. package/src/migrations/045-agent-thread-sandbox-state.sql +2 -0
  57. package/src/migrations/046-workflow-intervention-principals.sql +15 -0
  58. package/src/migrations/047-ontology-commit-attribution.sql +50 -0
  59. package/src/migrations/048-file-upload-sessions.sql +34 -0
  60. package/src/migrations/049-native-sessions.sql +19 -0
  61. package/src/migrations.ts +26 -0
  62. package/src/objects/query-compiler.ts +102 -11
  63. package/src/objects/read-scope.ts +26 -25
  64. package/src/objects/reader.ts +33 -1
  65. package/src/objects/rows.ts +5 -1
  66. package/src/objects/storage.ts +22 -2
  67. package/src/ontology-storage/index.ts +15 -0
  68. package/src/ontology-storage/materializations.ts +28 -58
  69. package/src/ontology-storage/shared.ts +7 -3
  70. package/src/ontology-storage/vector-indexing.ts +168 -0
  71. package/src/ontology-storage/vectors.ts +172 -0
  72. package/src/pg-ai-cost-storage.ts +4 -0
  73. package/src/pg-file-upload-session-storage.ts +143 -0
  74. package/src/pg-workflow-intervention-storage.ts +11 -15
@@ -76,6 +76,11 @@ export interface PgAuthSessionRow {
76
76
  readonly last_seen_at: PgDate | null
77
77
  readonly user_agent: string | null
78
78
  readonly ip_address: string | null
79
+ readonly client_name: string | null
80
+ readonly access_expires_at: PgDate | null
81
+ readonly refresh_token_hash: string | null
82
+ readonly previous_refresh_token_hash: string | null
83
+ readonly refreshed_at: PgDate | null
79
84
  }
80
85
 
81
86
  export interface PgAuthAccessTokenRow {
@@ -83,7 +88,7 @@ export interface PgAuthAccessTokenRow {
83
88
  readonly id: string
84
89
  readonly name: string
85
90
  readonly kind: AccessTokenRecord["kind"]
86
- readonly subject_type: AccessTokenRecord["subjectType"]
91
+ readonly subject_type: AccessTokenRecord["subject"]["type"]
87
92
  readonly subject_id: string
88
93
  readonly token_hash: string
89
94
  readonly group_ids: readonly string[] | string | null
@@ -157,8 +162,6 @@ export interface PgAuthDeviceAuthorizationRow {
157
162
  readonly device_code_hash: string
158
163
  readonly user_code: string
159
164
  readonly client_name: string
160
- readonly token_name: string
161
- readonly token_expires_at: PgDate
162
165
  readonly status: DeviceAuthorizationRecord["status"]
163
166
  readonly approved_user_id: string | null
164
167
  readonly approved_session_id: string | null
@@ -235,6 +238,16 @@ export function rowToSessionRecord(row: PgAuthSessionRow): SessionRecord {
235
238
  lastSeenAt: row.last_seen_at ? toDate(row.last_seen_at) : undefined,
236
239
  userAgent: row.user_agent ?? undefined,
237
240
  ipAddress: row.ip_address ?? undefined,
241
+ bearer:
242
+ row.refresh_token_hash !== null && row.client_name !== null && row.access_expires_at !== null
243
+ ? {
244
+ clientName: row.client_name,
245
+ accessExpiresAt: toDate(row.access_expires_at),
246
+ refreshTokenHash: row.refresh_token_hash,
247
+ previousRefreshTokenHash: row.previous_refresh_token_hash ?? undefined,
248
+ refreshedAt: row.refreshed_at ? toDate(row.refreshed_at) : undefined,
249
+ }
250
+ : undefined,
238
251
  }
239
252
  }
240
253
 
@@ -244,8 +257,7 @@ export function rowToAccessTokenRecord(row: PgAuthAccessTokenRow): AccessTokenRe
244
257
  projectId: row.project_id,
245
258
  name: row.name,
246
259
  kind: row.kind,
247
- subjectType: row.subject_type,
248
- subjectId: row.subject_id,
260
+ subject: { type: row.subject_type, id: row.subject_id },
249
261
  tokenHash: row.token_hash,
250
262
  groupIds: parseOptionalStringArray(row.group_ids),
251
263
  createdByPrincipal: principalFromColumns(row),
@@ -332,8 +344,6 @@ export function rowToDeviceAuthorizationRecord(
332
344
  deviceCodeHash: row.device_code_hash,
333
345
  userCode: row.user_code,
334
346
  clientName: row.client_name,
335
- tokenName: row.token_name,
336
- tokenExpiresAt: toDate(row.token_expires_at),
337
347
  status: row.status,
338
348
  approvedUserId: row.approved_user_id ?? undefined,
339
349
  approvedSessionId: row.approved_session_id ?? undefined,
@@ -1,5 +1,10 @@
1
1
  import type { AuthSessionAudience } from "@sixb/core"
2
- import type { AuthSessionStore, CreateAuthSessionInput, SessionRecord } from "@sixb/core/storage"
2
+ import type {
3
+ AuthSessionStore,
4
+ CreateAuthSessionInput,
5
+ RotateSessionRefreshTokenResult,
6
+ SessionRecord,
7
+ } from "@sixb/core/storage"
3
8
  import { AuthStorageError } from "@sixb/core/storage"
4
9
  import {
5
10
  authLockKey,
@@ -85,11 +90,10 @@ export class PgAuthSessionStore implements AuthSessionStore {
85
90
 
86
91
  if (
87
92
  !row ||
93
+ row.refresh_token_hash !== null ||
88
94
  row.audience !== params.audience ||
89
95
  row.token_hash !== params.tokenHash ||
90
- row.revoked_at ||
91
- new Date(row.expires_at) <= params.now ||
92
- (row.absolute_expires_at !== null && new Date(row.absolute_expires_at) <= params.now)
96
+ !isLiveSessionRow(row, params.now)
93
97
  ) {
94
98
  return null
95
99
  }
@@ -97,6 +101,71 @@ export class PgAuthSessionStore implements AuthSessionStore {
97
101
  return rowToSessionRecord(row)
98
102
  }
99
103
 
104
+ async findValidByAccessTokenHash(params: {
105
+ readonly projectId: string
106
+ readonly id: string
107
+ readonly tokenHash: string
108
+ readonly now: Date
109
+ }): Promise<SessionRecord | null> {
110
+ const row = await getSessionRowById(this.sql, params)
111
+ if (
112
+ !row ||
113
+ row.access_expires_at === null ||
114
+ row.token_hash !== params.tokenHash ||
115
+ new Date(row.access_expires_at) <= params.now ||
116
+ !isLiveSessionRow(row, params.now)
117
+ ) {
118
+ return null
119
+ }
120
+
121
+ return rowToSessionRecord(row)
122
+ }
123
+
124
+ async rotateRefreshToken(
125
+ params: Parameters<AuthSessionStore["rotateRefreshToken"]>[0]
126
+ ): Promise<RotateSessionRefreshTokenResult> {
127
+ return runPgTransaction(this.sql, async (tx): Promise<RotateSessionRefreshTokenResult> => {
128
+ const row = await getSessionRowById(tx, params, { forUpdate: true })
129
+ if (!row?.refresh_token_hash || !isLiveSessionRow(row, params.now)) {
130
+ return { status: "invalid" }
131
+ }
132
+
133
+ const replacedRecently =
134
+ row.previous_refresh_token_hash === params.refreshTokenHash &&
135
+ row.refreshed_at !== null &&
136
+ params.now.getTime() - new Date(row.refreshed_at).getTime() <= params.reuseGraceMs
137
+ if (row.refresh_token_hash !== params.refreshTokenHash && !replacedRecently) {
138
+ if (row.previous_refresh_token_hash !== params.refreshTokenHash) {
139
+ return { status: "invalid" }
140
+ }
141
+ await tx`
142
+ UPDATE auth_sessions SET revoked_at = ${params.now}
143
+ WHERE project_id = ${params.projectId} AND id = ${params.id}
144
+ `
145
+ return { status: "reused" }
146
+ }
147
+
148
+ const [rotated] = await tx<PgAuthSessionRow[]>`
149
+ UPDATE auth_sessions
150
+ SET token_hash = ${params.next.tokenHash},
151
+ access_expires_at = ${params.next.accessExpiresAt},
152
+ previous_refresh_token_hash = refresh_token_hash,
153
+ refresh_token_hash = ${params.next.refreshTokenHash},
154
+ refreshed_at = ${params.now},
155
+ last_seen_at = ${params.now},
156
+ expires_at = GREATEST(
157
+ expires_at,
158
+ LEAST(${params.next.expiresAt}, COALESCE(absolute_expires_at, ${params.next.expiresAt}))
159
+ )
160
+ WHERE project_id = ${params.projectId} AND id = ${params.id}
161
+ RETURNING *
162
+ `
163
+ return rotated
164
+ ? { status: "rotated", session: rowToSessionRecord(rotated) }
165
+ : { status: "invalid" }
166
+ })
167
+ }
168
+
100
169
  async renewIfValid(params: {
101
170
  readonly projectId: string
102
171
  readonly id: string
@@ -119,6 +188,7 @@ export class PgAuthSessionStore implements AuthSessionStore {
119
188
  AND id = ${params.id}
120
189
  AND audience = ${params.audience}
121
190
  AND token_hash = ${params.tokenHash}
191
+ AND refresh_token_hash IS NULL
122
192
  AND revoked_at IS NULL
123
193
  AND expires_at > ${params.now}
124
194
  AND (absolute_expires_at IS NULL OR absolute_expires_at > ${params.now})
@@ -191,3 +261,11 @@ export class PgAuthSessionStore implements AuthSessionStore {
191
261
  })
192
262
  }
193
263
  }
264
+
265
+ function isLiveSessionRow(row: PgAuthSessionRow, now: Date): boolean {
266
+ return (
267
+ row.revoked_at === null &&
268
+ new Date(row.expires_at) > now &&
269
+ (row.absolute_expires_at === null || new Date(row.absolute_expires_at) > now)
270
+ )
271
+ }
@@ -487,7 +487,10 @@ export async function createSession(
487
487
  expires_at,
488
488
  absolute_expires_at,
489
489
  user_agent,
490
- ip_address
490
+ ip_address,
491
+ client_name,
492
+ access_expires_at,
493
+ refresh_token_hash
491
494
  ) VALUES (
492
495
  ${projectId},
493
496
  ${id},
@@ -499,7 +502,10 @@ export async function createSession(
499
502
  ${input.expiresAt},
500
503
  ${input.absoluteExpiresAt ?? null},
501
504
  ${input.userAgent ?? null},
502
- ${input.ipAddress ?? null}
505
+ ${input.ipAddress ?? null},
506
+ ${input.bearer ? assertNonEmpty(input.bearer.clientName, "Session client name") : null},
507
+ ${input.bearer?.accessExpiresAt ?? null},
508
+ ${input.bearer ? assertNonEmpty(input.bearer.refreshTokenHash, "Refresh token hash") : null}
503
509
  )
504
510
  RETURNING *
505
511
  `
package/src/index.ts CHANGED
@@ -42,6 +42,7 @@ import { PgAiLimitStorage } from "./pg-ai-limit-storage"
42
42
  import { PgAiUsageStorage } from "./pg-ai-usage-storage"
43
43
  import { createPgClient, type SQL, type SQLClient } from "./pg-client"
44
44
  import { PgExecutionStorage } from "./pg-execution-storage"
45
+ import { PgFileUploadSessionStorage } from "./pg-file-upload-session-storage"
45
46
  import { PgPipelineRunStorage } from "./pg-pipeline-run-storage"
46
47
  import { PgProjectionRunStorage } from "./pg-projection-run-storage"
47
48
  import { PgRulesStorage } from "./pg-rules-storage"
@@ -158,6 +159,7 @@ export class PostgresStorage implements MigrationCapableStorage {
158
159
  readonly connectorConnections: PgConnectorConnectionStorage
159
160
  readonly shareGrants: PgShareGrantStorage
160
161
  readonly shareSessions: PgShareSessionStorage
162
+ readonly fileUploadSessions: PgFileUploadSessionStorage
161
163
  readonly migrators: readonly StorageMigrator[]
162
164
 
163
165
  private readonly sql: SQL
@@ -235,6 +237,7 @@ export class PostgresStorage implements MigrationCapableStorage {
235
237
  this.connectorConnections = createOperationScopedFacade(stores.connectorConnections, scope)
236
238
  this.shareGrants = createOperationScopedFacade(stores.shareGrants, scope)
237
239
  this.shareSessions = createOperationScopedFacade(stores.shareSessions, scope)
240
+ this.fileUploadSessions = createOperationScopedFacade(stores.fileUploadSessions, scope)
238
241
  registerPostgresStorageTestingAdapter(this, (durationMs) =>
239
242
  stores.connectorConnections.advanceTimeForTesting(durationMs)
240
243
  )
@@ -371,6 +374,7 @@ function createPostgresStores(
371
374
  connectorConnections: new PgConnectorConnectionStorage(sql),
372
375
  shareGrants,
373
376
  shareSessions,
377
+ fileUploadSessions: new PgFileUploadSessionStorage(sql),
374
378
  }
375
379
  }
376
380
 
@@ -395,6 +399,7 @@ interface PostgresStoreSet {
395
399
  readonly connectorConnections: PgConnectorConnectionStorage
396
400
  readonly shareGrants: PgShareGrantStorage
397
401
  readonly shareSessions: PgShareSessionStorage
402
+ readonly fileUploadSessions: PgFileUploadSessionStorage
398
403
  }
399
404
 
400
405
  function resolveTimeoutMillis(value: number | undefined, label: string): number | undefined {
@@ -0,0 +1,2 @@
1
+ ALTER TABLE agent_threads ADD COLUMN sandbox_params JSONB
2
+ CHECK (sandbox_params IS NULL OR jsonb_typeof(sandbox_params) = 'object');
@@ -0,0 +1,28 @@
1
+ -- Transactional derived state. Search extensions are not required for persistence.
2
+ CREATE TABLE object_vectors (
3
+ project_id TEXT NOT NULL,
4
+ object_type_id TEXT NOT NULL,
5
+ primary_id TEXT NOT NULL,
6
+ profile TEXT NOT NULL CHECK (length(btrim(profile)) > 0),
7
+ configuration TEXT NOT NULL,
8
+ source TEXT[] NOT NULL,
9
+ source_fingerprint TEXT NOT NULL,
10
+ embedding REAL[] NOT NULL,
11
+ last_commit_id TEXT NOT NULL,
12
+ PRIMARY KEY (project_id, object_type_id, primary_id, profile),
13
+ FOREIGN KEY (project_id, object_type_id, primary_id)
14
+ REFERENCES objects (project_id, object_type_id, primary_id) ON DELETE CASCADE,
15
+ FOREIGN KEY (project_id, last_commit_id)
16
+ REFERENCES ontology_commits (project_id, id) DEFERRABLE INITIALLY DEFERRED,
17
+ CONSTRAINT object_vectors_sources CHECK (
18
+ cardinality(source) > 0 AND array_ndims(source) = 1 AND array_lower(source, 1) = 1
19
+ AND array_position(source, NULL) IS NULL
20
+ ),
21
+ CONSTRAINT object_vectors_values CHECK (
22
+ cardinality(embedding) BETWEEN 1 AND 16000
23
+ AND array_ndims(embedding) = 1 AND array_lower(embedding, 1) = 1
24
+ AND array_position(embedding, NULL) IS NULL
25
+ AND '-Infinity'::real < ALL(embedding) AND 'Infinity'::real > ALL(embedding)
26
+ AND 0::real <> ANY(embedding)
27
+ )
28
+ );
@@ -0,0 +1,24 @@
1
+ CREATE TABLE object_vector_indexing (
2
+ project_id TEXT NOT NULL,
3
+ id TEXT NOT NULL,
4
+ object_type_id TEXT NOT NULL,
5
+ primary_id TEXT NOT NULL,
6
+ profile TEXT NOT NULL,
7
+ request JSONB NOT NULL,
8
+ status TEXT NOT NULL CHECK (status IN ('pending', 'running', 'ready', 'failed')),
9
+ available_at TIMESTAMPTZ NOT NULL,
10
+ dispatch_at TIMESTAMPTZ NOT NULL,
11
+ values_json JSONB,
12
+ error TEXT,
13
+ PRIMARY KEY (project_id, id),
14
+ UNIQUE (project_id, object_type_id, primary_id, profile)
15
+ );
16
+ CREATE INDEX object_vector_indexing_due ON object_vector_indexing (project_id, dispatch_at, id)
17
+ WHERE status <> 'failed';
18
+
19
+ ALTER TABLE executions DROP CONSTRAINT executions_authority_kernel_operation_check;
20
+ ALTER TABLE executions ADD CONSTRAINT executions_authority_kernel_operation_check
21
+ CHECK (authority_kernel_operation IS NULL OR authority_kernel_operation IN ('ontology.recover', 'ontology.indexVectors'));
22
+ ALTER TABLE executions DROP CONSTRAINT executions_source_kind_check;
23
+ ALTER TABLE executions ADD CONSTRAINT executions_source_kind_check
24
+ CHECK (source_kind IN ('http', 'webhook', 'schedule', 'event', 'datasetVersion', 'execution', 'ontologyCommit'));
@@ -0,0 +1,3 @@
1
+ ALTER TABLE object_vector_indexing ADD COLUMN batch_id TEXT;
2
+ CREATE INDEX object_vector_indexing_batch ON object_vector_indexing (project_id, batch_id, id)
3
+ WHERE batch_id IS NOT NULL;
@@ -0,0 +1,2 @@
1
+ ALTER TABLE agent_threads ADD COLUMN sandbox_state JSONB
2
+ CHECK (sandbox_state IS NULL OR jsonb_typeof(sandbox_state) = 'object');
@@ -0,0 +1,15 @@
1
+ -- Intervention actors were stored as { principalType, principalId }. Rewrite them to the
2
+ -- canonical Principal shape { type, id } used by every other stored principal.
3
+ UPDATE workflow_interventions
4
+ SET submitted_by = jsonb_build_object(
5
+ 'type', submitted_by->>'principalType',
6
+ 'id', submitted_by->>'principalId'
7
+ )
8
+ WHERE submitted_by->>'principalType' IS NOT NULL;
9
+
10
+ UPDATE workflow_interventions
11
+ SET cancelled_by = jsonb_build_object(
12
+ 'type', cancelled_by->>'principalType',
13
+ 'id', cancelled_by->>'principalId'
14
+ )
15
+ WHERE cancelled_by->>'principalType' IS NOT NULL;
@@ -0,0 +1,50 @@
1
+ -- Commits and their events name who requested the write and what ran it, replacing the
2
+ -- authority-only `actor`. Both are copied from the commit's execution, which stays canonical and
3
+ -- is immutable, so the backfill is exact.
4
+ ALTER TABLE ontology_commits
5
+ ADD COLUMN requested_by JSONB,
6
+ ADD COLUMN executor JSONB;
7
+
8
+ UPDATE ontology_commits c SET
9
+ requested_by = CASE
10
+ WHEN e.requested_by_user_id IS NOT NULL
11
+ THEN jsonb_build_object('type', 'user', 'id', e.requested_by_user_id)
12
+ WHEN e.requested_by_service_account_id IS NOT NULL
13
+ THEN jsonb_build_object('type', 'serviceAccount', 'id', e.requested_by_service_account_id)
14
+ END,
15
+ executor = CASE e.executor_kind
16
+ WHEN 'request' THEN jsonb_build_object('type', 'request', 'requestId', e.executor_id)
17
+ WHEN 'agent' THEN jsonb_build_object('type', 'agent', 'runId', e.executor_id)
18
+ WHEN 'kernel' THEN jsonb_build_object(
19
+ 'type', 'kernel',
20
+ 'operation',
21
+ CASE e.authority_kernel_operation
22
+ WHEN 'ontology.recover'
23
+ THEN jsonb_build_object('type', 'ontology.recover', 'recoveryId', e.executor_id)
24
+ ELSE jsonb_build_object('type', 'ontology.indexVectors', 'indexingId', e.executor_id)
25
+ END
26
+ )
27
+ ELSE jsonb_build_object(
28
+ 'type', 'primitive',
29
+ 'kind', e.executor_kind,
30
+ 'id', e.authority_primitive_id,
31
+ 'runId', e.executor_id
32
+ )
33
+ END
34
+ FROM executions e
35
+ WHERE e.project_id = c.project_id AND e.id = c.execution_id;
36
+
37
+ ALTER TABLE ontology_commits ALTER COLUMN executor SET NOT NULL;
38
+
39
+ -- Events not yet published would otherwise reach consumers in the retired shape.
40
+ UPDATE ontology_outbox o SET envelope =
41
+ (o.envelope - 'actor')
42
+ || jsonb_build_object('executor', c.executor)
43
+ || CASE
44
+ WHEN c.requested_by IS NULL THEN '{}'::jsonb
45
+ ELSE jsonb_build_object('requestedBy', c.requested_by)
46
+ END
47
+ FROM ontology_commits c
48
+ WHERE c.project_id = o.project_id AND c.id = o.commit_id;
49
+
50
+ ALTER TABLE ontology_commits DROP COLUMN actor;
@@ -0,0 +1,34 @@
1
+ -- Durable staged-upload sessions, so an upload survives restarts and spans API replicas.
2
+ CREATE TABLE file_upload_sessions (
3
+ id TEXT PRIMARY KEY CHECK (length(trim(id)) > 0),
4
+ project_id TEXT NOT NULL CHECK (length(trim(project_id)) > 0),
5
+ owner_principal_type TEXT NOT NULL
6
+ CHECK (owner_principal_type IN ('user', 'serviceAccount', 'system')),
7
+ owner_principal_id TEXT NOT NULL CHECK (length(owner_principal_id) > 0),
8
+ strategy TEXT NOT NULL CHECK (strategy IN ('server', 'direct-put', 'multipart')),
9
+ status TEXT NOT NULL CHECK (status IN ('pending', 'completed', 'aborted')),
10
+ file_name TEXT,
11
+ media_type TEXT,
12
+ logical_path TEXT,
13
+ expected_size_bytes BIGINT CHECK (expected_size_bytes IS NULL OR expected_size_bytes >= 0),
14
+ expected_digest TEXT,
15
+ provider_upload JSONB CHECK (provider_upload IS NULL OR jsonb_typeof(provider_upload) = 'object'),
16
+ signed_parts JSONB NOT NULL CHECK (jsonb_typeof(signed_parts) = 'array'),
17
+ file_ref JSONB CHECK (file_ref IS NULL OR jsonb_typeof(file_ref) = 'object'),
18
+ created_at TIMESTAMPTZ NOT NULL,
19
+ expires_at TIMESTAMPTZ NOT NULL,
20
+ completed_at TIMESTAMPTZ,
21
+ aborted_at TIMESTAMPTZ,
22
+ -- Derived by core (fileUploadSessionReapAt); NULL while an abandoned upload awaits its abort.
23
+ reap_at TIMESTAMPTZ,
24
+ CHECK ((status = 'completed') = (completed_at IS NOT NULL)),
25
+ CHECK ((status = 'aborted') = (aborted_at IS NOT NULL))
26
+ );
27
+
28
+ CREATE INDEX idx_file_upload_sessions_reap
29
+ ON file_upload_sessions (reap_at)
30
+ WHERE reap_at IS NOT NULL;
31
+
32
+ CREATE INDEX idx_file_upload_sessions_abandoned
33
+ ON file_upload_sessions (project_id, expires_at)
34
+ WHERE status = 'pending' AND provider_upload IS NOT NULL;
@@ -0,0 +1,19 @@
1
+ -- Native clients, such as the CLI, hold their session as bearer tokens: a
2
+ -- short-lived access token, whose hash is `token_hash`, and a rotating refresh token. Browser
3
+ -- sessions leave these columns NULL; `refresh_token_hash IS NULL` is what marks a cookie session.
4
+ ALTER TABLE auth_sessions
5
+ ADD COLUMN client_name TEXT,
6
+ ADD COLUMN access_expires_at TIMESTAMPTZ,
7
+ ADD COLUMN refresh_token_hash TEXT,
8
+ ADD COLUMN previous_refresh_token_hash TEXT,
9
+ ADD COLUMN refreshed_at TIMESTAMPTZ,
10
+ ADD CONSTRAINT auth_sessions_bearer_state CHECK (
11
+ (refresh_token_hash IS NULL) = (client_name IS NULL)
12
+ AND (refresh_token_hash IS NULL) = (access_expires_at IS NULL)
13
+ AND (refresh_token_hash IS NOT NULL OR previous_refresh_token_hash IS NULL)
14
+ );
15
+
16
+ -- The device flow now starts a session instead of issuing a personal access token.
17
+ ALTER TABLE auth_device_authorizations
18
+ DROP COLUMN token_name,
19
+ DROP COLUMN token_expires_at;
package/src/migrations.ts CHANGED
@@ -90,6 +90,22 @@ import shareSessionsSql from "./migrations/036-share-sessions.sql" with { type:
90
90
  import projectionSourceRootsSql from "./migrations/039-projection-source-roots.sql" with {
91
91
  type: "text",
92
92
  }
93
+ import agentThreadWorkspacesSql from "./migrations/041-agent-thread-workspaces.sql" with {
94
+ type: "text",
95
+ }
96
+ import vectorProfilesSql from "./migrations/042-vector-profiles.sql" with { type: "text" }
97
+ import vectorIndexingSql from "./migrations/043-vector-indexing.sql" with { type: "text" }
98
+ import vectorBatchingSql from "./migrations/044-vector-batching.sql" with { type: "text" }
99
+ import agentThreadSandboxStateSql from "./migrations/045-agent-thread-sandbox-state.sql" with {
100
+ type: "text",
101
+ }
102
+ import workflowInterventionPrincipalsSql from "./migrations/046-workflow-intervention-principals.sql" with {
103
+ type: "text",
104
+ }
105
+ import ontologyCommitAttributionSql from "./migrations/047-ontology-commit-attribution.sql" with {
106
+ type: "text",
107
+ }
108
+ import nativeSessionsSql from "./migrations/049-native-sessions.sql" with { type: "text" }
93
109
  import type { SQL, SQLClient } from "./pg-client"
94
110
 
95
111
  export interface PostgresMigrationContext {
@@ -383,6 +399,15 @@ export const postgresStorageMigrations = defineMigrations<PostgresMigrationConte
383
399
  pgSql("038-outbox-publication-order", outboxPublicationOrderSql),
384
400
  pgSql("039-projection-source-roots", projectionSourceRootsSql),
385
401
  pgSql("040-connector-optional-pkce", connectorOptionalPkceSql),
402
+ pgSql("041-agent-thread-workspaces", agentThreadWorkspacesSql),
403
+ pgSql("042-vector-profiles", vectorProfilesSql),
404
+ pgSql("043-vector-indexing", vectorIndexingSql),
405
+ pgSql("044-vector-batching", vectorBatchingSql),
406
+ pgSql("045-agent-thread-sandbox-state", agentThreadSandboxStateSql),
407
+ pgSql("046-workflow-intervention-principals", workflowInterventionPrincipalsSql),
408
+ pgSql("047-ontology-commit-attribution", ontologyCommitAttributionSql),
409
+ pgSql("048-file-upload-sessions", fileUploadSessionsSql),
410
+ pgSql("049-native-sessions", nativeSessionsSql),
386
411
  ],
387
412
  })
388
413
 
@@ -406,3 +431,4 @@ import outboxPublicationOrderSql from "./migrations/038-outbox-publication-order
406
431
  import connectorOptionalPkceSql from "./migrations/040-connector-optional-pkce.sql" with {
407
432
  type: "text",
408
433
  }
434
+ import fileUploadSessionsSql from "./migrations/048-file-upload-sessions.sql" with { type: "text" }