File size: 16,534 Bytes
a8f4b72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { sql } from 'drizzle-orm';
import {
  check,
  customType,
  doublePrecision,
  index,
  integer,
  jsonb,
  pgTable,
  text,
  timestamp,
  uniqueIndex,
  type AnyPgColumn
} from 'drizzle-orm/pg-core';

type JsonObject = Record<string, unknown>;
const vector1536 = customType<{ data: number[]; driverData: string }>({
  dataType: () => 'vector(1536)',
  toDriver: (value) => `[${value.join(',')}]`,
  fromDriver: (value) => {
    const inner = value.slice(1, -1).trim();
    return inner ? inner.split(',').map(Number) : [];
  }
});

export const storageSchemaMigrations = pgTable('storage_schema_migrations', {
  version: integer('version').primaryKey(),
  name: text('name').notNull(),
  appliedAt: timestamp('applied_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow()
});

export const projects = pgTable('projects', {
  projectId: text('project_id').primaryKey(),
  name: text('name').notNull(),
  description: text('description').notNull().default(''),
  stage: text('stage').notNull().default('Research'),
  stateJson: jsonb('state_json').$type<JsonObject>().notNull().default({}),
  createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  archivedAt: timestamp('archived_at', { withTimezone: true, mode: 'string' })
}, (table) => [
  index('projects_stage_updated_idx').on(table.stage, table.updatedAt),
  index('projects_state_gin_idx').using('gin', table.stateJson)
]);

export const projectEvents = pgTable('project_events', {
  eventId: text('event_id').primaryKey(),
  projectId: text('project_id').notNull().references(() => projects.projectId, { onDelete: 'cascade' }),
  eventType: text('event_type').notNull(),
  payloadJson: jsonb('payload_json').$type<JsonObject>().notNull().default({}),
  createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  createdBy: text('created_by')
}, (table) => [
  index('project_events_project_created_idx').on(table.projectId, table.createdAt)
]);

export const snapshots = pgTable('snapshots', {
  snapshotId: text('snapshot_id').primaryKey(),
  projectId: text('project_id').notNull().references(() => projects.projectId, { onDelete: 'cascade' }),
  snapshotType: text('snapshot_type').notNull(),
  label: text('label').notNull(),
  source: text('source').notNull().default('local'),
  schemaVersion: text('schema_version').notNull().default('1'),
  stateJson: jsonb('state_json').$type<JsonObject>().notNull(),
  checksum: text('checksum').notNull(),
  createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  createdBy: text('created_by'),
  metadataJson: jsonb('metadata_json').$type<JsonObject>().notNull().default({})
}, (table) => [
  check('snapshots_type_check', sql`${table.snapshotType} IN ('manual', 'scheduled', 'pre_change', 'canon', 'frontier', 'archive')`),
  index('snapshots_project_created_idx').on(table.projectId, table.createdAt),
  index('snapshots_type_created_idx').on(table.snapshotType, table.createdAt),
  index('snapshots_metadata_gin_idx').using('gin', table.metadataJson)
]);

export const snapshotItems = pgTable('snapshot_items', {
  snapshotItemId: text('snapshot_item_id').primaryKey(),
  snapshotId: text('snapshot_id').notNull().references(() => snapshots.snapshotId, { onDelete: 'cascade' }),
  entityType: text('entity_type').notNull(),
  entityId: text('entity_id').notNull(),
  ordinal: integer('ordinal').notNull().default(0),
  payloadJson: jsonb('payload_json').$type<JsonObject>().notNull(),
  contentHash: text('content_hash').notNull()
}, (table) => [
  check('snapshot_items_ordinal_check', sql`${table.ordinal} >= 0`),
  uniqueIndex('snapshot_items_snapshot_entity_uq').on(table.snapshotId, table.entityType, table.entityId),
  index('snapshot_items_entity_idx').on(table.entityType, table.entityId)
]);

export const canonEntries = pgTable('canon_entries', {
  entryId: text('entry_id').primaryKey(),
  projectId: text('project_id').references(() => projects.projectId, { onDelete: 'set null' }),
  slug: text('slug').notNull(),
  title: text('title').notNull(),
  body: text('body').notNull(),
  entryType: text('entry_type').notNull(),
  status: text('status').notNull().default('draft'),
  version: integer('version').notNull().default(1),
  sourceSnapshotId: text('source_snapshot_id').references(() => snapshots.snapshotId, { onDelete: 'set null' }),
  supersedesEntryId: text('supersedes_entry_id').references((): AnyPgColumn => canonEntries.entryId, { onDelete: 'set null' }),
  metadataJson: jsonb('metadata_json').$type<JsonObject>().notNull().default({}),
  validFrom: timestamp('valid_from', { withTimezone: true, mode: 'string' }),
  validUntil: timestamp('valid_until', { withTimezone: true, mode: 'string' }),
  createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow()
}, (table) => [
  check('canon_entries_type_check', sql`${table.entryType} IN ('principle', 'decision', 'pattern', 'policy', 'knowledge', 'procedure')`),
  check('canon_entries_status_check', sql`${table.status} IN ('draft', 'active', 'superseded', 'archived')`),
  check('canon_entries_version_check', sql`${table.version} > 0`),
  uniqueIndex('canon_entries_project_slug_version_uq').on(table.projectId, table.slug, table.version),
  index('canon_entries_project_status_idx').on(table.projectId, table.status, table.updatedAt),
  index('canon_entries_type_status_idx').on(table.entryType, table.status),
  index('canon_entries_metadata_gin_idx').using('gin', table.metadataJson)
]);

export const canonRevisions = pgTable('canon_revisions', {
  revisionId: text('revision_id').primaryKey(),
  entryId: text('entry_id').notNull().references(() => canonEntries.entryId, { onDelete: 'cascade' }),
  version: integer('version').notNull(),
  title: text('title').notNull(),
  body: text('body').notNull(),
  sourceSnapshotId: text('source_snapshot_id').references(() => snapshots.snapshotId, { onDelete: 'set null' }),
  changeSummary: text('change_summary').notNull().default(''),
  metadataJson: jsonb('metadata_json').$type<JsonObject>().notNull().default({}),
  createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  createdBy: text('created_by')
}, (table) => [
  check('canon_revisions_version_check', sql`${table.version} > 0`),
  uniqueIndex('canon_revisions_entry_version_uq').on(table.entryId, table.version),
  index('canon_revisions_entry_created_idx').on(table.entryId, table.createdAt)
]);

export const frontierItems = pgTable('frontier_items', {
  frontierId: text('frontier_id').primaryKey(),
  projectId: text('project_id').references(() => projects.projectId, { onDelete: 'cascade' }),
  domain: text('domain').notNull(),
  itemType: text('item_type').notNull(),
  title: text('title').notNull(),
  description: text('description').notNull().default(''),
  rationale: text('rationale').notNull().default(''),
  status: text('status').notNull().default('candidate'),
  confidence: doublePrecision('confidence'),
  impact: text('impact').notNull().default('medium'),
  firstSeenAt: timestamp('first_seen_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  lastReviewedAt: timestamp('last_reviewed_at', { withTimezone: true, mode: 'string' }),
  reviewAfter: timestamp('review_after', { withTimezone: true, mode: 'string' }),
  metadataJson: jsonb('metadata_json').$type<JsonObject>().notNull().default({}),
  createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  updatedAt: timestamp('updated_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow()
}, (table) => [
  check('frontier_items_type_check', sql`${table.itemType} IN ('technology', 'capability', 'practice', 'dependency', 'research', 'risk')`),
  check('frontier_items_status_check', sql`${table.status} IN ('candidate', 'tracking', 'adopted', 'rejected', 'obsolete')`),
  check('frontier_items_confidence_check', sql`${table.confidence} IS NULL OR (${table.confidence} >= 0 AND ${table.confidence} <= 1)`),
  check('frontier_items_impact_check', sql`${table.impact} IN ('low', 'medium', 'high', 'critical')`),
  index('frontier_items_project_status_idx').on(table.projectId, table.status, table.updatedAt),
  index('frontier_items_domain_review_idx').on(table.domain, table.reviewAfter),
  index('frontier_items_metadata_gin_idx').using('gin', table.metadataJson)
]);

export const frontierObservations = pgTable('frontier_observations', {
  observationId: text('observation_id').primaryKey(),
  frontierId: text('frontier_id').notNull().references(() => frontierItems.frontierId, { onDelete: 'cascade' }),
  sourceName: text('source_name').notNull(),
  sourceUri: text('source_uri'),
  observedAt: timestamp('observed_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  summary: text('summary').notNull(),
  evidenceJson: jsonb('evidence_json').$type<JsonObject>().notNull().default({}),
  confidence: doublePrecision('confidence'),
  createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow()
}, (table) => [
  check('frontier_observations_confidence_check', sql`${table.confidence} IS NULL OR (${table.confidence} >= 0 AND ${table.confidence} <= 1)`),
  index('frontier_observations_frontier_idx').on(table.frontierId, table.observedAt)
]);

export const archiveRecords = pgTable('archive_records', {
  archiveId: text('archive_id').primaryKey(),
  projectId: text('project_id').references(() => projects.projectId, { onDelete: 'set null' }),
  resourceType: text('resource_type').notNull(),
  resourceId: text('resource_id').notNull(),
  snapshotId: text('snapshot_id').references(() => snapshots.snapshotId, { onDelete: 'set null' }),
  payloadJson: jsonb('payload_json').$type<JsonObject>().notNull(),
  checksum: text('checksum').notNull(),
  archiveReason: text('archive_reason').notNull().default(''),
  archivedAt: timestamp('archived_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  archivedBy: text('archived_by'),
  retentionUntil: timestamp('retention_until', { withTimezone: true, mode: 'string' }),
  restoredAt: timestamp('restored_at', { withTimezone: true, mode: 'string' }),
  metadataJson: jsonb('metadata_json').$type<JsonObject>().notNull().default({})
}, (table) => [
  index('archive_records_project_archived_idx').on(table.projectId, table.archivedAt),
  index('archive_records_resource_idx').on(table.resourceType, table.resourceId, table.archivedAt),
  index('archive_records_retention_idx').on(table.retentionUntil)
]);

export const knowledgeEmbeddings = pgTable('knowledge_embeddings', {
  embeddingId: text('embedding_id').primaryKey(),
  entityType: text('entity_type').notNull(),
  entityId: text('entity_id').notNull(),
  modelKey: text('model_key').notNull(),
  dimensions: integer('dimensions').notNull().default(1536),
  embedding: vector1536('embedding').notNull(),
  contentHash: text('content_hash').notNull(),
  createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow()
}, (table) => [
  check('knowledge_embeddings_dimensions_check', sql`${table.dimensions} = 1536`),
  uniqueIndex('knowledge_embeddings_entity_model_uq').on(table.entityType, table.entityId, table.modelKey),
  index('knowledge_embeddings_entity_idx').on(table.entityType, table.entityId),
  index('knowledge_embeddings_cosine_hnsw_idx').using('hnsw', table.embedding.op('vector_cosine_ops'))
]);

export const dependencyFindings = pgTable('dependency_findings', {
  findingId: text('finding_id').primaryKey(),
  projectId: text('project_id').notNull().references(() => projects.projectId, { onDelete: 'cascade' }),
  kind: text('kind').notNull(),
  name: text('name').notNull(),
  description: text('description').notNull().default(''),
  status: text('status').notNull().default('open'),
  source: text('source').notNull().default('manual'),
  metadataJson: jsonb('metadata_json').$type<JsonObject>().notNull().default({}),
  detectedAt: timestamp('detected_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  resolvedAt: timestamp('resolved_at', { withTimezone: true, mode: 'string' })
}, (table) => [
  check('dependency_findings_kind_check', sql`${table.kind} IN ('model', 'dataset', 'permission', 'tool', 'infrastructure')`),
  check('dependency_findings_status_check', sql`${table.status} IN ('open', 'resolved', 'waived')`),
  index('dependency_findings_project_status_idx').on(table.projectId, table.status, table.detectedAt),
  index('dependency_findings_kind_name_idx').on(table.kind, table.name, table.status),
  index('dependency_findings_metadata_gin_idx').using('gin', table.metadataJson)
]);

export const deltaRuns = pgTable('delta_runs', {
  deltaRunId: text('delta_run_id').primaryKey(),
  projectId: text('project_id').notNull().references(() => projects.projectId, { onDelete: 'cascade' }),
  currentLabel: text('current_label').notNull(),
  targetLabel: text('target_label').notNull(),
  currentStateJson: jsonb('current_state_json').$type<JsonObject>().notNull(),
  targetStateJson: jsonb('target_state_json').$type<JsonObject>().notNull(),
  status: text('status').notNull(),
  createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  createdBy: text('created_by')
}, (table) => [
  check('delta_runs_status_check', sql`${table.status} IN ('complete', 'blocked')`),
  index('delta_runs_project_created_idx').on(table.projectId, table.createdAt)
]);

export const deltaGaps = pgTable('delta_gaps', {
  gapId: text('gap_id').primaryKey(),
  deltaRunId: text('delta_run_id').notNull().references(() => deltaRuns.deltaRunId, { onDelete: 'cascade' }),
  dimension: text('dimension').notNull(),
  currentValuesJson: jsonb('current_values_json').$type<string[]>().notNull(),
  targetValuesJson: jsonb('target_values_json').$type<string[]>().notNull(),
  missingValuesJson: jsonb('missing_values_json').$type<string[]>().notNull(),
  severity: text('severity').notNull(),
  status: text('status').notNull().default('open'),
  createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow()
}, (table) => [
  check('delta_gaps_severity_check', sql`${table.severity} IN ('gap', 'blocker')`),
  check('delta_gaps_status_check', sql`${table.status} IN ('open', 'resolved', 'accepted')`),
  index('delta_gaps_run_status_idx').on(table.deltaRunId, table.status)
]);

export const deltaDependencies = pgTable('delta_dependencies', {
  deltaDependencyId: text('delta_dependency_id').primaryKey(),
  deltaRunId: text('delta_run_id').notNull().references(() => deltaRuns.deltaRunId, { onDelete: 'cascade' }),
  findingId: text('finding_id').notNull().references(() => dependencyFindings.findingId, { onDelete: 'restrict' }),
  createdAt: timestamp('created_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow()
}, (table) => [
  uniqueIndex('delta_dependencies_run_finding_uq').on(table.deltaRunId, table.findingId),
  index('delta_dependencies_run_idx').on(table.deltaRunId)
]);

export const governanceReviews = pgTable('governance_reviews', {
  reviewId: text('review_id').primaryKey(),
  projectId: text('project_id').notNull().references(() => projects.projectId, { onDelete: 'cascade' }),
  action: text('action').notNull(),
  resourceType: text('resource_type').notNull(),
  resourceId: text('resource_id').notNull(),
  decision: text('decision').notNull().default('pending'),
  requestedBy: text('requested_by'),
  requestedAt: timestamp('requested_at', { withTimezone: true, mode: 'string' }).notNull().defaultNow(),
  reviewedBy: text('reviewed_by'),
  reviewedAt: timestamp('reviewed_at', { withTimezone: true, mode: 'string' }),
  reason: text('reason').notNull().default(''),
  metadataJson: jsonb('metadata_json').$type<JsonObject>().notNull().default({})
}, (table) => [
  check('governance_reviews_decision_check', sql`${table.decision} IN ('pending', 'approved', 'rejected')`),
  index('governance_reviews_project_decision_idx').on(table.projectId, table.decision, table.requestedAt),
  index('governance_reviews_resource_idx').on(table.action, table.resourceType, table.resourceId, table.decision),
  index('governance_reviews_metadata_gin_idx').using('gin', table.metadataJson)
]);