-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathschema.ts
More file actions
2683 lines (2569 loc) · 110 KB
/
Copy pathschema.ts
File metadata and controls
2683 lines (2569 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// FILE SIZE EXCEPTION: Database schema — splitting creates import complexity. See .claude/rules/18-file-size-limits.md
//
// =============================================================================
// SCHEMA DOCUMENTATION
// =============================================================================
//
// Timestamp conventions:
// - BetterAuth tables (users, sessions, accounts, verifications, agentSettings,
// apiTokens) use `integer('...', { mode: 'timestamp_ms' })` which stores
// millisecond-epoch integers. Drizzle auto-converts JS Date objects.
// - All other tables use `text('...')` with `DEFAULT CURRENT_TIMESTAMP` or
// `DEFAULT (datetime('now'))`, storing ISO-8601 strings (e.g. "2026-04-12 14:30:00").
// These are compared as strings in SQL and parsed with `new Date()` in TypeScript.
//
// Encryption model:
// - Fields named `encryptedToken` / `storedValue` / `storedContent` hold
// AES-256-GCM ciphertext (base64-encoded).
// - Fields named `iv` / `valueIv` / `contentIv` hold the initialization vector
// (base64-encoded, 12 bytes random per encryption via Web Crypto API).
// - Key management: ENCRYPTION_KEY env var (base64-encoded 256-bit key), with
// optional purpose-specific overrides (PLATFORM_CREDENTIAL_ENCRYPTION_KEY, etc.).
// - Encrypt/decrypt logic: `apps/api/src/services/encryption.ts`
// - File-specific encryption: `apps/api/src/services/file-encryption.ts`
//
// onDelete policy rationale:
// - 'cascade': Used when child rows are meaningless without the parent
// (e.g. sessions without a user, tasks without a project).
// - 'set null': Used when the child row has independent value and should
// survive parent deletion (e.g. workspaces survive node deletion,
// compliance runs survive exception request deletion, tasks survive
// node deletion via autoProvisionedNodeId).
// - No FK constraint: Used for cross-table soft references where the
// referenced entity may not exist in D1 (e.g. chatSessionId references
// a session in the ProjectData Durable Object, not a D1 table).
//
// Credential tables:
// - `credentials`: Per-user credentials (BYOC model). Users provide their own
// cloud provider tokens and agent API keys. Encrypted per-user, cascade on
// user delete.
// - `platformCredentials`: Admin-managed fallback credentials shared across
// users. Used when a user lacks their own credential. No cascade on creator
// delete (uses bare reference) since the credential serves all users.
//
// =============================================================================
import { DEFAULT_WORKSPACE_PROFILE } from '@simple-agent-manager/shared';
import { sql } from 'drizzle-orm';
import {
index,
integer,
primaryKey,
real,
sqliteTable,
text,
uniqueIndex,
} from 'drizzle-orm/sqlite-core';
// =============================================================================
// Users (BetterAuth compatible + custom fields)
// BetterAuth requires integer timestamps with mode: 'timestamp_ms' so that
// Drizzle converts Date objects to millisecond integers for D1 storage.
// =============================================================================
export const users = sqliteTable('users', {
id: text('id').primaryKey(),
email: text('email').notNull(),
emailVerified: integer('email_verified', { mode: 'boolean' }).notNull().default(false),
name: text('name'),
image: text('image'),
// Custom fields
githubId: text('github_id').unique(),
avatarUrl: text('avatar_url'),
// User approval / invite-only mode
role: text('role').notNull().default('user'), // 'superadmin' | 'admin' | 'user'
status: text('status').notNull().default('active'), // 'active' | 'pending' | 'suspended'
createdAt: integer('created_at', { mode: 'timestamp_ms' })
.notNull()
.default(sql`(cast(unixepoch() * 1000 as integer))`),
updatedAt: integer('updated_at', { mode: 'timestamp_ms' })
.notNull()
.default(sql`(cast(unixepoch() * 1000 as integer))`),
});
// =============================================================================
// Platform Settings
// =============================================================================
export const platformSettings = sqliteTable('platform_settings', {
key: text('key').primaryKey(),
value: text('value').notNull(),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedBy: text('updated_by').references(() => users.id, { onDelete: 'set null' }),
});
// =============================================================================
// Sessions (BetterAuth)
// =============================================================================
export const sessions = sqliteTable(
'sessions',
{
id: text('id').primaryKey(),
expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
token: text('token').notNull().unique(),
createdAt: integer('created_at', { mode: 'timestamp_ms' })
.notNull()
.default(sql`(cast(unixepoch() * 1000 as integer))`),
updatedAt: integer('updated_at', { mode: 'timestamp_ms' })
.notNull()
.default(sql`(cast(unixepoch() * 1000 as integer))`),
ipAddress: text('ip_address'),
userAgent: text('user_agent'),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
},
(table) => ({
userIdIdx: index('idx_sessions_user_id').on(table.userId),
})
);
// =============================================================================
// Accounts (BetterAuth OAuth providers)
// =============================================================================
export const accounts = sqliteTable(
'accounts',
{
id: text('id').primaryKey(),
accountId: text('account_id').notNull(),
providerId: text('provider_id').notNull(),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
accessToken: text('access_token'),
refreshToken: text('refresh_token'),
idToken: text('id_token'),
accessTokenExpiresAt: integer('access_token_expires_at', { mode: 'timestamp_ms' }),
refreshTokenExpiresAt: integer('refresh_token_expires_at', { mode: 'timestamp_ms' }),
scope: text('scope'),
password: text('password'),
createdAt: integer('created_at', { mode: 'timestamp_ms' })
.notNull()
.default(sql`(cast(unixepoch() * 1000 as integer))`),
updatedAt: integer('updated_at', { mode: 'timestamp_ms' })
.notNull()
.default(sql`(cast(unixepoch() * 1000 as integer))`),
},
(table) => ({
userIdIdx: index('idx_accounts_user_id').on(table.userId),
})
);
// =============================================================================
// Verifications (BetterAuth)
// =============================================================================
export const verifications = sqliteTable(
'verifications',
{
id: text('id').primaryKey(),
identifier: text('identifier').notNull(),
value: text('value').notNull(),
expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
createdAt: integer('created_at', { mode: 'timestamp_ms' })
.notNull()
.default(sql`(cast(unixepoch() * 1000 as integer))`),
updatedAt: integer('updated_at', { mode: 'timestamp_ms' })
.notNull()
.default(sql`(cast(unixepoch() * 1000 as integer))`),
},
(table) => ({
identifierIdx: index('idx_verifications_identifier').on(table.identifier),
})
);
// =============================================================================
// Credentials (per-user encrypted cloud provider tokens and agent API keys)
//
// BYOC (Bring-Your-Own-Cloud) model: users supply their own Hetzner/Scaleway
// tokens and agent API keys. Tokens are NEVER stored as env vars — they are
// encrypted per-user with AES-256-GCM and stored here.
//
// See also: `platformCredentials` table below for admin-managed fallback keys.
// =============================================================================
export const credentials = sqliteTable(
'credentials',
{
id: text('id').primaryKey(),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }), // User deletion removes all their credentials
/**
* Null for user-scoped credentials (legacy, default). Set to project id for project-scoped
* overrides — resolution picks project-scoped first, falls back to user-scoped.
*/
projectId: text('project_id').references(() => projects.id, { onDelete: 'cascade' }),
provider: text('provider').notNull(),
credentialType: text('credential_type').notNull().default('cloud-provider'),
/** Null for cloud-provider credentials; set to 'claude-code' | 'openai-codex' for agent keys. */
agentType: text('agent_type'),
credentialKind: text('credential_kind').notNull().default('api-key'), // 'api-key' | 'oauth-token'
isActive: integer('is_active', { mode: 'boolean' }).notNull().default(true),
/** AES-256-GCM ciphertext (base64). Decrypt via `services/encryption.ts:decrypt()`. */
encryptedToken: text('encrypted_token').notNull(),
/** AES-256-GCM initialization vector (base64, 12 bytes random per encryption). */
iv: text('iv').notNull(),
createdAt: text('created_at') // ISO-8601 text timestamp
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at') // ISO-8601 text timestamp
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
userAgentKindUserScope: uniqueIndex('idx_credentials_user_agent_kind_user_scope')
.on(table.userId, table.agentType, table.credentialKind)
.where(sql`credential_type = 'agent-api-key' AND project_id IS NULL`),
userAgentKindProjectScope: uniqueIndex('idx_credentials_user_agent_kind_project_scope')
.on(table.userId, table.projectId, table.agentType, table.credentialKind)
.where(sql`credential_type = 'agent-api-key' AND project_id IS NOT NULL`),
activeCredential: index('idx_credentials_active')
.on(table.userId, table.projectId, table.agentType, table.isActive)
.where(sql`credential_type = 'agent-api-key' AND is_active = 1`),
})
);
// =============================================================================
// GitHub App Installations
// =============================================================================
export const githubInstallationAccounts = sqliteTable(
'github_installation_accounts',
{
installationId: text('installation_id').primaryKey(),
accountType: text('account_type').notNull(),
accountName: text('account_name').notNull(),
accountNameNormalized: text('normalized_account_name').notNull(),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
uninstalledAt: text('uninstalled_at'),
},
(table) => ({
activeLookupIdx: index('idx_github_installation_accounts_lookup')
.on(table.accountType, table.accountNameNormalized)
.where(sql`uninstalled_at IS NULL`),
})
);
// Per-user SAM links to GitHub App installations. Account deletion/unlink flows
// may remove these rows for the deleting user only; they must not remove
// canonical shared org state in `github_installation_accounts`.
export const githubInstallations = sqliteTable(
'github_installations',
{
id: text('id').primaryKey(),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
installationId: text('installation_id').notNull(),
externalInstallationId: text('external_installation_id'),
accountType: text('account_type').notNull(),
accountName: text('account_name').notNull(),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
userInstallationIdx: uniqueIndex('idx_github_installations_user_external_installation')
.on(table.userId, table.externalInstallationId)
.where(sql`external_installation_id IS NOT NULL`),
})
);
// =============================================================================
// Projects
// =============================================================================
export const projects = sqliteTable(
'projects',
{
id: text('id').primaryKey(),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
name: text('name').notNull(),
normalizedName: text('normalized_name').notNull(),
description: text('description'),
installationId: text('installation_id')
.notNull()
.references(() => githubInstallations.id, { onDelete: 'cascade' }),
repository: text('repository').notNull(),
defaultBranch: text('default_branch').notNull().default('main'),
/** Repo provider: 'github' (default) or 'artifacts' (Cloudflare Artifacts). */
repoProvider: text('repo_provider').notNull().default('github'),
/** Cloudflare Artifacts repo ID. Null for GitHub-backed projects. */
artifactsRepoId: text('artifacts_repo_id'),
githubRepoId: integer('github_repo_id'),
githubRepoNodeId: text('github_repo_node_id'),
// Per-project defaults (null = use platform defaults from env vars).
// Resolved via `resolveProjectScalingConfig()` in task-runner and node services.
defaultVmSize: text('default_vm_size'),
defaultAgentType: text('default_agent_type'),
defaultWorkspaceProfile: text('default_workspace_profile'),
/** Default devcontainer config name for new workspaces. null = auto-discover default. */
defaultDevcontainerConfigName: text('default_devcontainer_config_name'),
defaultProvider: text('default_provider'),
defaultLocation: text('default_location'),
/** Per-agent-type model + permission mode overrides.
* JSON: Record<AgentType, { model?: string | null, permissionMode?: string | null }>
* Null/missing for an agent type = fall through to user-level agent_settings. */
agentDefaults: text('agent_defaults'),
workspaceIdleTimeoutMs: integer('workspace_idle_timeout_ms'),
nodeIdleTimeoutMs: integer('node_idle_timeout_ms'),
// Per-project scaling parameters (null = use platform default from env).
// See SCALING_PARAMS registry in shared constants for metadata.
taskExecutionTimeoutMs: integer('task_execution_timeout_ms'),
maxConcurrentTasks: integer('max_concurrent_tasks'),
maxDispatchDepth: integer('max_dispatch_depth'),
maxSubTasksPerTask: integer('max_sub_tasks_per_task'),
warmNodeTimeoutMs: integer('warm_node_timeout_ms'),
maxWorkspacesPerNode: integer('max_workspaces_per_node'),
nodeCpuThresholdPercent: integer('node_cpu_threshold_percent'),
nodeMemoryThresholdPercent: integer('node_memory_threshold_percent'),
status: text('status').notNull().default('active'),
lastActivityAt: text('last_activity_at'),
activeSessionCount: integer('active_session_count').notNull().default(0),
createdBy: text('created_by')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
userIdIdx: index('idx_projects_user_id').on(table.userId),
installationIdIdx: index('idx_projects_installation_id').on(table.installationId),
userNormalizedNameUnique: uniqueIndex('idx_projects_user_normalized_name').on(
table.userId,
table.normalizedName
),
// Trial-onboarding sentinel owner is excluded from the uniqueness invariant:
// every anonymous trial inserts a row with the same (sentinel user, sentinel
// installation), so "one project per user+installation+repo" cannot hold for
// the sentinel. Isolation for trial rows is enforced by `projectId` scoping
// (see helpers.ts:resolveAnonymousUserId). The index still enforces
// uniqueness for real users. See migration 0046.
userInstallationRepoUnique: uniqueIndex('idx_projects_user_installation_repository')
.on(table.userId, table.installationId, table.repository)
.where(sql`user_id != 'system_anonymous_trials'`),
userGithubRepoIdUnique: uniqueIndex('idx_projects_user_github_repo_id')
.on(table.userId, table.githubRepoId)
.where(sql`github_repo_id IS NOT NULL`),
userArtifactsRepoUnique: uniqueIndex('idx_projects_user_artifacts_repo')
.on(table.userId, table.artifactsRepoId)
.where(sql`artifacts_repo_id IS NOT NULL`),
})
);
export const projectMembers = sqliteTable(
'project_members',
{
projectId: text('project_id')
.notNull()
.references(() => projects.id, { onDelete: 'cascade' }),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
role: text('role').notNull().default('owner'),
status: text('status').notNull().default('active'),
invitedBy: text('invited_by').references(() => users.id, { onDelete: 'set null' }),
removedAt: text('removed_at'),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
pk: primaryKey({ columns: [table.projectId, table.userId] }),
userStatusIdx: index('idx_project_members_user_status').on(table.userId, table.status),
projectStatusIdx: index('idx_project_members_project_status').on(table.projectId, table.status),
})
);
export const projectOwnershipTransfers = sqliteTable(
'project_ownership_transfers',
{
id: text('id').primaryKey(),
projectId: text('project_id').notNull(),
fromUserId: text('from_user_id').notNull(),
toUserId: text('to_user_id').notNull(),
initiatedBy: text('initiated_by').notNull(),
completedAt: text('completed_at'),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
}
);
export const projectMemberOffboardingPlans = sqliteTable(
'project_member_offboarding_plans',
{
id: text('id').primaryKey(),
projectId: text('project_id').notNull(),
memberUserId: text('member_user_id').notNull(),
requestedBy: text('requested_by').notNull(),
status: text('status').notNull().default('preview'),
resourceSummaryJson: text('resource_summary_json').notNull(),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
expiresAt: text('expires_at').notNull(),
appliedAt: text('applied_at'),
},
(table) => ({
projectMemberStatusIdx: index('idx_project_offboarding_plans_project_member_status').on(
table.projectId,
table.memberUserId,
table.status
),
})
);
export const projectMemberOffboardingResourceActions = sqliteTable(
'project_member_offboarding_resource_actions',
{
id: text('id').primaryKey(),
planId: text('plan_id')
.notNull()
.references(() => projectMemberOffboardingPlans.id, { onDelete: 'cascade' }),
resourceKind: text('resource_kind').notNull(),
resourceId: text('resource_id').notNull(),
credentialSourceBefore: text('credential_source_before').notNull(),
attributionUserIdBefore: text('attribution_user_id_before'),
attributionProjectIdBefore: text('attribution_project_id_before'),
recommendedAction: text('recommended_action').notNull(),
selectedAction: text('selected_action'),
status: text('status').notNull().default('pending'),
detailsJson: text('details_json').notNull(),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
planKindIdx: index('idx_project_offboarding_actions_plan_kind').on(
table.planId,
table.resourceKind
),
})
);
export const projectInviteLinks = sqliteTable(
'project_invite_links',
{
id: text('id').primaryKey(),
projectId: text('project_id')
.notNull()
.references(() => projects.id, { onDelete: 'cascade' }),
tokenHash: text('token_hash').notNull().unique(),
createdBy: text('created_by').references(() => users.id, { onDelete: 'set null' }),
expiresAt: text('expires_at').notNull(),
revokedAt: text('revoked_at'),
revokedBy: text('revoked_by').references(() => users.id, { onDelete: 'set null' }),
lastUsedAt: text('last_used_at'),
useCount: integer('use_count').notNull().default(0),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
projectActiveIdx: index('idx_project_invite_links_project').on(
table.projectId,
table.revokedAt,
table.expiresAt
),
})
);
export const projectAccessRequests = sqliteTable(
'project_access_requests',
{
id: text('id').primaryKey(),
projectId: text('project_id')
.notNull()
.references(() => projects.id, { onDelete: 'cascade' }),
inviteLinkId: text('invite_link_id').references(() => projectInviteLinks.id, {
onDelete: 'set null',
}),
requesterUserId: text('requester_user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
status: text('status').notNull().default('pending'),
githubAccessStatus: text('github_access_status').notNull().default('unchecked'),
githubAccessCheckedAt: text('github_access_checked_at'),
githubAccessMessage: text('github_access_message'),
requestedAt: text('requested_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
decidedAt: text('decided_at'),
decidedBy: text('decided_by').references(() => users.id, { onDelete: 'set null' }),
decisionNote: text('decision_note'),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
projectRequesterUnique: uniqueIndex('idx_project_access_requests_project_requester').on(
table.projectId,
table.requesterUserId
),
projectStatusIdx: index('idx_project_access_requests_project_status').on(
table.projectId,
table.status,
table.requestedAt
),
})
);
/** Per-project runtime environment variables injected into workspaces.
* Secret values are AES-256-GCM encrypted; non-secret values are stored in plaintext. */
export const projectRuntimeEnvVars = sqliteTable(
'project_runtime_env_vars',
{
id: text('id').primaryKey(),
projectId: text('project_id')
.notNull()
.references(() => projects.id, { onDelete: 'cascade' }),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
envKey: text('env_key').notNull(),
/** When isSecret=true: AES-256-GCM ciphertext (base64). When isSecret=false: plaintext value. */
storedValue: text('stored_value').notNull(),
/** AES-256-GCM IV (base64). Null when isSecret=false (value stored in plaintext). */
valueIv: text('value_iv'),
isSecret: integer('is_secret', { mode: 'boolean' }).notNull().default(false),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
projectKeyUnique: uniqueIndex('idx_project_runtime_env_project_key').on(
table.projectId,
table.envKey
),
userProjectIdx: index('idx_project_runtime_env_user_project').on(table.userId, table.projectId),
})
);
/** Per-project runtime files injected into workspaces (e.g. .env, config files).
* Secret files are AES-256-GCM encrypted; non-secret files are stored in plaintext. */
export const projectRuntimeFiles = sqliteTable(
'project_runtime_files',
{
id: text('id').primaryKey(),
projectId: text('project_id')
.notNull()
.references(() => projects.id, { onDelete: 'cascade' }),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
filePath: text('file_path').notNull(),
/** When isSecret=true: AES-256-GCM ciphertext (base64). When isSecret=false: plaintext content. */
storedContent: text('stored_content').notNull(),
/** AES-256-GCM IV (base64). Null when isSecret=false (content stored in plaintext). */
contentIv: text('content_iv'),
isSecret: integer('is_secret', { mode: 'boolean' }).notNull().default(false),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
projectPathUnique: uniqueIndex('idx_project_runtime_files_project_path').on(
table.projectId,
table.filePath
),
userProjectIdx: index('idx_project_runtime_files_user_project').on(
table.userId,
table.projectId
),
})
);
/** Additional same-installation GitHub repositories a project's workspace tokens
* may access (Codespaces-style "additional repository access"). The primary
* project repository is always included implicitly and is NOT stored here.
* Each row is verified (user∩app access) at add time and re-verified at every
* token mint. Workspace `/git-token` mints scope `repository_ids` to the primary
* repo plus all active rows here, so same-org submodules can be fetched. */
export const projectGithubRepositories = sqliteTable(
'project_github_repositories',
{
id: text('id').primaryKey(),
projectId: text('project_id')
.notNull()
.references(() => projects.id, { onDelete: 'cascade' }),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
/** Full repository name, e.g. "octocat/hello-world". */
repository: text('repository').notNull(),
/** GitHub numeric repo id captured at verification time (rename-stable). */
githubRepoId: integer('github_repo_id').notNull(),
/** GitHub GraphQL node id (nullable for legacy/edge cases). */
githubRepoNodeId: text('github_repo_node_id'),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
projectRepoUnique: uniqueIndex('idx_project_github_repos_project_repo').on(
table.projectId,
table.repository
),
userProjectIdx: index('idx_project_github_repos_user_project').on(
table.userId,
table.projectId
),
})
);
export const projectGitlabRepositories = sqliteTable(
'project_gitlab_repositories',
{
id: text('id').primaryKey(),
projectId: text('project_id')
.notNull()
.references(() => projects.id, { onDelete: 'cascade' }),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
host: text('host').notNull(),
gitlabProjectId: integer('gitlab_project_id').notNull(),
pathWithNamespace: text('path_with_namespace').notNull(),
webUrl: text('web_url'),
httpUrlToRepo: text('http_url_to_repo').notNull(),
defaultBranch: text('default_branch').notNull(),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
projectUnique: uniqueIndex('idx_project_gitlab_repos_project').on(table.projectId),
userHostProjectUnique: uniqueIndex('idx_project_gitlab_repos_user_host_project').on(
table.userId,
table.host,
table.gitlabProjectId
),
projectUserIdx: index('idx_project_gitlab_repos_project_user').on(
table.projectId,
table.userId
),
})
);
// =============================================================================
// Project Deployment Credentials (GCP OIDC for Defang deployments)
// Note: This table stores GCP WIF configuration (project IDs, service account
// emails, pool IDs) — NOT encrypted tokens. The actual OIDC token exchange
// happens at deployment time using these references.
// =============================================================================
export const projectDeploymentCredentials = sqliteTable(
'project_deployment_credentials',
{
id: text('id').primaryKey(),
projectId: text('project_id')
.notNull()
.references(() => projects.id, { onDelete: 'cascade' }),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
provider: text('provider').notNull().default('gcp'), // Currently only 'gcp'
gcpProjectId: text('gcp_project_id').notNull(),
gcpProjectNumber: text('gcp_project_number').notNull(),
serviceAccountEmail: text('service_account_email').notNull(),
wifPoolId: text('wif_pool_id').notNull(),
wifProviderId: text('wif_provider_id').notNull(),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
projectUnique: uniqueIndex('idx_project_deployment_creds_project').on(
table.projectId,
table.provider
),
userIdx: index('idx_project_deployment_creds_user').on(table.userId),
})
);
// =============================================================================
// Missions (Phase 2: Orchestration Primitives)
// =============================================================================
export const missions = sqliteTable(
'missions',
{
id: text('id').primaryKey(),
projectId: text('project_id')
.notNull()
.references(() => projects.id, { onDelete: 'cascade' }),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
title: text('title').notNull(),
description: text('description'),
status: text('status').notNull().default('planning'),
/** Soft FK to tasks table. The root task that initiated this mission. */
rootTaskId: text('root_task_id'),
/** JSON-serialized MissionBudgetConfig. Enforcement comes in later phases. */
budgetConfig: text('budget_config'),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
projectIdIdx: index('idx_missions_project_id').on(table.projectId),
projectStatusIdx: index('idx_missions_project_status').on(table.projectId, table.status),
userIdIdx: index('idx_missions_user_id').on(table.userId),
})
);
// =============================================================================
// Tasks
// =============================================================================
export const tasks = sqliteTable(
'tasks',
{
id: text('id').primaryKey(),
projectId: text('project_id')
.notNull()
.references(() => projects.id, { onDelete: 'cascade' }),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
/** Null for top-level tasks; set for agent-dispatched sub-tasks (dispatch depth > 0). No FK — parent may be in another project's scope. */
parentTaskId: text('parent_task_id'),
/** Null until a workspace is assigned during task execution. Set by TaskRunner DO. */
workspaceId: text('workspace_id'),
title: text('title').notNull(),
description: text('description'),
status: text('status').notNull().default('draft'),
executionStep: text('execution_step'),
priority: integer('priority').notNull().default(0),
agentProfileHint: text('agent_profile_hint'),
/** Optional skill selected for repeatable-work configuration. */
skillId: text('skill_id'),
/** Original skill hint/id requested by the caller. */
skillHint: text('skill_hint'),
startedAt: text('started_at'),
completedAt: text('completed_at'),
errorMessage: text('error_message'),
outputSummary: text('output_summary'),
outputBranch: text('output_branch'),
outputPrUrl: text('output_pr_url'),
completionEvidence: text('completion_evidence'),
finalizedAt: text('finalized_at'),
/** Task execution mode. 'task' = push/PR/complete lifecycle. 'conversation' = human-controlled lifecycle. */
taskMode: text('task_mode').notNull().default('task'),
/** Dispatch depth for agent-spawned tasks. 0 = user-created, N = Nth generation agent dispatch. */
dispatchDepth: integer('dispatch_depth').notNull().default(0),
/** Node auto-provisioned for this task. set null on node delete so the task record survives cleanup. */
autoProvisionedNodeId: text('auto_provisioned_node_id').references(() => nodes.id, {
onDelete: 'set null',
}),
/** Source that created this task. 'user' = manual, 'cron'/'webhook'/'mcp' = automated. */
triggeredBy: text('triggered_by').notNull().default('user'),
/** Soft FK to triggers table (null for user-created tasks). No DB constraint — trigger may be deleted independently. */
triggerId: text('trigger_id'),
/** Soft FK to trigger_executions table. No DB constraint — execution record may be cleaned up independently. */
triggerExecutionId: text('trigger_execution_id'),
/** Whether the agent credential came from the user or the platform. */
agentCredentialSource: text('agent_credential_source').default('user'), // 'user' | 'project' | 'platform'
/** User whose credential attribution is pinned for this task tree. */
credentialAttributionUserId: text('credential_attribution_user_id').references(() => users.id, { onDelete: 'set null' }),
/** Project scope used when credentialAttributionSource is 'project'. */
credentialAttributionProjectId: text('credential_attribution_project_id').references(() => projects.id, { onDelete: 'set null' }),
/** Root-pinned credential attribution source: 'user' | 'project' | 'platform'. */
credentialAttributionSource: text('credential_attribution_source').default('user'),
credentialBlockedReason: text('credential_blocked_reason'),
credentialBlockedAt: text('credential_blocked_at'),
/** Null for standalone tasks; set when task belongs to a mission. Set null on mission delete. */
missionId: text('mission_id').references(() => missions.id, { onDelete: 'set null' }),
/** Scheduler classification for mission tasks. Null for standalone tasks. */
schedulerState: text('scheduler_state'),
/** Resolved VM size for audit (e.g. 'small', 'medium', 'large'). */
requestedVmSize: text('requested_vm_size'),
/** Where the VM size came from (e.g. 'task', 'agent-profile', 'project', 'platform'). */
requestedVmSizeSource: text('requested_vm_size_source'),
/** VM size actually provisioned. Differs from requestedVmSize only when size-fallback descended on capacity exhaustion. Null until an auto-provisioned node succeeds at a smaller size. */
provisionedVmSize: text('provisioned_vm_size'),
/** JSON snapshot of ResourceRequirements as resolved from the precedence chain. */
resourceRequirementsJson: text('resource_requirements_json'),
/** Which level of the precedence chain provided the resource requirements. */
resourceRequirementsSource: text('resource_requirements_source'),
/** JSON snapshot of ResolvedResourceReservation (scheduler-facing units). */
resolvedReservationJson: text('resolved_reservation_json'),
/** JSON snapshot of PlacementExplanation (audit trail). */
placementExplanationJson: text('placement_explanation_json'),
createdBy: text('created_by')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
autoProvisionedNodeIdx: index('idx_tasks_auto_provisioned_node')
.on(table.autoProvisionedNodeId)
.where(sql`auto_provisioned_node_id is not null`),
projectStatusPriorityUpdatedIdx: index('idx_tasks_project_status_priority_updated').on(
table.projectId,
table.status,
table.priority,
table.updatedAt
),
projectCreatedAtIdx: index('idx_tasks_project_created_at').on(table.projectId, table.createdAt),
projectUserIdx: index('idx_tasks_project_user').on(table.projectId, table.userId),
missionIdIdx: index('idx_tasks_mission_id')
.on(table.missionId)
.where(sql`mission_id IS NOT NULL`),
})
);
export const taskDependencies = sqliteTable(
'task_dependencies',
{
taskId: text('task_id')
.notNull()
.references(() => tasks.id, { onDelete: 'cascade' }),
dependsOnTaskId: text('depends_on_task_id')
.notNull()
.references(() => tasks.id, { onDelete: 'cascade' }),
createdBy: text('created_by')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
pk: primaryKey({ columns: [table.taskId, table.dependsOnTaskId] }),
dependsOnIdx: index('idx_task_dependencies_depends_on').on(table.dependsOnTaskId),
})
);
export const taskStatusEvents = sqliteTable(
'task_status_events',
{
id: text('id').primaryKey(),
taskId: text('task_id')
.notNull()
.references(() => tasks.id, { onDelete: 'cascade' }),
fromStatus: text('from_status'),
toStatus: text('to_status').notNull(),
actorType: text('actor_type').notNull(),
actorId: text('actor_id'),
reason: text('reason'),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
taskCreatedAtIdx: index('idx_task_status_events_task_created_at').on(
table.taskId,
table.createdAt
),
})
);
// =============================================================================
// Nodes
// =============================================================================
export const nodes = sqliteTable(
'nodes',
{
id: text('id').primaryKey(),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
name: text('name').notNull(),
status: text('status').notNull().default('pending'),
vmSize: text('vm_size').notNull().default('medium'),
vmLocation: text('vm_location').notNull().default('nbg1'),
cloudProvider: text('cloud_provider'),
providerInstanceId: text('provider_instance_id'),
ipAddress: text('ip_address'),
backendDnsRecordId: text('backend_dns_record_id'),
lastHeartbeatAt: text('last_heartbeat_at'),
/** ISO-8601 timestamp from VM agent /ready after system provisioning completes. */
agentReadyAt: text('agent_ready_at'),
healthStatus: text('health_status').notNull().default('unhealthy'),
heartbeatStaleAfterSeconds: integer('heartbeat_stale_after_seconds').notNull().default(180),
lastMetrics: text('last_metrics'),
/** ISO-8601 timestamp when node entered warm pool. Null if node is not warm. Used by NodeLifecycle DO for timeout. */
warmSince: text('warm_since'),
/** 'user' = provisioned with user's own credential; 'platform' = provisioned with platform credential. */
credentialSource: text('credential_source').default('user'),
/** User whose credential attribution was used to provision this node. */
credentialAttributionUserId: text('credential_attribution_user_id').references(() => users.id, { onDelete: 'set null' }),
/** Project scope used when credentialAttributionSource is 'project'. */
credentialAttributionProjectId: text('credential_attribution_project_id').references(() => projects.id, { onDelete: 'set null' }),
/** Credential attribution source used at node creation: 'user' | 'project' | 'platform'. */
credentialAttributionSource: text('credential_attribution_source').default('user'),
offboardingStatus: text('offboarding_status'),
offboardingBlockedReason: text('offboarding_blocked_reason'),
offboardingBlockedAt: text('offboarding_blocked_at'),
/** 'workspace' = ephemeral task/dev node (default); 'deployment' = long-lived app-hosting node. */
nodeRole: text('node_role').notNull().default('workspace'),
/** 'shared' = eligible for multi-tenant placement; 'exclusive' = one deployment environment only. */
nodeMode: text('node_mode').notNull().default('shared'),
/** Runtime substrate: 'vm' (default) or 'cf-container' for the Sandbox spike. */
runtime: text('runtime').notNull().default('vm'),
errorMessage: text('error_message'),
createdAt: text('created_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
updatedAt: text('updated_at')
.notNull()
.default(sql`CURRENT_TIMESTAMP`),
},
(table) => ({
userIdIdx: index('idx_nodes_user_id').on(table.userId),
runtimeIdx: index('idx_nodes_runtime').on(table.runtime),
})
);
// =============================================================================
// Workspaces
// =============================================================================
export const workspaces = sqliteTable(
'workspaces',
{
id: text('id').primaryKey(),
/** Null when node is destroyed; workspace record preserved for history. set null on node delete. */
nodeId: text('node_id').references(() => nodes.id, { onDelete: 'set null' }),
/** Null for legacy workspaces created before project-first architecture. set null on project delete. */
projectId: text('project_id').references(() => projects.id, { onDelete: 'set null' }),
userId: text('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
/** Null for workspaces not linked to a GitHub installation. No onDelete — installation removal doesn't affect workspaces. */
installationId: text('installation_id').references(() => githubInstallations.id),
displayName: text('display_name'),
normalizedDisplayName: text('normalized_display_name'),
name: text('name').notNull(),
repository: text('repository').notNull(),
branch: text('branch').notNull().default('main'),
status: text('status').notNull().default('pending'),
vmSize: text('vm_size').notNull(),
vmLocation: text('vm_location').notNull(),
workspaceProfile: text('workspace_profile').default(DEFAULT_WORKSPACE_PROFILE),
/** Selected devcontainer config name. null = auto-discover default. */
devcontainerConfigName: text('devcontainer_config_name'),
hetznerServerId: text('hetzner_server_id'),
vmIp: text('vm_ip'),
dnsRecordId: text('dns_record_id'),
lastActivityAt: text('last_activity_at'),
/** Soft FK to ProjectData DO session (not a D1 table). Null until a chat session binds to this workspace. */
chatSessionId: text('chat_session_id'),
portsPublicEnabled: integer('ports_public_enabled', { mode: 'boolean' })
.notNull()
.default(false),
errorMessage: text('error_message'),