@workbasehq/core 0.2.14 → 0.3.0

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 (99) hide show
  1. package/package.json +18 -3
  2. package/src/access-evaluator.ts +72 -0
  3. package/src/access-guards.ts +35 -0
  4. package/src/access-inputs.ts +62 -0
  5. package/src/access-lock/cli.ts +34 -0
  6. package/src/access-lock.ts +183 -0
  7. package/src/access.ts +209 -0
  8. package/src/account-action-conditions.ts +27 -0
  9. package/src/account-command.ts +8 -0
  10. package/src/admin-ui.tsx +3 -2
  11. package/src/app.ts +3 -3
  12. package/src/canonical.ts +6 -0
  13. package/src/capabilities.ts +5 -3
  14. package/src/commands.ts +14 -8
  15. package/src/config.ts +105 -69
  16. package/src/console-build.ts +37 -0
  17. package/src/console-contract.ts +4 -0
  18. package/src/console-model.ts +2 -0
  19. package/src/console-presentation.ts +1 -1
  20. package/src/console.ts +3 -3
  21. package/src/crud.ts +13 -7
  22. package/src/dev-mailbox.ts +35 -0
  23. package/src/display-identity.ts +12 -0
  24. package/src/execution/atomic.ts +17 -3
  25. package/src/execution/policies.ts +14 -6
  26. package/src/execution/policy-receipts.ts +6 -5
  27. package/src/execution/post-commit.ts +11 -0
  28. package/src/execution/types.ts +1 -1
  29. package/src/index.ts +2 -0
  30. package/src/infra/README.md +39 -3
  31. package/src/infra/d1-migrations.ts +4 -3
  32. package/src/infra/instance-migrations.ts +26 -5
  33. package/src/infra/provision-config-main.mjs +3 -3
  34. package/src/infra/provision-diagnostics.ts +4 -0
  35. package/src/infra/provision-plan.ts +34 -5
  36. package/src/infra/provision.ts +26 -4
  37. package/src/infra/schema.ts +1 -1
  38. package/src/kernel/invitation-mail-port.ts +26 -0
  39. package/src/kernel/mail-outbox-port.ts +4 -2
  40. package/src/kernel/migrations.ts +38 -15
  41. package/src/kernel/plugin.ts +2 -0
  42. package/src/kernel/predicate.ts +15 -3
  43. package/src/kernel/registry.ts +69 -12
  44. package/src/member-bootstrap.ts +65 -0
  45. package/src/member-identities.ts +42 -0
  46. package/src/migrations/diagnostics.ts +6 -1
  47. package/src/migrations/model-b.ts +2 -1
  48. package/src/migrations/operational-evidence.ts +51 -0
  49. package/src/migrations/planner.ts +12 -1
  50. package/src/migrations/rebuild.ts +17 -12
  51. package/src/migrations/reset-era.ts +29 -0
  52. package/src/migrations/schema-bundle.ts +43 -0
  53. package/src/migrations/schema-cli.ts +74 -0
  54. package/src/migrations/schema-git.ts +36 -0
  55. package/src/migrations/schema-lock.ts +159 -0
  56. package/src/migrations/schema-plan.ts +94 -0
  57. package/src/migrations/schema.ts +73 -48
  58. package/src/migrations/sdk-baseline.ts +35 -0
  59. package/src/migrations/system-schema.ts +39 -0
  60. package/src/model-inputs.ts +25 -0
  61. package/src/openapi/cli.ts +72 -0
  62. package/src/openapi/generate.ts +166 -0
  63. package/src/openapi/input-projection.ts +131 -0
  64. package/src/openapi/public-paths.ts +80 -0
  65. package/src/openapi/routes.ts +29 -0
  66. package/src/ops.ts +4 -2
  67. package/src/organization-name.ts +35 -0
  68. package/src/organization-permissions.ts +10 -0
  69. package/src/organizations.ts +72 -3
  70. package/src/policies.ts +22 -6
  71. package/src/public-projection.ts +108 -0
  72. package/src/public-schema.ts +5 -43
  73. package/src/query/compiler.ts +13 -0
  74. package/src/query/input-schema.ts +89 -0
  75. package/src/query/limits.ts +1 -1
  76. package/src/query/schema.ts +20 -88
  77. package/src/record-action-routes.ts +87 -0
  78. package/src/record-actions-data.ts +17 -0
  79. package/src/record-actions.ts +61 -0
  80. package/src/record-read.ts +20 -0
  81. package/src/row-access.ts +11 -0
  82. package/src/row-invitations.ts +29 -0
  83. package/src/schema/README.md +323 -0
  84. package/src/schema/declaration.ts +5 -0
  85. package/src/schema/load.ts +423 -0
  86. package/src/schema/lock-format.ts +117 -0
  87. package/src/schema/physical-names.ts +30 -0
  88. package/src/schema/revision.ts +16 -0
  89. package/src/schema/source-location.ts +3 -0
  90. package/src/schema-compatibility.ts +2 -2
  91. package/src/schema.ts +171 -0
  92. package/src/types.ts +1 -1
  93. package/src/user-link-eligibility.ts +36 -0
  94. package/src/user-link-fields.ts +7 -0
  95. package/src/user-links.ts +30 -20
  96. package/src/worker-access-actions.ts +89 -0
  97. package/src/worker-access.ts +61 -0
  98. package/src/workflow-runtime.ts +109 -22
  99. package/src/bootstrap.ts +0 -23
@@ -0,0 +1,74 @@
1
+ import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'
2
+ import { dirname, resolve } from 'node:path'
3
+ import { pathToFileURL } from 'node:url'
4
+ import { loadConfig } from '../schema/load'
5
+ import { checkSchema, parseLock } from './schema-lock'
6
+ import { checkBundle, parseBundle } from './schema-bundle'
7
+ import { assertBaseFiles, bundleFilename, checkLinkage, plan, type ExistingBundle } from './schema-plan'
8
+ import { readSchemaBase } from './schema-git'
9
+
10
+ export async function runSchemaCli(command: 'plan' | 'check', args: readonly string[]): Promise<number> {
11
+ const options = { root: '.', config: 'config.ts', directory: '', migrations: 'migrations', init: false, base: '', confirmManual: false }
12
+ for (let i = 0; i < args.length; i++) {
13
+ const arg = args[i]
14
+ if (arg === '--init' && command === 'plan') options.init = true
15
+ else if (arg === '--confirm-manual' && command === 'plan') options.confirmManual = true
16
+ else if (['--root', '--config', '--directory', '--migrations', '--base'].includes(arg) && args[i + 1] && !args[i + 1].startsWith('--')) {
17
+ options[arg.slice(2) as 'root' | 'config' | 'directory' | 'migrations' | 'base'] = args[++i]
18
+ } else throw new Error('Usage: migrate:plan --base <ref> [--init] [--confirm-manual] | check:schema [--base <ref>]; paths: --root --config --directory --migrations')
19
+ }
20
+ const file = resolve(options.root, options.config)
21
+ const directory = options.directory ? resolve(options.root, options.directory) : dirname(file)
22
+ const lockPath = resolve(directory, 'schema.lock.json'), migrationsPath = resolve(directory, options.migrations)
23
+ const currentLock = existsSync(lockPath) ? readFileSync(lockPath, 'utf8') : undefined
24
+ if (options.init && currentLock) throw new Error('schema.lock.json already exists; --init requires no lock and no domain migrations')
25
+ if (command === 'plan' && !options.init && !options.base) throw new Error('migrate:plan requires --base <ref>; use --init only for a fresh domain')
26
+ const base = options.base ? readSchemaBase(resolve(options.root), options.base, lockPath, migrationsPath) : { lock: undefined, migrations: {} }
27
+ const migrations: Record<string, string> = {}
28
+ if (existsSync(migrationsPath)) for (const name of readdirSync(migrationsPath).filter(name => name.endsWith('.sql'))) migrations[name] = readFileSync(resolve(migrationsPath, name), 'utf8')
29
+ if (options.init && base.lock) throw new Error('--init requires no lock in base; base already has schema.lock.json')
30
+ if (options.init && (Object.keys(migrations).length || Object.keys(base.migrations).length)) throw new Error('--init requires no domain migrations locally or in base')
31
+ if (command === 'plan' && options.base && !base.lock && !options.init) throw new Error('Missing schema.lock.json in base; use migrate:plan --base <ref> --init for a fresh domain')
32
+ const { config, sources } = await loadConfig(file)
33
+ if (command === 'check') {
34
+ try {
35
+ if (!currentLock) throw new Error('Missing schema.lock.json; use migrate:plan --init')
36
+ checkSchema(config, parseLock(currentLock), sources)
37
+ for (const [name, sql] of Object.entries(migrations)) await checkBundle(name, sql)
38
+ if (options.base) await checkLinkage(base.lock, base.migrations, currentLock, migrations)
39
+ } catch (error) { console.error(`check:schema: ${error instanceof Error ? error.message : error}`); return 1 }
40
+ console.log('check:schema: schema, bundles and supplied base linkage match')
41
+ return 0
42
+ }
43
+ let existingBundle: ExistingBundle | undefined
44
+ const added = Object.keys(migrations).filter(name => !(name in base.migrations))
45
+ // A newly merged revision may occupy our pending bundle's filename. Only that
46
+ // pending bundle may be replaced with the new base bytes during renumbering.
47
+ if (currentLock && currentLock !== base.lock) {
48
+ const lock = parseLock(currentLock), filename = bundleFilename(lock.revision)
49
+ if (migrations[filename]) {
50
+ const bundle = parseBundle(filename, migrations[filename])
51
+ if (bundle.revision === lock.revision && bundle.parent === lock.parent && migrations[filename] !== base.migrations[filename]) existingBundle = { filename, sql: migrations[filename] }
52
+ }
53
+ }
54
+ if (added.length > 1 || added.some(name => name !== existingBundle?.filename)) throw new Error(`Expected exactly one pending migration matching the lock; found ${added.length} new files`)
55
+ assertBaseFiles(base.migrations, migrations, existingBundle?.filename)
56
+ const result = await plan({ baseLock: base.lock, baseMigrations: base.migrations, config, existingBundle, confirmManual: options.confirmManual, sources })
57
+ mkdirSync(migrationsPath, { recursive: true })
58
+ if (existingBundle && existingBundle.filename !== result.bundle?.filename) {
59
+ const restored = base.migrations[existingBundle.filename]
60
+ if (restored !== undefined) writeFileSync(resolve(migrationsPath, existingBundle.filename), restored)
61
+ else unlinkSync(resolve(migrationsPath, existingBundle.filename))
62
+ }
63
+ if (result.bundle) writeFileSync(resolve(migrationsPath, result.bundle.filename), result.bundle.sql)
64
+ writeFileSync(lockPath, result.lock)
65
+ console.log(`migrate:plan: r${parseLock(result.lock).revision}; ${result.bundle?.filename ?? 'no pending schema diff'}`)
66
+ return 0
67
+ }
68
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
69
+ try {
70
+ const [command, ...args] = process.argv.slice(2)
71
+ if (command !== 'plan' && command !== 'check') throw new Error('Expected plan or check')
72
+ process.exitCode = await runSchemaCli(command, args)
73
+ } catch (error) { console.error(error instanceof Error ? error.message : error); process.exitCode = 1 }
74
+ }
@@ -0,0 +1,36 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { existsSync } from 'node:fs'
3
+ import { dirname, relative, resolve, sep } from 'node:path'
4
+ import type { MigrationFiles } from './schema-plan'
5
+
6
+ /** Read-only adapter. Resolve the ref once so all reads use the same tip. */
7
+ export function readSchemaBase(root: string, ref: string, lockPath: string, migrationsPath: string): { lock?: string; migrations: MigrationFiles } {
8
+ const git = (...args: string[]) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
9
+ let tip: string
10
+ try { tip = git('show', '--no-patch', '--format=%H', '--end-of-options', `${ref}^{commit}`).trim() }
11
+ catch { throw new Error(`Unresolvable base ref ${ref}; supply an existing local commit ref (fetch it before planning)`) }
12
+ let top = resolve(root)
13
+ while (!existsSync(resolve(top, '.git'))) {
14
+ if (dirname(top) === top) throw new Error('Schema base requires a Git repository')
15
+ top = dirname(top)
16
+ }
17
+ const path = (file: string) => {
18
+ const name = relative(top, resolve(file)).split(sep).join('/')
19
+ if (name.startsWith('../')) throw new Error(`Schema path outside Git repository: ${file}`)
20
+ return name
21
+ }
22
+ const lockName = path(lockPath), directory = path(migrationsPath)
23
+ const names = execFileSync('git', ['--literal-pathspecs', 'ls-tree', '-r', '-z', '--name-only', tip, '--', lockName, directory], { cwd: top, encoding: 'utf8' }).split('\0').filter(Boolean)
24
+ if (!names.includes(lockName)) {
25
+ let present = false
26
+ try { git('cat-file', '-e', `${tip}:${lockName}`); present = true } catch { /* A lockless base is permitted for --init. */ }
27
+ if (present) throw new Error(`Git listing missed existing lock ${lockName}; refusing incomplete base state`)
28
+ }
29
+ const migrations: Record<string, string> = {}
30
+ for (const name of names) if (name.startsWith(directory + '/') && name.endsWith('.sql')) {
31
+ const file = name.slice(directory.length + 1)
32
+ if (file.includes('/')) throw new Error(`Nested domain migration is unsupported: ${name}`)
33
+ migrations[file] = git('show', `${tip}:${name}`)
34
+ }
35
+ return { lock: names.includes(lockName) ? git('show', `${tip}:${lockName}`) : undefined, migrations }
36
+ }
@@ -0,0 +1,159 @@
1
+ import type { InstanceConfig } from '../config'
2
+ import { physicalTables, renderTable, renderColumn, quote, type TableSpec } from './schema'
3
+ import type { SourceMap } from '../schema/source-location'
4
+ import { initialEntityId, initialFieldId, transitionId, validateLock, type EntityLineage, type RenameTransition, type SchemaLock } from '../schema/lock-format'
5
+ export type { SchemaLock, EntityLineage, FieldLineage, RenameTransition } from '../schema/lock-format'
6
+
7
+ export const lockBytes = (lock: SchemaLock) => JSON.stringify(lock, null, 2) + '\n'
8
+ const equal = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
9
+ export class SpecError extends Error {
10
+ constructor(readonly table: string, readonly column: string | undefined, message: string) {
11
+ super(`${table}${column ? `.${column}` : ''}: ${message}`)
12
+ }
13
+ }
14
+ /** Pure SQL-level diff: never reads config, files, source locations or SDK versions. */
15
+ export function diffSpecs(baseTables: readonly TableSpec[], tables: readonly TableSpec[]): string {
16
+ const sql: string[] = []
17
+ const reject = (table: string, column: string | undefined, reason: string): never => { throw new SpecError(table, column, reason) }
18
+ for (const base of baseTables) {
19
+ const table = tables.find(t => t.name === base.name)
20
+ if (!table) reject(base.name, undefined, 'dropping or renaming a table is unsupported')
21
+ for (const old of base.columns) {
22
+ const column = table!.columns.find(c => c.name === old.name)
23
+ if (!column) reject(base.name, old.name, 'dropping or renaming a column is unsupported')
24
+ if (!equal(old, column)) reject(base.name, old.name, 'changing type/default/check/constraints is unsupported')
25
+ }
26
+ for (const column of table!.columns.filter(c => !base.columns.some(old => old.name === c.name))) {
27
+ if (column.references || table!.foreignKeys.some(f => f.columns.includes(column.name))) reject(base.name, column.name, 'adding a reference to an existing table is unsupported')
28
+ if (column.notNull && (column.defaultSql === null || column.defaultSql === 'NULL')) reject(base.name, column.name, 'NOT NULL additions require a non-null default')
29
+ sql.push(`ALTER TABLE ${quote(base.name)} ADD COLUMN ${renderColumn(column)};`)
30
+ }
31
+ for (const key of ['unique', 'checks', 'foreignKeys', 'indexes'] as const) {
32
+ if (!equal(base[key], table![key])) {
33
+ const changed = [...base.foreignKeys, ...table!.foreignKeys].find(f => !base.foreignKeys.some(b => equal(b, f)) || !table!.foreignKeys.some(b => equal(b, f)))
34
+ reject(base.name, key === 'foreignKeys' ? changed?.columns.at(-1) : undefined, `changing table ${key} is unsupported`)
35
+ }
36
+ }
37
+ }
38
+ for (const table of tables) if (!baseTables.some(t => t.name === table.name)) sql.push(renderTable(table))
39
+ return sql.length ? sql.join('\n') + '\n' : ''
40
+ }
41
+ function located(error: unknown, sources: SourceMap): never {
42
+ if (!(error instanceof SpecError)) throw error
43
+ const path = `entities.${error.table}${error.column ? `.fields.${error.column}` : ''}`
44
+ const source = sources[path] ?? sources[`entities.${error.table}`] ?? sources['']
45
+ throw new Error(`${source ? `${source.file}:${source.line}` : 'config.ts:1'}: ${error.message}`)
46
+ }
47
+ export function schemaLock(config: InstanceConfig, base?: SchemaLock, sources: SourceMap = {}): SchemaLock {
48
+ try {
49
+ const previous = base && validateLock(base)
50
+ const transitions = previous ? structuredClone(previous.transitions) : []
51
+ const entities: EntityLineage[] = []
52
+ const normalized = { account: config.account, entities: {} as InstanceConfig['entities'] }
53
+ const entityNames = new Map<string, string>()
54
+ const intents: { name: string; field?: string; transition: RenameTransition }[] = []
55
+ const usedEntities = new Set<string>()
56
+ const record = (name: string, field: string | undefined, entity: EntityLineage, from: { logical: string; physical: string }, to: string, fieldId?: string) => {
57
+ const existing = transitions.find(t => t.entityId === entity.id && t.phase !== 'contracted')
58
+ if (existing) {
59
+ if (existing.bridge === (fieldId ? 'field' : 'entity') && existing.fieldIds?.[0] === fieldId && equal(existing.from, from) && existing.to.logical === to) {
60
+ intents.push({ name, field, transition: existing }); return
61
+ }
62
+ throw new SpecError(name, field, `second open transition for ${entity.id}; finish transition ${existing.id} first`)
63
+ }
64
+ // History is append-only. Include its generation and skip any ID already
65
+ // present, including IDs assigned by an earlier writer.
66
+ let generation = transitions.length + 1
67
+ let id = transitionId(entity.id, fieldId, from.logical, to, generation)
68
+ while (transitions.some(t => t.id === id)) id = transitionId(entity.id, fieldId, from.logical, to, ++generation)
69
+ const transition: RenameTransition = { id, entityId: entity.id, ...(fieldId ? { fieldIds: [fieldId] } : {}), from, to: { logical: to, physical: to }, bridge: fieldId ? 'field' : 'entity', phase: 'expanded' }
70
+ transitions.push(transition); intents.push({ name, field, transition })
71
+ }
72
+ // Authoring uses renameFrom at both levels. Expanded locks keep the source
73
+ // mapping; the target is intent data until the separate switch slice.
74
+ for (const [name, input] of Object.entries(config.entities).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
75
+ if (name === config.account?.entity) {
76
+ if (input.renameFrom || Object.values(input.fields).some(f => f.renameFrom || f.backfillFrom)) throw new SpecError(name, undefined, 'SDK account migration intents are unsupported')
77
+ normalized.entities[name] = { ...input, fields: { ...input.fields } }
78
+ continue
79
+ }
80
+ const source = input.renameFrom ?? name
81
+ const old = previous?.entities.find(e => e.logicalName === source)
82
+ if (input.renameFrom && (!old || source === name || Object.hasOwn(config.entities, source) || previous?.entities.some(e => e.logicalName === name || e.physicalName === name))) throw new SpecError(name, undefined, 'ambiguous/missing source or collision for entity renameFrom')
83
+ if (old && usedEntities.has(old.id)) throw new SpecError(name, undefined, 'ambiguous entity renameFrom: source reused')
84
+ if (old) usedEntities.add(old.id)
85
+ const entity: EntityLineage = old ? structuredClone(old) : { id: initialEntityId(name), logicalName: name, physicalName: name, fields: [] }
86
+ if (input.renameFrom) record(name, undefined, entity, { logical: source, physical: entity.physicalName }, name)
87
+ entityNames.set(name, entity.physicalName)
88
+ const fields: typeof input.fields = {}
89
+ const fieldNames = new Map<string, string>()
90
+ const usedFields = new Set<string>()
91
+ for (const [key, field] of Object.entries(input.fields)) {
92
+ if (field.backfillFrom) throw new SpecError(name, key, 'backfillFrom is unsupported')
93
+ if (field.computed) {
94
+ if (field.renameFrom) throw new SpecError(name, key, 'computed renameFrom is unsupported')
95
+ fields[key] = field; continue
96
+ }
97
+ const source = field.renameFrom ?? key
98
+ const oldField = old?.fields.find(f => f.logicalName === source)
99
+ const oldColumn = previous?.tables.find(t => t.name === old?.physicalName)?.columns.find(c => c.name === oldField?.physicalName)
100
+ if (field.renameFrom && (!oldField || oldColumn?.implicit || source === key || Object.hasOwn(input.fields, source) || old?.fields.some(f => f.logicalName === key || f.physicalName === key))) throw new SpecError(name, key, 'ambiguous/missing source or collision for field renameFrom')
101
+ if (oldField && usedFields.has(oldField.id)) throw new SpecError(name, key, 'ambiguous field renameFrom: source reused')
102
+ if (oldField) usedFields.add(oldField.id)
103
+ const physical = oldField?.physicalName ?? key
104
+ if (field.renameFrom) record(name, key, entity, { logical: source, physical }, key, oldField!.id)
105
+ fieldNames.set(key, physical)
106
+ fields[physical] = { ...field, renameFrom: undefined }
107
+ }
108
+ normalized.entities[entity.physicalName] = { ...input, renameFrom: undefined, fields,
109
+ checks: input.checks.map(c => ({ ...c, left: fieldNames.get(c.left) ?? c.left, right: fieldNames.get(c.right) ?? c.right })),
110
+ }
111
+ entities.push(entity)
112
+ }
113
+ for (const entity of Object.values(normalized.entities)) entity.fields = Object.fromEntries(Object.entries(entity.fields).map(([key, field]) => [key,
114
+ field.type === 'ref' && field.entity && entityNames.has(field.entity) ? { ...field, entity: entityNames.get(field.entity)! } : field,
115
+ ]))
116
+ const tables = physicalTables(normalized, previous?.tables)
117
+ // Every rename must be definition-preserving and isolated from other schema
118
+ // edits. Diffing the source projection checks defaults, checks, FK and indexes.
119
+ const sql = diffSpecs(previous?.tables ?? [], tables)
120
+ const open = transitions.find(t => t.phase !== 'contracted')
121
+ if (open && sql) throw new SpecError(intents[0]?.name ?? entities.find(e => e.id === open.entityId)!.logicalName, intents[0]?.field, 'rename + definition change or unrelated schema edit is unsupported')
122
+ for (const entity of entities) {
123
+ const table = tables.find(t => t.name === entity.physicalName)!
124
+ entity.fields = table.columns.map(c => entity.fields.find(f => f.physicalName === c.name) ?? { id: initialFieldId(entity.id, c.name), logicalName: c.name, physicalName: c.name })
125
+ }
126
+ const changed = !!sql || !equal(transitions, previous?.transitions ?? [])
127
+ return validateLock({ lockVersion: 2, revision: previous ? previous.revision + Number(changed) : 1, parent: previous?.parent ?? null, tables, entities, transitions })
128
+ } catch (error) { return located(error, sources) }
129
+ }
130
+ export function parseLock(bytes: string): SchemaLock {
131
+ let value: unknown
132
+ try { value = JSON.parse(bytes) } catch { throw new Error('Invalid schema.lock.json: malformed JSON') }
133
+ return validateLock(value)
134
+ }
135
+ export function checkSchema(config: InstanceConfig, lock: SchemaLock, sources: SourceMap = {}) {
136
+ lock = validateLock(lock)
137
+ const current = schemaLock(config, lock, sources)
138
+ const canonical = physicalTables(config)
139
+ for (const [i, table] of current.tables.entries()) {
140
+ const previous = lock.tables.find(t => t.name === table.name)!
141
+ const entity = current.entities.find(e => e.physicalName === table.name)!
142
+ const intent = current.transitions.find(t => t.entityId === entity.id && t.bridge === 'entity' && t.phase === 'expanded')
143
+ const expected = canonical.find(t => t.name === entity.logicalName || t.name === intent?.to.logical)
144
+ const column = expected?.columns.find((column, i) => column.implicit && column.name !== previous?.columns[i]?.name)
145
+ if (previous && (lock.tables[i]?.name !== table.name || column)) located(new SpecError(entity.logicalName, column?.name, 'table/column order differs from the canonical physical schema'), sources)
146
+ }
147
+ // Compare by column name while retaining the lock's order; diffSpecs names unsupported drift.
148
+ const sql = diffSpecs(lock.tables, current.tables)
149
+ if (sql || !equal(current.entities, lock.entities) || !equal(current.transitions, lock.transitions)) {
150
+ if (!sql) located(new SpecError(current.entities[0]?.logicalName ?? '', undefined, 'lineage differs from schema.lock.json; regenerate the schema lock'), sources)
151
+ const table = current.tables.find(t => !lock.tables.some(b => b.name === t.name) || !equal(t, lock.tables.find(b => b.name === t.name)))!
152
+ const column = table.columns.find(c => !lock.tables.find(b => b.name === table.name)?.columns.some(b => equal(b, c)))
153
+ located(new SpecError(table.name, column?.name, 'schema differs from schema.lock.json; regenerate the schema lock'), sources)
154
+ }
155
+ }
156
+ /** SDK dependencies are derived, never versioned lock metadata. */
157
+ export function sdkDependencies(tables: readonly TableSpec[]) {
158
+ return [...new Set(tables.flatMap(t => [...t.foreignKeys.map(f => f.table), ...t.columns.flatMap(c => c.references ? [c.references.table] : [])]))].filter(name => !tables.some(t => t.name === name)).sort()
159
+ }
@@ -0,0 +1,94 @@
1
+ import type { InstanceConfig } from '../config'
2
+ import type { SourceMap } from '../schema/source-location'
3
+ import { sha256 } from '../crypto'
4
+ import { checkBundle, hasManual, manualEvidence, parseBundle, renderBundle } from './schema-bundle'
5
+ import { diffSpecs, lockBytes, parseLock, schemaLock, type SchemaLock } from './schema-lock'
6
+
7
+ export type MigrationFiles = Readonly<Record<string, string>>
8
+ export interface ExistingBundle { filename: string; sql: string }
9
+ export const bundleFilename = (revision: number) => `${String(revision).padStart(4, '0')}_r${revision}.sql`
10
+ export function fileRevision(filename: string): number {
11
+ const match = /^(\d+)_r([1-9]\d*)\.sql$/.exec(filename)
12
+ if (!match || !Number.isSafeInteger(Number(match[1])) || Number(match[1]) !== Number(match[2])) throw new Error(`${filename}:1: filename N must equal rN`)
13
+ return Number(match[2])
14
+ }
15
+ export function assertBaseFiles(base: MigrationFiles, current: MigrationFiles, replacing?: string) {
16
+ for (const [file, sql] of Object.entries(base)) if (file !== replacing && current[file] !== sql) throw new Error(`${file}:1: base migration ${current[file] === undefined ? 'missing' : 'edited'}; restore base bytes`)
17
+ }
18
+ function assertColumnOrder(base: SchemaLock | undefined, lock: SchemaLock) {
19
+ for (const table of base?.tables ?? []) {
20
+ const current = lock.tables.find(t => t.name === table.name)
21
+ if (!current) continue // diffSpecs reports unsupported table drops.
22
+ for (const [i, column] of table.columns.entries()) if (current.columns[i]?.name !== column.name) {
23
+ throw new Error(`schema.lock.json:1: ${table.name}.${column.name}: column order must preserve the base prefix; append new columns`)
24
+ }
25
+ }
26
+ }
27
+ /** This slice records rename intent only; no expansion/switch/contract SQL. */
28
+ export function assertNoRenameSQL(lock: SchemaLock) {
29
+ const transition = lock.transitions.find(t => t.phase !== 'contracted')
30
+ if (transition) throw new Error(`schema.lock.json:1: transition ${transition.id} (${transition.bridge} ${transition.from.logical} -> ${transition.to.logical}, ${transition.phase}): expansion SQL is unsupported in this slice`)
31
+ }
32
+ function assertLineage(base: SchemaLock | undefined, lock: SchemaLock) {
33
+ if (!base) return
34
+ for (const entity of base.entities) {
35
+ const current = lock.entities.find(e => e.id === entity.id)
36
+ if (!current || current.logicalName !== entity.logicalName || current.physicalName !== entity.physicalName) throw new Error(`schema.lock.json:1: immutable entity identity/mapping changed: ${entity.id}`)
37
+ for (const field of entity.fields) if (!current.fields.some(f => f.id === field.id && f.logicalName === field.logicalName && f.physicalName === field.physicalName)) throw new Error(`schema.lock.json:1: immutable field identity/mapping changed: ${field.id}`)
38
+ }
39
+ if (lock.transitions.length < base.transitions.length || base.transitions.some((t, i) => JSON.stringify(t) !== JSON.stringify(lock.transitions[i]))) throw new Error('schema.lock.json:1: transition history is immutable in this slice')
40
+ }
41
+ /** Checks the single permitted transition from the ref tip, never a merge-base. */
42
+ export async function checkLinkage(baseLock: string | undefined, baseMigrations: MigrationFiles, currentLock: string, migrations: MigrationFiles) {
43
+ if (baseLock === undefined && Object.keys(baseMigrations).length) throw new Error('Missing schema.lock.json in base with domain migrations; unsupported base history')
44
+ assertBaseFiles(baseMigrations, migrations)
45
+ const lock = parseLock(currentLock), base = baseLock === undefined ? undefined : parseLock(baseLock)
46
+ assertLineage(base, lock)
47
+ assertNoRenameSQL(lock)
48
+ assertColumnOrder(base, lock)
49
+ const added = Object.keys(migrations).filter(file => !(file in baseMigrations))
50
+ for (const [file, sql] of Object.entries(migrations)) {
51
+ const bundle = await checkBundle(file, sql)
52
+ if (fileRevision(file) !== bundle.revision) throw new Error(`${file}:1: header revision differs from filename`)
53
+ }
54
+ if (currentLock === baseLock && added.length === 0) return
55
+ // A byte-only, deterministic v1 bootstrap has no SQL/revision transition.
56
+ // The exact original parent and all migration bytes stay pinned.
57
+ if (baseLock !== undefined && JSON.parse(baseLock).lockVersion === 1 && added.length === 0 && currentLock === lockBytes(base!)) return
58
+ if (lock.parent !== (baseLock === undefined ? null : await sha256(baseLock))) throw new Error('schema.lock.json:1: wrong parent or stale base; regenerate against --base <ref> tip')
59
+ if (lock.revision !== (base?.revision ?? 0) + 1) throw new Error('schema.lock.json:1: revision skip or stale base; expected base.revision + 1')
60
+ if (added.length !== 1) throw new Error(`Expected exactly one new migration file; found ${added.length}`)
61
+ const file = added[0], bundle = parseBundle(file, migrations[file])
62
+ if (fileRevision(file) !== lock.revision) throw new Error(`${file}:1: migration gap; expected r${lock.revision}`)
63
+ if (bundle.parent !== lock.parent) throw new Error(`${file}:1: wrong parent; header must match schema.lock.json`)
64
+ const generated = diffSpecs(base?.tables ?? [], lock.tables)
65
+ if (!generated) throw new Error(`${file}:1: empty schema diff; data-only migrations are unsupported`)
66
+ if (bundle.generated !== generated) throw new Error(`${file}:1: generated region differs from lock diff; regenerate`)
67
+ }
68
+ /** Pure planning: all filesystem and Git state are supplied as bytes. */
69
+ export async function plan(input: {
70
+ baseLock?: string; baseMigrations: MigrationFiles; config: InstanceConfig
71
+ existingBundle?: ExistingBundle; confirmManual?: boolean; sources?: SourceMap
72
+ }) {
73
+ const { baseLock, baseMigrations, config, existingBundle, confirmManual, sources } = input
74
+ const base = baseLock === undefined ? undefined : parseLock(baseLock)
75
+ const lock = schemaLock(config, base, sources)
76
+ assertLineage(base, lock)
77
+ assertNoRenameSQL(lock)
78
+ assertColumnOrder(base, lock)
79
+ const generated = diffSpecs(base?.tables ?? [], lock.tables)
80
+ const previous = existingBundle && parseBundle(existingBundle.filename, existingBundle.sql)
81
+ if (!generated && base) {
82
+ if (previous && hasManual(previous)) throw new Error(`${existingBundle!.filename}:1: empty schema diff has manual SQL; refusing to delete manual regions`)
83
+ return { lock: JSON.parse(baseLock!).lockVersion === 1 ? lockBytes(base) : baseLock!, bundle: undefined }
84
+ }
85
+ lock.parent = baseLock === undefined ? null : await sha256(baseLock)
86
+ const bundle = { revision: lock.revision, parent: lock.parent, manual: 'none', pre: previous?.pre ?? '', generated, post: previous?.post ?? '' }
87
+ if (hasManual(bundle)) {
88
+ const unchanged = previous && previous.generated === generated && previous.parent === bundle.parent && previous.revision === bundle.revision
89
+ bundle.manual = confirmManual ? await manualEvidence(bundle) : unchanged ? previous.manual : 'unconfirmed'
90
+ }
91
+ const filename = bundleFilename(lock.revision)
92
+ if (filename in baseMigrations) throw new Error(`${filename}:1: new migration collides with base`)
93
+ return { lock: lockBytes(lock), bundle: { filename, sql: renderBundle(bundle) } }
94
+ }
@@ -1,8 +1,11 @@
1
+ import { systemSchema } from './system-schema'
2
+ export { systemSchema } from './system-schema'
1
3
  import { workflowSchema } from '../workflow-schema'
2
4
  import { opsSchema } from '../ops-schema'
3
5
  import { betterAuthSchema } from './better-auth-schema'
4
6
  import { emailDeliverySchema } from './email-delivery-schema'
5
7
  import { CORE_VERSION, type Field, type InstanceConfig } from '../config'
8
+ import { usesSdkBaseline } from './reset-era'
6
9
  export function quote(name: string) {
7
10
  if (!/^[a-z][a-z0-9_]*$/.test(name)) throw new Error(`Invalid SQL identifier: ${name}`)
8
11
  return `"${name}"`
@@ -14,64 +17,86 @@ export function literal(value: unknown): string {
14
17
  if (typeof value === 'string') return `'${value.replaceAll("'", "''")}'`
15
18
  throw new Error('Unsupported SQL literal')
16
19
  }
17
- export function column(name: string, f: Field) {
20
+ /** SQL-level data only. Runtime presentation and policy declarations never enter renderTable. */
21
+ export interface ColumnSpec {
22
+ name: string; sqlType: string; notNull: boolean; defaultSql: string | null; checks: string[]
23
+ implicit?: boolean; primaryKey?: boolean; references?: { table: string; column: string }
24
+ }
25
+ export interface TableSpec {
26
+ name: string; columns: ColumnSpec[]; unique: string[][]; checks: string[]
27
+ foreignKeys: { columns: string[]; table: string; targetColumns: string[] }[]
28
+ indexes: { name: string; columns: string[] }[]
29
+ }
30
+ function physicalColumn(name: string, f: Field): ColumnSpec {
18
31
  const q = quote(name)
19
- const type = ['int', 'bool'].includes(f.type) ? 'INTEGER' : f.type === 'float' ? 'REAL' : 'TEXT'
20
- return `${q} ${type}${f.required ? ' NOT NULL' : ''}${f.default !== undefined ? ` DEFAULT ${literal(f.default)}` : ''}${f.type === 'enum' ? ` CHECK (${q} IN (${f.values!.map(literal).join(', ')}))` : ''}${f.type === 'bool' ? ` CHECK (${q} IN (0,1))` : ''}${f.min !== undefined ? ` CHECK (${q} >= ${literal(f.min)})` : ''}`
32
+ return { name, sqlType: ['int', 'bool'].includes(f.type) ? 'INTEGER' : f.type === 'float' ? 'REAL' : 'TEXT',
33
+ notNull: f.required, defaultSql: f.default === undefined ? null : literal(f.default),
34
+ checks: [
35
+ ...(f.type === 'enum' ? [`${q} IN (${f.values!.map(literal).join(', ')})`] : []),
36
+ ...(f.type === 'bool' ? [`${q} IN (0,1)`] : []),
37
+ ...(f.min !== undefined ? [`${q} >= ${literal(f.min)}`] : []),
38
+ ],
39
+ }
21
40
  }
22
- export function createEntity(name: string, entity: InstanceConfig['entities'][string]) {
41
+ export function renderColumn(c: ColumnSpec) {
42
+ return `${c.implicit ? c.name : quote(c.name)} ${c.sqlType}${c.primaryKey ? ' PRIMARY KEY' : ''}${c.notNull ? ' NOT NULL' : ''}${c.defaultSql !== null ? ` DEFAULT ${c.defaultSql}` : ''}${c.references ? ` REFERENCES ${c.references.table}(${c.references.column})` : ''}${c.checks.map(check => ` CHECK (${check})`).join('')}`
43
+ }
44
+ // Legacy adapters project before rendering; the renderer knows only SQL specs.
45
+ export function column(name: string, field: Field) { return renderColumn(physicalColumn(name, field)) }
46
+ export function physicalTable(name: string, entity: InstanceConfig['entities'][string]): TableSpec {
47
+ const fields = Object.entries(entity.fields).filter(([, f]) => !f.computed)
48
+ const refs = fields.filter(([, f]) => f.type === 'ref')
49
+ const implicit = (name: string, sqlType: string, notNull = true, defaultSql: string | null = null): ColumnSpec =>
50
+ ({ name, sqlType, notNull, defaultSql, checks: [], implicit: true })
51
+ return { name, columns: [
52
+ { ...implicit('id', 'TEXT', false), primaryKey: true },
53
+ { ...implicit('organization_id', 'TEXT'), references: { table: 'organizations', column: 'id' } },
54
+ implicit('created_at', 'TEXT'), implicit('updated_at', 'TEXT'), implicit('version', 'INTEGER', true, '1'),
55
+ ...fields.map(([key, field]) => physicalColumn(key, field)),
56
+ ], unique: [['organization_id', 'id']],
57
+ checks: entity.checks.map(c => `${quote(c.left)} ${c.op} ${quote(c.right)}`),
58
+ foreignKeys: refs.map(([key, f]) => ({ columns: ['organization_id', key], table: f.entity!, targetColumns: ['organization_id', 'id'] })),
59
+ indexes: [{ name: `${name}_org_idx`, columns: ['organization_id', 'id'] }, ...refs.map(([key]) => ({ name: `${name}_${key}_idx`, columns: ['organization_id', key] }))],
60
+ }
61
+ }
62
+ export function renderTable(table: TableSpec) {
63
+ const q = (name: string) => table.columns.find(c => c.name === name)?.implicit ? name : quote(name)
23
64
  const columns = [
24
- 'id TEXT PRIMARY KEY', 'organization_id TEXT NOT NULL REFERENCES organizations(id)',
25
- 'created_at TEXT NOT NULL', 'updated_at TEXT NOT NULL', 'version INTEGER NOT NULL DEFAULT 1',
26
- ...Object.entries(entity.fields).filter(([, f]) => !f.computed).map(([k, f]) => column(k, f)), 'UNIQUE (organization_id, id)',
27
- ...Object.entries(entity.fields).filter(([, f]) => f.type === 'ref' && !f.computed).map(([k, f]) => `FOREIGN KEY (organization_id, ${quote(k)}) REFERENCES ${quote(f.entity!)}(organization_id, id)`),
28
- ...entity.checks.map(c => `CHECK (${quote(c.left)} ${c.op} ${quote(c.right)})`),
65
+ ...table.columns.map(renderColumn), ...table.unique.map(keys => `UNIQUE (${keys.map(q).join(', ')})`),
66
+ ...table.foreignKeys.map(f => `FOREIGN KEY (${f.columns.map(q).join(', ')}) REFERENCES ${quote(f.table)}(${f.targetColumns.join(', ')})`),
67
+ ...table.checks.map(check => `CHECK (${check})`),
29
68
  ]
30
- return `CREATE TABLE ${quote(name)} (\n ${columns.join(',\n ')}\n);\nCREATE INDEX ${quote(`${name}_org_idx`)} ON ${quote(name)}(organization_id, id);\n` + Object.entries(entity.fields).filter(([, f]) => f.type === 'ref' && !f.computed).map(([k]) => `CREATE INDEX ${quote(`${name}_${k}_idx`)} ON ${quote(name)}(organization_id, ${quote(k)});`).join('\n')
69
+ const indexes = table.indexes.map(index => `CREATE INDEX ${quote(index.name)} ON ${quote(table.name)}(${index.columns.map(q).join(', ')});`)
70
+ return `CREATE TABLE ${quote(table.name)} (\n ${columns.join(',\n ')}\n);\n${indexes[0]}\n${indexes.slice(1).join('\n')}`
71
+ }
72
+ export function createEntity(name: string, entity: InstanceConfig['entities'][string]) { return renderTable(physicalTable(name, entity)) }
73
+
74
+ /** New tables have canonical order; existing columns retain the base's physical order. */
75
+ export function physicalTables(config: Pick<InstanceConfig, 'entities' | 'account'>, base: readonly TableSpec[] = []): TableSpec[] {
76
+ return Object.entries(config.entities).filter(([name]) => name !== config.account?.entity).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, entity]) => {
77
+ const table = physicalTable(name, { ...entity, fields: Object.fromEntries(Object.entries(entity.fields).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) })
78
+ const previous = base.find(t => t.name === name)
79
+ if (previous) {
80
+ const names = previous.columns.map(c => c.name)
81
+ table.columns = [...names.flatMap(name => table.columns.filter(c => c.name === name)), ...table.columns.filter(c => !names.includes(c.name))]
82
+ }
83
+ return table
84
+ })
31
85
  }
32
- export const systemSchema = `
33
- CREATE TABLE atomic_assert (run_id TEXT NOT NULL, rule TEXT NOT NULL, step INTEGER NOT NULL DEFAULT 0, ok INTEGER NOT NULL CHECK (ok = 1), policy_ok INTEGER NOT NULL DEFAULT 1 CHECK (policy_ok = 1), actor_ok INTEGER NOT NULL DEFAULT 1 CHECK (actor_ok = 1), PRIMARY KEY (run_id, step)) WITHOUT ROWID;
34
- CREATE TABLE organizations (id TEXT PRIMARY KEY, name TEXT NOT NULL);
35
- CREATE TABLE users (id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, password_hash TEXT NOT NULL, salt TEXT NOT NULL, created_at TEXT NOT NULL);
36
- CREATE TABLE memberships (user_id TEXT NOT NULL REFERENCES users(id), organization_id TEXT NOT NULL REFERENCES organizations(id), role TEXT NOT NULL CHECK (role IN ('owner','dispatcher','viewer')), PRIMARY KEY (user_id, organization_id));
37
- CREATE TABLE sessions (token_hash TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), expires_at TEXT NOT NULL);
38
- CREATE INDEX sessions_user_idx ON sessions(user_id);
39
- CREATE TABLE invitations (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id), email TEXT NOT NULL, role TEXT NOT NULL CHECK (role IN ('owner','dispatcher','viewer')), token_hash TEXT NOT NULL UNIQUE, expires_at TEXT NOT NULL, accepted_at TEXT, accepted_user_id TEXT REFERENCES users(id), inviter_id TEXT NOT NULL REFERENCES users(id));
40
- CREATE INDEX invitations_org_idx ON invitations(organization_id);
41
- CREATE TABLE email_outbox (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id), recipient TEXT NOT NULL, subject TEXT NOT NULL, body TEXT NOT NULL, created_at TEXT NOT NULL);
42
- CREATE TABLE audit_outbox (event_id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, payload TEXT NOT NULL CHECK(json_valid(payload)), created_at TEXT NOT NULL, delivered_at TEXT, attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT);
43
- CREATE INDEX audit_outbox_pending_idx ON audit_outbox(delivered_at, created_at);
44
- CREATE TABLE security_log (id TEXT PRIMARY KEY, organization_id TEXT, actor_id TEXT, operation TEXT NOT NULL, status INTEGER NOT NULL, correlation_id TEXT NOT NULL, occurred_at TEXT NOT NULL, requested_scope_hash TEXT);
45
- CREATE INDEX security_log_org_idx ON security_log(organization_id, occurred_at);
46
- CREATE TABLE idempotency_keys (organization_id TEXT NOT NULL, key TEXT NOT NULL, command TEXT NOT NULL, response_json TEXT NOT NULL, request_hash TEXT, PRIMARY KEY (organization_id, key));
47
- CREATE TABLE webhook_deliveries (event_id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, payload TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at TEXT NOT NULL, last_error TEXT, lease_until TEXT);
48
- CREATE INDEX webhook_pending_idx ON webhook_deliveries(state, next_attempt_at);
49
86
 
50
- ALTER TABLE invitations ADD COLUMN revoked_at TEXT;
51
- ALTER TABLE invitations ADD COLUMN created_at TEXT;
52
- CREATE TABLE identities (
53
- user_id TEXT NOT NULL REFERENCES users(id), provider TEXT NOT NULL, issuer TEXT NOT NULL,
54
- subject TEXT NOT NULL, created_at TEXT NOT NULL, UNIQUE(provider, issuer, subject)
55
- );
56
- CREATE INDEX identities_user_idx ON identities(user_id);
57
- INSERT INTO identities (user_id,provider,issuer,subject,created_at) SELECT id,'local','local',id,created_at FROM users;
58
- CREATE TABLE access_tokens (
59
- id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id),
60
- issuer_id TEXT NOT NULL REFERENCES users(id), name TEXT NOT NULL,
61
- token_hash TEXT NOT NULL UNIQUE, prefix TEXT NOT NULL,
62
- role TEXT NOT NULL CHECK(role IN ('owner','dispatcher','viewer')),
63
- operations TEXT CHECK(operations IS NULL OR (json_valid(operations) AND json_type(operations)='array')),
64
- expires_at TEXT NOT NULL, revoked_at TEXT, last_used_at TEXT, created_at TEXT NOT NULL
65
- );
66
- CREATE INDEX access_tokens_org_idx ON access_tokens(organization_id);
67
- CREATE INDEX memberships_org_role_idx ON memberships(organization_id,role);
68
- CREATE TABLE instance_meta (revision INTEGER PRIMARY KEY, core_version TEXT NOT NULL, applied_at TEXT NOT NULL);
69
- `
70
87
  export const revisionSQL = (revision: number) => `INSERT INTO instance_meta VALUES (${revision}, '${CORE_VERSION}', strftime('%Y-%m-%dT%H:%M:%fZ','now'));`
71
88
  // Revisions are the primary key: preserve older rows and refresh only the current
72
89
  // revision's SDK stamp after deploy-time migration verification succeeds.
73
90
  export const coreVersionSQL = (revision: number) => `UPDATE instance_meta SET core_version = ${literal(CORE_VERSION)}, applied_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE revision = ${literal(revision)} AND revision = (SELECT MAX(revision) FROM instance_meta) AND core_version <> ${literal(CORE_VERSION)};`
74
- export const initialSchema = (config: InstanceConfig) => configuredSystemSchema(config) + opsSchema + (config.account?.entity === 'users' ? betterAuthSchema.replace('user_id TEXT NOT NULL REFERENCES users(id)', 'user_id TEXT NOT NULL REFERENCES "user"(id)') : betterAuthSchema) + emailDeliverySchema + workflowSchema + Object.entries(config.entities).filter(([n]) => !(n === 'users' && config.account?.entity === n)).map(([n, e]) => createEntity(n, e)).join('\n') + '\n' + revisionSQL(config.revision) + '\n'
91
+ /** New-era Instance SQL owns domain tables only.
92
+ * Preserve the inline defineInstance baseline until its consumers are retired. */
93
+ export function initialSchema(config: InstanceConfig) {
94
+ const legacy = !usesSdkBaseline(config)
95
+ ? configuredSystemSchema(config) + opsSchema + (config.account?.entity === 'users' ? betterAuthSchema.replace('user_id TEXT NOT NULL REFERENCES users(id)', 'user_id TEXT NOT NULL REFERENCES "user"(id)') : betterAuthSchema) + emailDeliverySchema + workflowSchema
96
+ : ''
97
+ if (usesSdkBaseline(config)) return physicalTables(config).map(renderTable).join('\n') + '\n'
98
+ return legacy + Object.entries(config.entities).filter(([n]) => !(n === 'users' && config.account?.entity === n)).map(([n, e]) => createEntity(n, e)).join('\n') + '\n' + revisionSQL(config.revision) + '\n'
99
+ }
75
100
 
76
101
  /** Fresh schemas support configured application roles and the explicit users/account extension.
77
102
  * Existing installations keep their append-only migration chain. */
@@ -0,0 +1,35 @@
1
+ import { operationalEvidenceMigration } from './operational-evidence'
2
+ import type { PluginMigration } from '../kernel/plugin'
3
+ import { systemSchema } from './system-schema'
4
+ import { betterAuthSchema } from './better-auth-schema'
5
+ import { emailDeliverySchema } from './email-delivery-schema'
6
+ import { workflowSchema } from '../workflow-schema'
7
+ import { opsSchema } from '../ops-schema'
8
+
9
+ export const SDK_NAMESPACE = 'workbase-sdk'
10
+ export const SDK_BASELINE = '001_system'
11
+
12
+ // SDK-owned Model B projection. Application roles are validated by the runtime,
13
+ // never baked into SDK SQL/checksums or supplied by an Instance domain migration.
14
+ const accounts = `CREATE TABLE users (
15
+ id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id),
16
+ email TEXT UNIQUE, password_hash TEXT NOT NULL DEFAULT '', salt TEXT NOT NULL DEFAULT '',
17
+ created_at TEXT NOT NULL, updated_at TEXT NOT NULL, version INTEGER NOT NULL DEFAULT 1,
18
+ name TEXT NOT NULL, role TEXT NOT NULL, UNIQUE (organization_id, id)
19
+ );
20
+ CREATE INDEX users_org_idx ON users(organization_id, id);`
21
+
22
+ // Share the retained system definitions while the inline entry path still ships.
23
+ // No live-catalog introspection/backfill or config-dependent statements in this era.
24
+ const baseline = systemSchema
25
+ .replace(/ CHECK ?\(role IN \('owner','dispatcher','viewer'\)\)/g, '')
26
+ .replace(/CREATE TABLE users \([^;]+;/, accounts)
27
+ .replace("INSERT INTO identities (user_id,provider,issuer,subject,created_at) SELECT id,'local','local',id,created_at FROM users;", '')
28
+ .replace('user_id TEXT NOT NULL REFERENCES users(id), provider', 'user_id TEXT NOT NULL REFERENCES "user"(id), provider')
29
+ + opsSchema + betterAuthSchema.replace('user_id TEXT NOT NULL REFERENCES users(id)', 'user_id TEXT NOT NULL REFERENCES "user"(id)')
30
+ + emailDeliverySchema + workflowSchema
31
+
32
+ /** Append only: one immutable SQL file and receipt per SDK step, same engine as plugins. */
33
+ export function sdkMigrations(): readonly PluginMigration[] {
34
+ return [{ name: SDK_BASELINE, sql: baseline }, operationalEvidenceMigration]
35
+ }
@@ -0,0 +1,39 @@
1
+ // Shared immutable system definitions for the retained inline path and SDK reset baseline.
2
+ export const systemSchema = `
3
+ CREATE TABLE atomic_assert (run_id TEXT NOT NULL, rule TEXT NOT NULL, step INTEGER NOT NULL DEFAULT 0, ok INTEGER NOT NULL CHECK (ok = 1), policy_ok INTEGER NOT NULL DEFAULT 1 CHECK (policy_ok = 1), actor_ok INTEGER NOT NULL DEFAULT 1 CHECK (actor_ok = 1), PRIMARY KEY (run_id, step)) WITHOUT ROWID;
4
+ CREATE TABLE organizations (id TEXT PRIMARY KEY, name TEXT NOT NULL);
5
+ CREATE TABLE users (id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, password_hash TEXT NOT NULL, salt TEXT NOT NULL, created_at TEXT NOT NULL);
6
+ CREATE TABLE memberships (user_id TEXT NOT NULL REFERENCES users(id), organization_id TEXT NOT NULL REFERENCES organizations(id), role TEXT NOT NULL CHECK (role IN ('owner','dispatcher','viewer')), PRIMARY KEY (user_id, organization_id));
7
+ CREATE TABLE sessions (token_hash TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id), expires_at TEXT NOT NULL);
8
+ CREATE INDEX sessions_user_idx ON sessions(user_id);
9
+ CREATE TABLE invitations (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id), email TEXT NOT NULL, role TEXT NOT NULL CHECK (role IN ('owner','dispatcher','viewer')), token_hash TEXT NOT NULL UNIQUE, expires_at TEXT NOT NULL, accepted_at TEXT, accepted_user_id TEXT REFERENCES users(id), inviter_id TEXT NOT NULL REFERENCES users(id));
10
+ CREATE INDEX invitations_org_idx ON invitations(organization_id);
11
+ CREATE TABLE email_outbox (id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id), recipient TEXT NOT NULL, subject TEXT NOT NULL, body TEXT NOT NULL, created_at TEXT NOT NULL);
12
+ CREATE TABLE audit_outbox (event_id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, payload TEXT NOT NULL CHECK(json_valid(payload)), created_at TEXT NOT NULL, delivered_at TEXT, attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT);
13
+ CREATE INDEX audit_outbox_pending_idx ON audit_outbox(delivered_at, created_at);
14
+ CREATE TABLE security_log (id TEXT PRIMARY KEY, organization_id TEXT, actor_id TEXT, operation TEXT NOT NULL, status INTEGER NOT NULL, correlation_id TEXT NOT NULL, occurred_at TEXT NOT NULL, requested_scope_hash TEXT);
15
+ CREATE INDEX security_log_org_idx ON security_log(organization_id, occurred_at);
16
+ CREATE TABLE idempotency_keys (organization_id TEXT NOT NULL, key TEXT NOT NULL, command TEXT NOT NULL, response_json TEXT NOT NULL, request_hash TEXT, PRIMARY KEY (organization_id, key));
17
+ CREATE TABLE webhook_deliveries (event_id TEXT PRIMARY KEY, organization_id TEXT NOT NULL, payload TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, next_attempt_at TEXT NOT NULL, last_error TEXT, lease_until TEXT);
18
+ CREATE INDEX webhook_pending_idx ON webhook_deliveries(state, next_attempt_at);
19
+
20
+ ALTER TABLE invitations ADD COLUMN revoked_at TEXT;
21
+ ALTER TABLE invitations ADD COLUMN created_at TEXT;
22
+ CREATE TABLE identities (
23
+ user_id TEXT NOT NULL REFERENCES users(id), provider TEXT NOT NULL, issuer TEXT NOT NULL,
24
+ subject TEXT NOT NULL, created_at TEXT NOT NULL, UNIQUE(provider, issuer, subject)
25
+ );
26
+ CREATE INDEX identities_user_idx ON identities(user_id);
27
+ INSERT INTO identities (user_id,provider,issuer,subject,created_at) SELECT id,'local','local',id,created_at FROM users;
28
+ CREATE TABLE access_tokens (
29
+ id TEXT PRIMARY KEY, organization_id TEXT NOT NULL REFERENCES organizations(id),
30
+ issuer_id TEXT NOT NULL REFERENCES users(id), name TEXT NOT NULL,
31
+ token_hash TEXT NOT NULL UNIQUE, prefix TEXT NOT NULL,
32
+ role TEXT NOT NULL CHECK(role IN ('owner','dispatcher','viewer')),
33
+ operations TEXT CHECK(operations IS NULL OR (json_valid(operations) AND json_type(operations)='array')),
34
+ expires_at TEXT NOT NULL, revoked_at TEXT, last_used_at TEXT, created_at TEXT NOT NULL
35
+ );
36
+ CREATE INDEX access_tokens_org_idx ON access_tokens(organization_id);
37
+ CREATE INDEX memberships_org_role_idx ON memberships(organization_id,role);
38
+ CREATE TABLE instance_meta (revision INTEGER PRIMARY KEY, core_version TEXT NOT NULL, applied_at TEXT NOT NULL);
39
+ `
@@ -0,0 +1,25 @@
1
+ import { z } from 'zod'
2
+ import type { InstanceConfig } from './config'
3
+
4
+ // Declarative model/input builders shared by runtime validation and build tools.
5
+ export const baseFields = ['id', 'organization_id', 'created_at', 'updated_at', 'version']
6
+ export function bodyValidator(entity: InstanceConfig['entities'][string], partial = false) {
7
+ const shape: Record<string, z.ZodType> = {}
8
+ for (const [name, f] of Object.entries(entity.fields)) {
9
+ if (f.readOnly || f.computed) continue
10
+ let v: z.ZodType
11
+ switch (f.type) {
12
+ case 'int': v = z.number().int().min(f.min ?? Number.MIN_SAFE_INTEGER); break
13
+ case 'float': v = z.number().min(f.min ?? -Number.MAX_VALUE); break
14
+ case 'bool': v = z.boolean(); break
15
+ case 'datetime': v = z.iso.datetime(); break
16
+ case 'enum': v = z.enum(f.values as [string, ...string[]]); break
17
+ default: v = z.string().min(1).max(f.type === 'text' ? 100000 : 2000)
18
+ }
19
+ if (!f.required) v = v.nullable()
20
+ if (!partial && f.default !== undefined) v = v.default(f.default)
21
+ else if (partial || !f.required) v = v.optional()
22
+ shape[name] = v
23
+ }
24
+ return z.strictObject(shape)
25
+ }