@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
@@ -1,5 +1,9 @@
1
+ import { assertSchemaLockBound } from '../schema/revision'
2
+ import { workerAccessCommands } from '../worker-access-actions'
3
+ import { bindActionPolicy } from '../record-actions'
4
+ import { accessGuards } from '../access-guards'
1
5
  import { isBuiltinPlugin } from './builtin-source'
2
- import { baseFields, defineInstance, type InstanceConfig, type InstanceInput, type Operation } from '../config'
6
+ import { baseFields, defineInstance, normalizeInstance, type InstanceConfig, type InstanceInput, type Operation } from '../config'
3
7
  import { createCommandRegistry, type CommandRegistry } from '../commands'
4
8
  import { createWorkflowRegistry, type WorkflowRegistry } from '../workflow-runtime'
5
9
  import { authorizeOperation } from '../authorization'
@@ -11,26 +15,38 @@ import type { AtomicOperation } from '../execution/types'
11
15
  import type { KernelCommand, ResourceAction, PluginMigration, Predicate, TableFilter, WorkbasePlugin } from './plugin'
12
16
  import { renderPredicate } from './predicate'
13
17
  export { renderPredicate } from './predicate'
18
+ import { DeclarationError } from '../schema/declaration'
14
19
  import { resolvePlugins } from './composition'
15
20
  import { applyPluginMigrations } from './migrations'
16
21
  import { timed } from '../request-timing'
22
+ import { policyFilter, readableFields, validatePolicies } from '../policies'
23
+ import { effectiveAuthority } from '../access-evaluator'
17
24
  import { userLinkCommands, userLinkActionPermission } from '../user-links'
18
25
 
19
26
  const registries = new WeakMap<InstanceConfig, KernelRegistry>()
20
27
  export const lifecyclePhases = ['contribute', 'validate', 'migrations', 'ports', 'mount'] as const
28
+ interface WorkflowRegistration { kind: 'runtime' | 'plugin'; plugin?: string; source: string }
21
29
  export class KernelRegistry {
22
30
  readonly plugins: readonly WorkbasePlugin[]
23
31
  readonly providers: ReadonlyMap<string, readonly WorkbasePlugin[]>
24
32
  readonly config: InstanceConfig
25
33
  readonly commands: CommandRegistry
26
34
  readonly workflows: WorkflowRegistry
35
+ /** Audit provenance captured during composition, including environment factories.
36
+ * Kept separate from the command-name guard registry. */
37
+ readonly workflowRegistrations: ReadonlyMap<string, WorkflowRegistration>
27
38
  readonly migrations: readonly PluginMigration[]
28
39
  /** True only for a complete permissions provider outside development trust. */
29
40
  readonly permissionsActive: boolean
30
41
  private readonly trust: boolean
31
42
  private readonly hasAuthorization: boolean
32
- constructor(config: InstanceInput, options: RuntimeOptions = {}, env?: RuntimeEnv) {
33
- const resolved = resolvePlugins(options.plugins ?? config.plugins ?? [], config.interactive)
43
+ /** Audit the actual runtime bypass, including separately supplied options. */
44
+ get authorizationTrust(): boolean { return this.trust }
45
+ constructor(config: InstanceInput & Pick<InstanceConfig, 'effectiveAccess'>, options: RuntimeOptions = {}, env?: RuntimeEnv) {
46
+ assertSchemaLockBound(config)
47
+ if (config.baseline === 'workbase-sdk' && !config.effectiveAccess) throw new DeclarationError(['access'], 'Executable schema configurations require explicit entity access and shared access.ts')
48
+ const configuredPlugins = options.plugins ?? config.plugins ?? []
49
+ const resolved = resolvePlugins(configuredPlugins, config.interactive)
34
50
  this.plugins = resolved.plugins
35
51
  this.providers = resolved.providers
36
52
  const names = new Set(this.plugins.map(plugin => plugin.name))
@@ -38,6 +54,8 @@ export class KernelRegistry {
38
54
  const entities = { ...config.entities }
39
55
  const commands = [...(options.commands?.values() ?? [])]
40
56
  const workflows = [...(options.workflows?.values() ?? [])]
57
+ const workflowRegistrations = new Map<string, WorkflowRegistration>(
58
+ workflows.map(workflow => [workflow.name, { kind: 'runtime', source: 'workflows' }]))
41
59
  const commandNames = [...(config.commands ?? [])]
42
60
  for (const plugin of this.plugins) {
43
61
  for (const [name, entity] of Object.entries(plugin.entities ?? {})) {
@@ -48,23 +66,38 @@ export class KernelRegistry {
48
66
  if (!isBuiltinPlugin(plugin) || !options.commands?.has(command.name)) commands.push(command)
49
67
  if (!commandNames.includes(command.name)) commandNames.push(command.name)
50
68
  }
51
- for (const workflow of [...(plugin.workflows ?? []), ...(env ? plugin.workflowDefinitions?.(env)?.values() ?? [] : [])]) {
52
- if (!isBuiltinPlugin(plugin) || !options.workflows?.has(workflow.name)) workflows.push(workflow)
69
+ // Source-map array positions belong to authored config.plugins, not the
70
+ // dependency-sorted plugin list. Runtime overrides use the enclosing fallback.
71
+ const source = options.plugins ? 'plugins' : `plugins.${configuredPlugins.indexOf(plugin)}`
72
+ const definitions = [
73
+ ...(plugin.workflows ?? []).map((workflow, index) => ({ workflow, source: `${source}.workflows.${index}` })),
74
+ ...[...(env ? plugin.workflowDefinitions?.(env)?.values() ?? [] : [])].map(workflow => ({ workflow, source: `${source}.workflowDefinitions` })),
75
+ ]
76
+ for (const { workflow, source } of definitions) {
77
+ if (!isBuiltinPlugin(plugin) || !options.workflows?.has(workflow.name)) {
78
+ workflows.push(workflow)
79
+ workflowRegistrations.set(workflow.name, { kind: 'plugin', plugin: plugin.name, source })
80
+ }
53
81
  }
54
82
  }
55
83
  // validate: whole model, registries, and each plugin-owned section.
56
84
  const pluginConfig = { ...config.pluginConfig }
57
85
  for (const plugin of this.plugins) if (plugin.configSchema) pluginConfig[plugin.name] = plugin.configSchema.parse(pluginConfig[plugin.name])
58
86
  for (const name of Object.keys(pluginConfig)) if (!names.has(name)) throw new Error(`Unknown plugin config: ${name}`)
59
- this.config = defineInstance({ ...config, plugins: this.plugins, entities, commands: commandNames,
87
+ const normalize = config.effectiveAccess ? (input: Parameters<typeof normalizeInstance>[0]) => normalizeInstance(input, true) : defineInstance
88
+ this.config = normalize({ ...config, plugins: this.plugins, entities, commands: commandNames,
60
89
  ...(config.pluginConfig || Object.keys(pluginConfig).length ? { pluginConfig } : {}) })
90
+ if (config.effectiveAccess) { this.config.effectiveAccess = config.effectiveAccess; validatePolicies(this.config) }
61
91
  this.providers.get('console')?.[0]?.validateConsole?.(this.config)
62
- for (const command of userLinkCommands(this.config)) {
92
+ for (const command of [...userLinkCommands(this.config), ...workerAccessCommands(this.config, env)]) {
63
93
  commands.push(command)
64
94
  if (!this.config.commands.includes(command.name)) this.config.commands.push(command.name)
65
95
  }
66
96
  this.commands = createCommandRegistry(commands)
67
97
  this.workflows = createWorkflowRegistry(workflows)
98
+ this.workflowRegistrations = workflowRegistrations
99
+ if (this.config.effectiveAccess) this.config.effectiveAccess = accessGuards(this.config.effectiveAccess, this.config.commands, [...this.commands.values()], this.plugins)
100
+ if (this.config.effectiveAccess) bindActionPolicy(this.config.effectiveAccess, this.config)
68
101
  // migrations: append hooks to the supplied chain. Applying D1 migrations remains an operator action.
69
102
  this.migrations = Object.freeze([...(options.migrations ?? []), ...this.plugins.flatMap(plugin => (plugin.migrations ?? []).map(migration => ({ ...migration, name: `${plugin.name}/${migration.name}` })))])
70
103
  if (new Set(this.migrations.map(migration => migration.name)).size !== this.migrations.length) throw new Error('Duplicate plugin migration')
@@ -85,6 +118,11 @@ export class KernelRegistry {
85
118
  if (!port) throw new ApiError(503, 'mail_outbox_required')
86
119
  return port
87
120
  }
121
+ get invitationMail() {
122
+ const port = this.providers.get('members')?.[0]?.invitationMail
123
+ if (!port) throw new ApiError(503, 'invitation_mail_required')
124
+ return port
125
+ }
88
126
  get audit() { return this.providers.get('audit')?.[0]?.audit }
89
127
  /** Explicit operator action; never run migrations in a request or on uninstall. */
90
128
  applyMigrations(db: D1Database) { return applyPluginMigrations(db, this.plugins, this.config) }
@@ -143,9 +181,12 @@ export class KernelRegistry {
143
181
  return actor
144
182
  })
145
183
  }
146
- tableFilter(entity: string, scope: Scope): TableFilter {
184
+ tableFilter(entity: string, scope: Scope, operation: Operation = 'read'): TableFilter {
147
185
  if (!this.trust && !this.hasAuthorization) return { kind: 'none' }
148
- const filters = this.plugins.flatMap(plugin => plugin.tableFilter ? [plugin.tableFilter.call(this, entity, scope)] : [])
186
+ // The compiled policy is mandatory regardless of the permissions provider.
187
+ // Its builtin adapter would duplicate it and use the default read operation.
188
+ const filters = this.plugins.flatMap(plugin => plugin.tableFilter && !(this.config.effectiveAccess && isBuiltinPlugin(plugin) && plugin.authorization && plugin.policyInConfig) ? [plugin.tableFilter.call(this, entity, scope)] : [])
189
+ if (this.config.effectiveAccess) filters.unshift(policyFilter(this.config, entity, scope, operation))
149
190
  if (!filters.length) return { kind: this.trust ? 'all' : 'none' }
150
191
  // A denying provider may erase row selection, but never request authority
151
192
  // needed by an enclosing policy that negates this source's existence.
@@ -156,7 +197,7 @@ export class KernelRegistry {
156
197
  return where.length ? { kind: 'where', predicate: { all: where.map(filter => filter.predicate) }, ...authority, ...(where.some(filter => filter.deny === 'forbidden') ? { deny: 'forbidden' as const } : {}) } : { kind: 'all', ...authority }
157
198
  }
158
199
  fieldMask(entity: string, scope: Scope): string[] {
159
- let fields = [...baseFields, ...Object.keys(this.config.entities[entity].fields)]
200
+ let fields = this.config.effectiveAccess ? readableFields(this.config, entity, scope) : [...baseFields, ...Object.keys(this.config.entities[entity].fields)]
160
201
  for (const plugin of this.plugins) if (plugin.fieldMask) {
161
202
  const mask = new Set(plugin.fieldMask.call(this, entity, scope))
162
203
  fields = fields.filter(field => mask.has(field))
@@ -164,12 +205,28 @@ export class KernelRegistry {
164
205
  return fields
165
206
  }
166
207
  commandGuard(command: KernelCommand, scope: Scope, input: unknown) {
167
- // Only the existing trusted identity writer can use this service permission.
168
- const internal = scope.actor.type === 'service' && 'system' in command.permission && command.permission.system === 'identity.write'
208
+ // Service authority is limited to trusted internal writers, even in trust mode.
209
+ const servicePermission = 'system' in command.permission && ['identity.write', 'organizations.provision', 'members.bootstrap'].includes(command.permission.system)
210
+ const internal = scope.actor.type === 'service' && servicePermission
211
+ if ((scope.actor.type === 'service' || servicePermission) && !internal) throw new ApiError(403, 'permission_denied')
169
212
  if (!internal && !this.trust && !this.hasAuthorization) throw new ApiError(403, 'permission_denied')
170
213
  // Credential restrictions and entity-scope provenance survive provider removal and trust.
171
214
  if (scope.actor.type === 'agent' || command.kind === 'entity') authorizeOperation(scope, operationName(command))
215
+ if (this.config.effectiveAccess && !internal) {
216
+ const policy = this.config.effectiveAccess
217
+ const authority = effectiveAuthority(policy, scope)
218
+ const primary = command.permission
219
+ if (command.kind === 'command') {
220
+ const guard = policy.guards.find(guard => guard.name === command.name)
221
+ if (!guard?.permission && !('system' in primary)) throw new ApiError(405, 'unsupported_command')
222
+ const requirements = guard?.permission ? [guard.permission, ...guard.additionalPermissions] : []
223
+ for (const grant of requirements) if (!authority.permits(grant)) throw new ApiError(403, 'permission_denied')
224
+ }
225
+ if (!authority.permits(primary)) throw new ApiError(403, 'permission_denied')
226
+ for (const grant of command.additionalPermissions ?? []) if (!authority.permits(grant)) throw new ApiError(403, 'permission_denied')
227
+ }
172
228
  for (const plugin of this.plugins) {
229
+ if (this.config.effectiveAccess && isBuiltinPlugin(plugin) && plugin.authorization && plugin.policyInConfig) continue
173
230
  const result = plugin.commandGuard?.call(this, command, scope, input)
174
231
  if (result && !result.allow) throw new ApiError(403, result.code)
175
232
  }
@@ -0,0 +1,65 @@
1
+ import { accountProvisioning } from './account-provisioning'
2
+ import { sha256 } from './crypto'
3
+ import { ApiError } from './errors'
4
+ import { RuleFailed } from './execution/errors'
5
+ import { kernelFor } from './kernel/registry'
6
+ import { validateRole } from './organization-permissions'
7
+ import { organizationRule } from './organization-rules'
8
+ import { membershipExecutor } from './organizations'
9
+ import { scopeOperations } from './scope-operations'
10
+ import type { InstanceConfig } from './config'
11
+ import type { RuntimeEnv, Scope } from './types'
12
+
13
+ /** Called by Members' ops-guarded route; never creates an identity or session. */
14
+ export async function bootstrapInstanceOwner(config: InstanceConfig, env: RuntimeEnv, ownerEmail: string, correlationId: string) {
15
+ const kernel = kernelFor(config)
16
+ if (!kernel.providers.has('members') || kernel.providers.has('organizations')) throw new ApiError(404, 'not_found')
17
+ const id = await kernel.resolveScopeId(env.DB)
18
+ const role = validateRole(config, config.organizationOwnerRole)
19
+ const signInRequired = { status: 409 as const, body: { error: 'owner_sign_in_required' } }
20
+ const verifiedOwner = () => env.DB.prepare('SELECT id,email FROM "user" WHERE lower(email)=? AND "emailVerified"=1')
21
+ .bind(ownerEmail.toLowerCase()).first<{ id: string; email: string }>()
22
+ const owner = await verifiedOwner()
23
+ if (!owner) return signInRequired
24
+ const key = 'members.bootstrap'
25
+ const command = 'members/bootstrap'
26
+ const requestHash = await sha256(JSON.stringify([owner.id, owner.email.toLowerCase()]))
27
+ // One durable receipt for the instance. Replays never restore a changed grant.
28
+ const replay = async () => {
29
+ const receipt = await env.DB.prepare('SELECT response_json,request_hash FROM idempotency_keys WHERE organization_id=? AND key=? AND command=?')
30
+ .bind(id, key, command).first<{ response_json: string; request_hash: string }>()
31
+ if (!receipt) return null
32
+ if (receipt.request_hash !== requestHash) throw new ApiError(409, 'instance_owner_exists')
33
+ const result = JSON.parse(receipt.response_json) as { body: { organization_id: string; user_id: string; role: string } }
34
+ return { status: 200 as const, body: { ...result.body, replayed: true } }
35
+ }
36
+ const prior = await replay()
37
+ if (prior) return prior
38
+ const hasOwner = () => env.DB.prepare('SELECT 1 FROM memberships WHERE organization_id=? AND role=?').bind(id, role).first()
39
+ if (await hasOwner()) throw new ApiError(409, 'instance_owner_exists')
40
+ const scope: Scope = { actor: { type: 'service', id: 'instance-owner-bootstrapper' }, organizationId: id, role: '', correlationId }
41
+ scopeOperations.set(scope, { operations: [command] })
42
+ const body = { organization_id: id, user_id: owner.id, role, replayed: false }
43
+ try {
44
+ const account = await accountProvisioning(env, config, owner, id, role, new Date().toISOString())
45
+ await membershipExecutor(config, env)(scope, command, 'members.bootstrap', {
46
+ rules: [organizationRule('instance_owner_bootstrap', ...account, {
47
+ sql: `INSERT INTO memberships (user_id,organization_id,role) SELECT ?,?,?
48
+ WHERE EXISTS (SELECT 1 FROM "user" WHERE id=? AND lower(email)=? AND "emailVerified"=1)
49
+ AND NOT EXISTS (SELECT 1 FROM memberships WHERE organization_id=? AND role=?)`,
50
+ bindings: [owner.id, id, role, owner.id, owner.email.toLowerCase(), id, role],
51
+ }), organizationRule('instance_owner_receipt', {
52
+ sql: 'INSERT INTO idempotency_keys (organization_id,key,command,response_json,request_hash) VALUES (?,?,?,?,?)',
53
+ bindings: [id, key, command, JSON.stringify({ status: 201, body }), requestHash],
54
+ })], event: { operation: 'membership.bootstrapped', entity: 'memberships', entityId: owner.id }, result: { status: 201, body },
55
+ })
56
+ } catch (error) {
57
+ const winner = await replay()
58
+ if (winner) return winner
59
+ if (!await verifiedOwner()) return signInRequired
60
+ if (await hasOwner()) throw new ApiError(409, 'instance_owner_exists')
61
+ if (error instanceof RuleFailed || /UNIQUE constraint failed: memberships\./i.test(String(error))) throw new ApiError(409, 'membership_conflict')
62
+ throw error
63
+ }
64
+ return { status: 201 as const, body }
65
+ }
@@ -0,0 +1,42 @@
1
+ import type { InstanceConfig } from './config'
2
+ import type { Scope } from './types'
3
+ import { kernelFor } from './kernel/registry'
4
+ import { organizationPermission } from './organization-permissions'
5
+ import { displayIdentity } from './display-identity'
6
+ import { accountLinkUnique, linkableMembers } from './user-link-eligibility'
7
+
8
+ /** Same gates as the Members read route, including attenuated token authority. */
9
+ export function requireMembersRead(config: InstanceConfig, scope: Scope) {
10
+ kernelFor(config).resourcePermission(scope, 'members.read')
11
+ organizationPermission(config, scope, 'members.read')
12
+ }
13
+ export function canReadMembers(config: InstanceConfig, scope: Scope): boolean {
14
+ if (!kernelFor(config).providers.has('members')) return false
15
+ try { requireMembersRead(config, scope); return true } catch { return false }
16
+ }
17
+ /** One workspace-scoped source for Members, linked identity and the Link picker.
18
+ * Email is already part of the Members projection under these exact gates.
19
+ * The optional id narrows a lookup; it never substitutes for the membership join.
20
+ * Only the Link picker opts into the writer's account eligibility filter.
21
+ */
22
+ export async function memberIdentities(config: InstanceConfig, scope: Scope, db: D1Database, userId?: string, target?: { entity: string; row: string }, search?: string) {
23
+ requireMembersRead(config, scope)
24
+ const eligible = target ? linkableMembers(scope.organizationId) : undefined
25
+ const unique = target ? accountLinkUnique(config, scope.organizationId, target, { member: true }) : undefined
26
+ const rows = await db.prepare(`SELECT m.user_id,u.email,m.role,a.name,p.first_name AS firstName,p.last_name AS lastName
27
+ FROM memberships m JOIN users u ON u.id=m.user_id LEFT JOIN "user" a ON a.id=u.id
28
+ LEFT JOIN identity_profiles p ON p.user_id=u.id AND (
29
+ NOT EXISTS (SELECT 1 FROM identities i WHERE i.user_id=u.id AND i.provider<>'local')
30
+ OR (p.synced_at IS NOT NULL
31
+ AND (SELECT count(*) FROM identities i WHERE i.user_id=u.id AND i.provider<>'local')=1
32
+ AND EXISTS (SELECT 1 FROM identities i WHERE i.user_id=u.id AND i.provider=p.source_provider AND i.issuer=p.source_issuer AND i.subject=p.source_subject)))
33
+ WHERE m.organization_id=?${userId === undefined ? '' : ' AND m.user_id=?'}${eligible ? ` AND m.user_id IN (${eligible.sql})` : ''}${unique ? ` AND ${unique.sql}` : ''} ORDER BY m.user_id`)
34
+ .bind(scope.organizationId, ...(userId === undefined ? [] : [userId]), ...(eligible?.bindings ?? []), ...(unique?.bindings ?? []))
35
+ .all<{ user_id: string; email: string; role: string; name: string | null; firstName: string | null; lastName: string | null }>()
36
+ // Filter on the server after SQL eligibility and the trusted identity projection.
37
+ // JS case folding also handles Czech names; SQLite lower() only folds ASCII.
38
+ const tokens = target ? (search ?? '').toLocaleLowerCase().trim().split(/\s+/).map(token => token.replace(/^[<]+|[>]+$/g, '')).filter(Boolean) : []
39
+ return rows.results.map(({ name, firstName, lastName, ...row }) => ({ ...row,
40
+ display_name: displayIdentity({ name, firstName, lastName, email: row.email }).displayName,
41
+ })).filter(row => tokens.every(token => [row.display_name, row.email].some(value => value?.toLocaleLowerCase().includes(token))))
42
+ }
@@ -1,4 +1,5 @@
1
1
  const messages = {
2
+ schema_lock_not_bound: 'schema lock not bound: bindSchemaLock(config, lock) before use',
2
3
  usage: 'usage: workbase-migrate migrate <database-id> <migration-directory> [--config <module-path>]; requires CLOUDFLARE_DEFAULT_ACCOUNT_ID and CLOUDFLARE_API_TOKEN',
3
4
  invalid_config_default_export: 'invalid_config_default_export',
4
5
  invalid_cloudflare_ids: 'invalid_cloudflare_ids',
@@ -14,6 +15,7 @@ const messages = {
14
15
  } as const
15
16
 
16
17
  type Diagnostic = { code: keyof typeof messages }
18
+ | { code: 'migration_unsupported_history'; found: string[] }
17
19
  | { code: 'd1_http_status'; status: number }
18
20
  | { code: 'migration_blocked'; reason: 'multiple_organizations' | 'account_organization_mismatch' | 'required_account_field'; userIds: string[]; field?: string }
19
21
  | { code: 'migration_blocked'; reason: 'incoming_foreign_key_actions'; table: string; referencingTables: string[] }
@@ -26,7 +28,10 @@ const diagnostics = new WeakMap<object, string>()
26
28
  export class MigrationDiagnostic extends Error {
27
29
  constructor(diagnostic: Diagnostic) {
28
30
  let message: string
29
- if (diagnostic.code === 'migration_blocked') {
31
+ if (diagnostic.code === 'migration_unsupported_history') {
32
+ const found = diagnostic.found.map(name => /^[a-zA-Z0-9_-]{1,128}$/.test(name) ? name : '[nonstandard table]')
33
+ message = `migration_unsupported_history:found ${found.join(', ')} without a compatible SDK baseline; old-era or mixed history is unsupported; reset the database explicitly (history was not changed)`
34
+ } else if (diagnostic.code === 'migration_blocked') {
30
35
  message = `migration_blocked:${diagnostic.reason}:${JSON.stringify(diagnostic.reason === 'incoming_foreign_key_actions' ? { table: diagnostic.table, referencingTables: diagnostic.referencingTables } : { field: diagnostic.field, userIds: diagnostic.userIds })}`
31
36
  } else if (diagnostic.code === 'd1_http_status') {
32
37
  const status = diagnostic.status
@@ -1,3 +1,4 @@
1
+ import { modelBOperationalEvidenceMigration } from './operational-evidence'
1
2
  import type { InstanceConfig } from '../config'
2
3
  import type { PluginMigration } from '../kernel/plugin'
3
4
  import { accountRoleValue } from '../account-provisioning'
@@ -141,5 +142,5 @@ export function coreMigrations(config?: InstanceConfig): readonly PluginMigratio
141
142
  const accounts = config?.account?.entity === 'users' ? [`INSERT INTO ${guard} (ok) SELECT NOT EXISTS (SELECT user_id FROM memberships GROUP BY user_id HAVING count(DISTINCT organization_id)>1) AND NOT EXISTS (SELECT 1 FROM memberships m WHERE NOT EXISTS (SELECT 1 FROM users u WHERE u.id=m.user_id AND u.organization_id=m.organization_id))`] : []
142
143
  return [`CREATE TABLE ${guard} (ok INTEGER CONSTRAINT rebuild_requires_review CHECK (ok = 1))`, 'PRAGMA defer_foreign_keys = ON', ...witnesses, ...statements, ...accounts,
143
144
  `INSERT INTO ${guard} (ok) SELECT NOT EXISTS (SELECT 1 FROM pragma_foreign_key_check)`, `DROP TABLE ${guard}`, 'PRAGMA defer_foreign_keys = OFF']
144
- } }]
145
+ } }, modelBOperationalEvidenceMigration]
145
146
  }
@@ -0,0 +1,51 @@
1
+ import type { PluginMigration } from '../kernel/plugin'
2
+
3
+ // Only trusted schema identifiers and fixed literals enter this builder. Histories
4
+ // belong to the existing source row; triggers make source + evidence one D1 write.
5
+ export function deliveryHistorySql(table: 'webhook_deliveries' | 'email_outbox' | 'audit_outbox', id: 'event_id' | 'id', state: string, codes: readonly string[], pendingOnInsert = true) {
6
+ const timestamp = "strftime('%Y-%m-%dT%H:%M:%fZ','now')"
7
+ const error = `CASE WHEN NEW.last_error IN (${codes.map(code => `'${code}'`).join(',')}) THEN NEW.last_error ELSE '${codes[0]}' END`
8
+ const snapshot = (pending: boolean) => `json_object('occurred_at',${timestamp},'state',${pending ? "'pending'" : state},'error_code',${pending ? "'backlog_pending'" : error},'attempts',NEW.attempts)`
9
+ return `ALTER TABLE ${table} ADD COLUMN operational_history TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(operational_history) AND json_type(operational_history)='array');
10
+ ${pendingOnInsert ? `CREATE TRIGGER ${table}_evidence_pending AFTER INSERT ON ${table} BEGIN
11
+ UPDATE ${table} SET operational_history=json_insert(operational_history,'$[#]',${snapshot(true)}) WHERE ${id}=NEW.${id};
12
+ END;` : ''}
13
+ CREATE TRIGGER ${table}_evidence_failure AFTER UPDATE OF last_error ON ${table}
14
+ WHEN NEW.last_error IS NOT NULL BEGIN
15
+ UPDATE ${table} SET operational_history=json_insert(operational_history,'$[#]',${snapshot(false)}) WHERE ${id}=NEW.${id};
16
+ END;
17
+ CREATE INDEX ${table}_evidence_org ON ${table}(organization_id,${id});`
18
+ }
19
+
20
+ const webhookEvidenceSql = `ALTER TABLE webhook_deliveries ADD COLUMN created_at TEXT;
21
+ CREATE TRIGGER webhook_deliveries_created AFTER INSERT ON webhook_deliveries WHEN NEW.created_at IS NULL BEGIN
22
+ UPDATE webhook_deliveries SET created_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE event_id=NEW.event_id;
23
+ END;
24
+ ${deliveryHistorySql('webhook_deliveries', 'event_id', "CASE WHEN NEW.state='failed' THEN 'failed' ELSE 'pending' END", ['delivery_failed', 'delivery_interrupted'])}
25
+ `
26
+ const relayEvidenceSql = `ALTER TABLE _ops_relay_run ADD COLUMN operational_history TEXT NOT NULL DEFAULT '[]' CHECK(json_valid(operational_history) AND json_type(operational_history)='array');
27
+ CREATE TRIGGER ops_relay_evidence_insert AFTER INSERT ON _ops_relay_run BEGIN
28
+ UPDATE _ops_relay_run SET operational_history=json_insert(operational_history,'$[#]',json_object('occurred_at',NEW.ts,'backlog',NEW.backlog,'oldest_age_seconds',NEW.oldest_age_seconds,'failed',NEW.failed,'delivered',NEW.delivered,'webhook_delivered',NEW.webhook_delivered,'errors',NEW.errors)) WHERE id=1;
29
+ END;
30
+ CREATE TRIGGER ops_relay_evidence_update AFTER UPDATE OF ts ON _ops_relay_run BEGIN
31
+ UPDATE _ops_relay_run SET operational_history=json_insert(operational_history,'$[#]',json_object('occurred_at',NEW.ts,'backlog',NEW.backlog,'oldest_age_seconds',NEW.oldest_age_seconds,'failed',NEW.failed,'delivered',NEW.delivered,'webhook_delivered',NEW.webhook_delivered,'errors',NEW.errors)) WHERE id=1;
32
+ END;
33
+ `
34
+
35
+ export const operationalEvidenceMigration: PluginMigration = {
36
+ name: '002_operational_evidence', sql: `\n${webhookEvidenceSql}${relayEvidenceSql}`,
37
+ }
38
+
39
+ // Model B also accepts migration-only databases without the SDK system schema.
40
+ // Keep the static identity/receipt, but only alter source tables that exist.
41
+ export const modelBOperationalEvidenceMigration: PluginMigration = {
42
+ ...operationalEvidenceMigration,
43
+ async statements(db) {
44
+ const { results } = await db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name IN ('webhook_deliveries','_ops_relay_run')").all<{ name: string }>()
45
+ const tables = new Set(results.map(row => row.name))
46
+ return [
47
+ ...(tables.has('webhook_deliveries') ? [webhookEvidenceSql] : []),
48
+ ...(tables.has('_ops_relay_run') ? [relayEvidenceSql] : []),
49
+ ]
50
+ },
51
+ }
@@ -1,9 +1,20 @@
1
1
  import { defineInstance, inspectInstance, type InstanceConfig } from '../config'
2
2
  import { column, createEntity, initialSchema, literal, quote, revisionSQL } from './schema'
3
3
  import { rebuildWithNullableRefs, type SupplementalIndex } from './rebuild'
4
+ import { schemaLock } from './schema-lock'
5
+ import { assertNoRenameSQL } from './schema-plan'
4
6
  export interface MigrationPlan { sql: string; destructive: string[]; blocked: string[]; warnings: string[] }
5
7
  export function plan(fromConfig: InstanceConfig | null, toConfig: InstanceConfig, options: { allowDestructive?: boolean; indexes?: SupplementalIndex[] } = {}): MigrationPlan {
6
8
  const to = defineInstance(toConfig)
9
+ // SDK-era callers cannot bypass the lock planner's rename gate by using this
10
+ // older entry point. Inline legacy configs keep their existing contract.
11
+ if (to.baseline === 'workbase-sdk' && Object.values(to.entities).some(e => e.renameFrom || Object.values(e.fields).some(f => f.renameFrom))) {
12
+ try { assertNoRenameSQL(schemaLock(to, fromConfig ? schemaLock(fromConfig) : undefined)) }
13
+ catch (error) {
14
+ const reason = error instanceof Error ? error.message : String(error)
15
+ return { sql: `-- BLOCKED: ${reason}\n`, destructive: [], blocked: [reason], warnings: [] }
16
+ }
17
+ }
7
18
  if (!fromConfig) return { sql: initialSchema(to), destructive: [], blocked: [], warnings: [] }
8
19
  // An older schema may violate a new presentation invariant; the result must
9
20
  // still pass strict validation above. Never alter its physical baseline.
@@ -107,6 +118,6 @@ export function plan(fromConfig: InstanceConfig | null, toConfig: InstanceConfig
107
118
  sql.push('PRAGMA defer_foreign_keys = OFF;')
108
119
  }
109
120
  sql.push(...referenceBackfills)
110
- sql.push(rebuilds.size ? revisionSQL(to.revision).replace('INSERT INTO', 'INSERT OR IGNORE INTO') : revisionSQL(to.revision))
121
+ if (to.baseline !== 'workbase-sdk') sql.push(rebuilds.size ? revisionSQL(to.revision).replace('INSERT INTO', 'INSERT OR IGNORE INTO') : revisionSQL(to.revision))
111
122
  return { sql: `-- ${from.id}: revision ${from.revision} -> ${to.revision}\n${sql.join('\n')}\n`, destructive, blocked, warnings }
112
123
  }
@@ -6,14 +6,16 @@ export interface SupplementalIndex { entity: string; name: string; fields: strin
6
6
 
7
7
  const differences = ['rowid', 'columns', 'indexes', 'foreign_keys', 'inline_constraints', 'triggers', 'incoming_actions'] as const
8
8
 
9
- /** Canonical multiset of top-level definitions. Token boundaries and string
10
- * contents survive normalization. Quoted identifiers (i), bare words (w),
9
+ /** Canonical multiset of top-level definitions from a body ending in ')'.
10
+ * Token boundaries and string contents survive normalization. Quoted identifiers (i), bare words (w),
11
11
  * numbers (n), strings (s) and punctuation (p) remain distinct. Only whitespace,
12
12
  * identifier quote style/case and definition order are ignored. Numeric states
13
13
  * consume decimal/hex digits and signed exponents without swallowing operators.
14
14
  * Comments, unknown characters, incomplete tokens and table suffixes fail closed.
15
+ * Defaults use the same scanner without identifier folding and require one part;
16
+ * only lexical whitespace is ignored, including between a sign and a number.
15
17
  */
16
- function definitions(table: string) {
18
+ function definitions(source: string, foldIdentifiers = true) {
17
19
  const ch = 'substr(body, pos, 1)', next = 'substr(body, pos + 1, 1)'
18
20
  const word = `${ch} GLOB '[a-zA-Z0-9_$]'`
19
21
  const digit = `${ch} GLOB '[0-9]'`
@@ -34,9 +36,7 @@ function definitions(table: string) {
34
36
  const space = `${ch} IN (' ', char(9), char(10), char(12), char(13))`
35
37
  const opening = `${ch} IN (${["'", '"', '`', '['].map(literal).join(', ')})`
36
38
  const punctuation = `${ch} IN (${[...'(),.+-*/%<>=~&|!'].map(literal).join(', ')})`
37
- return `(WITH RECURSIVE source(body) AS (
38
- SELECT substr(sql, instr(sql, '(') + 1) FROM sqlite_schema WHERE type = 'table' AND lower(name) = lower(${table})
39
- ), scan(pos, depth, mode, token, definition, parts) AS (
39
+ return `(WITH RECURSIVE source(body) AS (${source}), scan(pos, depth, mode, token, definition, parts) AS (
40
40
  SELECT 1, 0, '', '', '', json_array()
41
41
  UNION ALL
42
42
  SELECT pos + CASE WHEN ${flush} THEN 0 WHEN ${escaped} THEN 2 ELSE 1 END,
@@ -63,10 +63,10 @@ function definitions(table: string) {
63
63
  WHEN ${number} THEN token || ${ch}
64
64
  WHEN ${quoted} THEN CASE WHEN ${closing} AND NOT (${escaped}) THEN '' ELSE token || ${ch} END
65
65
  WHEN (${word}) OR (${ch} = '.' AND ${next} GLOB '[0-9]') THEN token || ${ch} ELSE '' END,
66
- CASE WHEN ${flush} THEN definition || json_quote(CASE WHEN mode = 'word' THEN 'w:' || lower(token) ELSE 'n:' || token END) || ','
66
+ CASE WHEN ${flush} THEN definition || json_quote(CASE WHEN mode = 'word' THEN 'w:' || ${foldIdentifiers ? 'lower(token)' : 'token'} ELSE 'n:' || token END) || ','
67
67
  WHEN ${number} THEN definition
68
68
  WHEN ${quoted} THEN CASE WHEN ${closing} AND NOT (${escaped})
69
- THEN definition || json_quote(CASE WHEN mode = ${literal("'")} THEN 's:' || token ELSE 'i:' || lower(token) END) || ',' ELSE definition END
69
+ THEN definition || json_quote(CASE WHEN mode = ${literal("'")} THEN 's:' || token ELSE 'i:' || ${foldIdentifiers ? 'lower(token)' : 'mode || token'} END) || ',' ELSE definition END
70
70
  WHEN ${boundary} THEN ''
71
71
  WHEN ${opening} OR (${word}) OR (${space}) OR (${ch} = '.' AND ${next} GLOB '[0-9]') THEN definition
72
72
  ELSE definition || json_quote('p:' || ${ch}) || ',' END,
@@ -74,14 +74,19 @@ function definitions(table: string) {
74
74
  FROM scan, source WHERE mode NOT IN ('done', 'invalid') AND pos <= length(body)
75
75
  ) SELECT json_group_array(value) FROM (
76
76
  SELECT value FROM scan, source, json_each(parts)
77
- WHERE mode = 'done' AND trim(substr(body, pos), ' ' || char(9) || char(10) || char(12) || char(13)) = '' ORDER BY value
77
+ WHERE mode = 'done' AND trim(substr(body, pos), ' ' || char(9) || char(10) || char(12) || char(13)) = ''
78
+ ${foldIdentifiers ? '' : "AND json_array_length(parts) = 1 AND value <> ''"} ORDER BY value
78
79
  ))`
79
80
  }
80
81
 
81
82
  /** Use SQLite itself to describe both the physical table and a generator-built
82
83
  * witness. Keep automatic indexes and auxiliary index columns in the fingerprint.
83
84
  * Compare ASCII-case-folded identifiers rather than history-dependent column/FK
84
- * IDs. Preserve default expressions and string/numeric literal contents exactly.
85
+ * IDs. Defaults ignore lexical whitespace only via the inline typed-token scanner:
86
+ * retain token kinds/boundaries, word/identifier case and quoting, string contents,
87
+ * numeric spelling, operators and parentheses. No default remains distinct from
88
+ * DEFAULT NULL. Do not evaluate expressions or equate arithmetic/parenthesized
89
+ * forms; the inline guard also retains parentheses SQLite may omit in dflt_value.
85
90
  * Body tokens cover CHECK, COLLATE, conflict clauses and FK deferrability, which
86
91
  * PRAGMAs do not expose, so unfamiliar DDL still fails closed.
87
92
  */
@@ -90,7 +95,7 @@ function fingerprint(name: string, indexNames: [string, string][] = []) {
90
95
  const indexName = indexNames.length ? `CASE lower(name) ${indexNames.map(([physical, canonical]) => `WHEN lower(${literal(physical)}) THEN lower(${literal(canonical)})`).join(' ')} ELSE lower(name) END` : 'lower(name)'
91
96
  return `json_object(
92
97
  'rowid', (SELECT wr FROM pragma_table_list WHERE schema = 'main' AND lower(name) = lower(${table})),
93
- 'columns', (SELECT json_group_array(json_array(lower(name), lower(type), "notnull", dflt_value, pk, hidden)) FROM (SELECT * FROM pragma_table_xinfo(${table}) ORDER BY lower(name))),
98
+ 'columns', (SELECT json_group_array(json_array(lower(name), lower(type), "notnull", CASE WHEN dflt_value IS NOT NULL THEN ${definitions("SELECT dflt_value || ')'", false)} END, pk, hidden)) FROM (SELECT * FROM pragma_table_xinfo(${table}) ORDER BY lower(name))),
94
99
  'indexes', (SELECT json_group_array(json_array(index_name, origin, "unique", partial, json(columns))) FROM (
95
100
  SELECT CASE WHEN origin = 'c' THEN ${indexName} ELSE origin END AS index_name, origin, "unique", partial,
96
101
  (SELECT json_group_array(json_array(seqno, CASE WHEN cid < 0 THEN cid END, lower(name), "desc", lower(coll), "key")) FROM (SELECT * FROM pragma_index_xinfo(i.name) ORDER BY seqno)) AS columns
@@ -99,7 +104,7 @@ function fingerprint(name: string, indexNames: [string, string][] = []) {
99
104
  SELECT lower("table") AS "table", on_update, on_delete, match,
100
105
  (SELECT json_group_array(json_array(seq, lower("from"), lower("to"))) FROM (SELECT * FROM pragma_foreign_key_list(${table}) WHERE id = fk.id ORDER BY seq)) AS columns
101
106
  FROM pragma_foreign_key_list(${table}) fk WHERE seq = 0 ORDER BY "table", on_update, on_delete, match, columns)),
102
- 'inline_constraints', ${definitions(table)},
107
+ 'inline_constraints', ${definitions(`SELECT substr(sql, instr(sql, '(') + 1) FROM sqlite_schema WHERE type = 'table' AND lower(name) = lower(${table})`)},
103
108
  'triggers', (SELECT count(*) FROM sqlite_schema WHERE type = 'trigger' AND lower(tbl_name) = lower(${table})),
104
109
  'incoming_actions', NOT EXISTS (SELECT 1 FROM sqlite_schema s, pragma_foreign_key_list(s.name) fk WHERE s.type = 'table' AND s.name NOT GLOB '_cf_*' AND s.name NOT GLOB 'sqlite_*' AND lower(fk."table") = lower(${table}) AND (fk.on_delete <> 'NO ACTION' OR fk.on_update <> 'NO ACTION'))
105
110
  )`
@@ -0,0 +1,29 @@
1
+ import type { InstanceConfig } from '../config'
2
+ import { MigrationDiagnostic } from './diagnostics'
3
+ import { SDK_BASELINE, SDK_NAMESPACE } from './sdk-baseline'
4
+
5
+ export type MigrationConfig = Pick<InstanceConfig, 'entities' | 'baseline'>
6
+ /** Era is schema data and survives copies, serialization and module realms. */
7
+ export function usesSdkBaseline(config?: Pick<InstanceConfig, 'baseline'>) {
8
+ return config?.baseline === 'workbase-sdk'
9
+ }
10
+
11
+ /** Read-only preflight, also used by direct kernel migration callers.
12
+ * A failed first SDK file may leave an empty receipt table, which is safe to retry.
13
+ * Every other pre-baseline application table/history requires an explicit reset. */
14
+ export async function assertResetEra(db: D1Database): Promise<boolean> {
15
+ const { results: tables } = await db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT GLOB 'sqlite_*' AND name NOT GLOB '_cf_*' ORDER BY name").all<{ name: string }>()
16
+ const ledger = tables.some(row => row.name === '_plugin_migrations')
17
+ const receipts = ledger ? (await db.prepare('SELECT namespace,name,position FROM _plugin_migrations ORDER BY namespace,position').all<{ namespace: string; name: string; position: number }>()).results : []
18
+ const baseline = receipts.some(row => row.namespace === SDK_NAMESPACE && row.name === SDK_BASELINE && row.position === 0)
19
+ const legacy = receipts.some(row => row.namespace === 'workbase-core')
20
+ const application = tables.filter(row => row.name !== '_plugin_migrations')
21
+ if (legacy || (!baseline && (application.length || receipts.length))) {
22
+ throw new MigrationDiagnostic({ code: 'migration_unsupported_history', found: [
23
+ ...application.map(row => row.name),
24
+ ...(ledger ? ['_plugin_migrations'] : []),
25
+ ...(legacy ? ['workbase-core'] : []),
26
+ ] })
27
+ }
28
+ return ledger
29
+ }
@@ -0,0 +1,43 @@
1
+ import { sha256 } from '../crypto'
2
+
3
+ export interface Bundle {
4
+ revision: number; parent: string | null; manual: string
5
+ pre: string; generated: string; post: string
6
+ }
7
+ const markers = ['begin pre-data', 'end pre-data', 'begin generated', 'end generated', 'begin post-data', 'end post-data']
8
+ const digest = '[a-f0-9]{64}'
9
+ const header = new RegExp(`^-- workbase:migration r([1-9]\\d*) parent=(${digest}|none) manual=(${digest}|unconfirmed|none)$`)
10
+ /** Only delimiters are interpreted. Region bodies retain every byte, including CRLF. */
11
+ export function parseBundle(file: string, sql: string): Bundle {
12
+ const lines = sql.match(/[^\n]*\n|[^\n]+$/g) ?? []
13
+ const fail = (line: number, reason: string): never => { throw new Error(`${file}:${line}: ${reason}`) }
14
+ const match = header.exec((lines[0] ?? '').replace(/\r?\n$/, ''))
15
+ if (!match || !Number.isSafeInteger(Number(match[1]))) fail(1, 'expected migration header')
16
+ const bodies = ['', '', '']
17
+ let next = 0
18
+ for (let i = 1; i < lines.length; i++) {
19
+ const line = lines[i].replace(/\r?\n$/, '')
20
+ if (line.startsWith('-- workbase:')) {
21
+ if (line !== `-- workbase:${markers[next]}` || next === markers.length) fail(i + 1, `duplicate, out-of-order or invalid marker; expected ${markers[next] ?? 'end of file'}`)
22
+ next++
23
+ } else if (next % 2 === 1) bodies[Math.floor(next / 2)] += lines[i]
24
+ else fail(i + 1, 'content outside regions')
25
+ }
26
+ if (next !== markers.length) fail(lines.length + 1, `missing marker -- workbase:${markers[next]}`)
27
+ return { revision: Number(match![1]), parent: match![2] === 'none' ? null : match![2], manual: match![3], pre: bodies[0], generated: bodies[1], post: bodies[2] }
28
+ }
29
+ export function renderBundle(bundle: Bundle): string {
30
+ return `-- workbase:migration r${bundle.revision} parent=${bundle.parent ?? 'none'} manual=${bundle.manual}\n`
31
+ + `-- workbase:begin pre-data\n${bundle.pre}-- workbase:end pre-data\n`
32
+ + `-- workbase:begin generated\n${bundle.generated}-- workbase:end generated\n`
33
+ + `-- workbase:begin post-data\n${bundle.post}-- workbase:end post-data\n`
34
+ }
35
+ export const hasManual = (bundle: Bundle) => bundle.pre.length > 0 || bundle.post.length > 0
36
+ /** Decimal UTF-8 byte length, colon, body; repeated in pre/generated/post order. */
37
+ export const manualEvidence = (bundle: Bundle) => sha256([bundle.pre, bundle.generated, bundle.post].map(body => `${new TextEncoder().encode(body).length}:${body}`).join(''))
38
+ export async function checkBundle(file: string, sql: string): Promise<Bundle> {
39
+ const bundle = parseBundle(file, sql)
40
+ const expected = hasManual(bundle) ? await manualEvidence(bundle) : 'none'
41
+ if (bundle.manual !== expected) throw new Error(`${file}:1: manual ${bundle.manual === 'unconfirmed' ? 'unconfirmed' : 'evidence mismatch'}; review manual regions and run migrate:plan --base <ref> --confirm-manual`)
42
+ return bundle
43
+ }