@abloatai/transaction 0.58.0 → 0.59.1

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 (59) hide show
  1. package/dist/client/ablo.d.ts +3 -4
  2. package/dist/client/ablo.d.ts.map +1 -1
  3. package/dist/client/ablo.js.map +1 -1
  4. package/dist/client/surface.d.ts +15 -0
  5. package/dist/client/surface.d.ts.map +1 -0
  6. package/dist/client/surface.js +29 -0
  7. package/dist/client/surface.js.map +1 -0
  8. package/dist/pricing.d.ts +7 -1
  9. package/dist/pricing.d.ts.map +1 -1
  10. package/dist/pricing.js +16 -2
  11. package/dist/pricing.js.map +1 -1
  12. package/dist/schema/ddl.d.ts.map +1 -1
  13. package/dist/schema/ddl.js +1 -1
  14. package/dist/schema/ddl.js.map +1 -1
  15. package/dist/schema/deployment/backfill.d.ts +44 -0
  16. package/dist/schema/deployment/backfill.d.ts.map +1 -0
  17. package/dist/schema/deployment/backfill.js +57 -0
  18. package/dist/schema/deployment/backfill.js.map +1 -0
  19. package/dist/schema/deployment/contracts.d.ts +526 -0
  20. package/dist/schema/deployment/contracts.d.ts.map +1 -0
  21. package/dist/schema/deployment/contracts.js +77 -0
  22. package/dist/schema/deployment/contracts.js.map +1 -0
  23. package/dist/schema/deployment/fingerprint.d.ts +3 -0
  24. package/dist/schema/deployment/fingerprint.d.ts.map +1 -0
  25. package/dist/schema/deployment/fingerprint.js +18 -0
  26. package/dist/schema/deployment/fingerprint.js.map +1 -0
  27. package/dist/schema/deployment/index.d.ts +18 -0
  28. package/dist/schema/deployment/index.d.ts.map +1 -0
  29. package/dist/schema/deployment/index.js +120 -0
  30. package/dist/schema/deployment/index.js.map +1 -0
  31. package/dist/schema/deployment/postgresCatalog.d.ts +39 -0
  32. package/dist/schema/deployment/postgresCatalog.d.ts.map +1 -0
  33. package/dist/schema/deployment/postgresCatalog.js +86 -0
  34. package/dist/schema/deployment/postgresCatalog.js.map +1 -0
  35. package/dist/schema/deployment/reconcile.d.ts +20 -0
  36. package/dist/schema/deployment/reconcile.d.ts.map +1 -0
  37. package/dist/schema/deployment/reconcile.js +318 -0
  38. package/dist/schema/deployment/reconcile.js.map +1 -0
  39. package/dist/schema/deployment/sequence.d.ts +4 -0
  40. package/dist/schema/deployment/sequence.d.ts.map +1 -0
  41. package/dist/schema/deployment/sequence.js +71 -0
  42. package/dist/schema/deployment/sequence.js.map +1 -0
  43. package/dist/schema/index.d.ts +1 -0
  44. package/dist/schema/index.d.ts.map +1 -1
  45. package/dist/schema/index.js +4 -0
  46. package/dist/schema/index.js.map +1 -1
  47. package/package.json +1 -1
  48. package/src/client/ablo.ts +2 -2
  49. package/src/client/surface.ts +50 -0
  50. package/src/pricing.ts +16 -2
  51. package/src/schema/ddl.ts +3 -1
  52. package/src/schema/deployment/backfill.ts +88 -0
  53. package/src/schema/deployment/contracts.ts +119 -0
  54. package/src/schema/deployment/fingerprint.ts +13 -0
  55. package/src/schema/deployment/index.ts +132 -0
  56. package/src/schema/deployment/postgresCatalog.ts +131 -0
  57. package/src/schema/deployment/reconcile.ts +335 -0
  58. package/src/schema/deployment/sequence.ts +85 -0
  59. package/src/schema/index.ts +5 -0
package/src/pricing.ts CHANGED
@@ -46,7 +46,7 @@ export type { MeterEvent, PlanTier, RateBracket };
46
46
  * could observe the difference. It is emitted into the generated pricing
47
47
  * documentation so a stale copy is identifiable on sight.
48
48
  */
49
- export const PRICING_VERSION = '2026-08-24';
49
+ export const PRICING_VERSION = '2026-08-28';
50
50
 
51
51
  /**
52
52
  * Resolve a stored plan string (`stripe_subscription.plan`) to a tier.
@@ -257,7 +257,7 @@ export const PLANS = z
257
257
  hardCapOps: null,
258
258
  hardCapOpsPerDay: null,
259
259
  storageGib: 50,
260
- maxConcurrentConnections: 1_000,
260
+ maxConcurrentConnections: 5_000,
261
261
  contractPriced: false,
262
262
  features: ['auditExport'],
263
263
  },
@@ -397,3 +397,17 @@ export function dailyOpsCapForTier(tier: PlanTier): number | null {
397
397
  export function connectionCapForTier(tier: PlanTier): number | null {
398
398
  return PLANS[tier].maxConcurrentConnections;
399
399
  }
400
+
401
+ /**
402
+ * The first public tier that can reserve the requested connection capacity.
403
+ * A `null` cap is negotiated capacity, not infinity in the runtime; it is the
404
+ * commercial catch-all that sends the buyer into an Enterprise capacity plan.
405
+ */
406
+ export function selectPlanForConnectionCapacity(connections: number): PlanTier {
407
+ const requested = Number.isFinite(connections) ? Math.max(1, Math.ceil(connections)) : 1;
408
+ for (const tier of PLAN_ORDER) {
409
+ const cap = PLANS[tier].maxConcurrentConnections;
410
+ if (cap === null || requested <= cap) return tier;
411
+ }
412
+ return 'enterprise';
413
+ }
package/src/schema/ddl.ts CHANGED
@@ -318,7 +318,9 @@ export function generateProvisionPlan(
318
318
  for (const [fieldName, meta] of Object.entries(model.fields)) {
319
319
  const col = meta.column ?? camelToSnake(fieldName);
320
320
  if (BASE_COLUMNS.has(col) || col === orgCol) continue;
321
- statements.push(`ALTER TABLE ${qt} ADD COLUMN IF NOT EXISTS ${q(col)} ${sqlType(meta.type)};`);
321
+ statements.push(
322
+ `ALTER TABLE ${qt} ADD COLUMN IF NOT EXISTS ${q(col)} ${sqlType(meta.type)}${meta.isOptional ? '' : ' NOT NULL'};`,
323
+ );
322
324
  if (meta.type === 'enum' && meta.enumValues && meta.enumValues.length > 0) {
323
325
  const cname = `${table}_${col}_enum`;
324
326
  const allowed = meta.enumValues.map((v) => `'${v.replace(/'/g, "''")}'`).join(', ');
@@ -0,0 +1,88 @@
1
+ export type BackfillStatus = 'pending' | 'running' | 'paused' | 'succeeded' | 'failed' | 'cancelled';
2
+
3
+ export interface BackfillCheckpoint {
4
+ readonly jobId: string;
5
+ readonly idempotencyKey: string;
6
+ readonly cursor: string | null;
7
+ readonly processed: number;
8
+ readonly batches: number;
9
+ readonly status: BackfillStatus;
10
+ readonly updatedAt: string;
11
+ readonly error?: string;
12
+ }
13
+
14
+ export interface BackfillBatchResult {
15
+ readonly nextCursor: string | null;
16
+ readonly processed: number;
17
+ readonly done: boolean;
18
+ }
19
+
20
+ export interface ResumableBackfillEffects {
21
+ readonly load: (jobId: string) => Promise<BackfillCheckpoint | null>;
22
+ readonly save: (checkpoint: BackfillCheckpoint) => Promise<void>;
23
+ /** Must be idempotent for the job idempotency key and input cursor. */
24
+ readonly runBatch: (input: { jobId: string; idempotencyKey: string; cursor: string | null; limit: number; signal?: AbortSignal }) => Promise<BackfillBatchResult>;
25
+ readonly now?: () => string;
26
+ readonly retry?: (error: unknown, attempt: number) => Promise<void>;
27
+ /** Operational throttle checked before each batch; pause preserves the checkpoint for an exact resume. */
28
+ readonly beforeBatch?: (checkpoint: BackfillCheckpoint) => Promise<'run' | 'pause'>;
29
+ readonly onProgress?: (checkpoint: BackfillCheckpoint) => Promise<void> | void;
30
+ }
31
+
32
+ export interface ResumableBackfillOptions {
33
+ readonly jobId: string;
34
+ readonly idempotencyKey: string;
35
+ readonly batchSize?: number;
36
+ readonly maxBatches?: number;
37
+ readonly maxAttempts?: number;
38
+ readonly signal?: AbortSignal;
39
+ }
40
+
41
+ /** Bounded, resumable runner. A durable effect owns checkpoints; the transform owns idempotency. */
42
+ export async function runResumableBackfill(effects: ResumableBackfillEffects, options: ResumableBackfillOptions): Promise<BackfillCheckpoint> {
43
+ if (!options.jobId || !options.idempotencyKey) throw new Error('backfill jobId and idempotencyKey are required');
44
+ const batchSize = options.batchSize ?? 500;
45
+ const maxBatches = options.maxBatches ?? 100;
46
+ const maxAttempts = options.maxAttempts ?? 3;
47
+ if (batchSize < 1 || maxBatches < 1 || maxAttempts < 1) throw new Error('backfill bounds must be positive');
48
+ const now = effects.now ?? (() => new Date().toISOString());
49
+ let checkpoint = await effects.load(options.jobId) ?? { jobId: options.jobId, idempotencyKey: options.idempotencyKey, cursor: null, processed: 0, batches: 0, status: 'pending' as const, updatedAt: now() };
50
+ if (checkpoint.idempotencyKey !== options.idempotencyKey) throw new Error(`backfill job ${options.jobId} was created with a different idempotency key`);
51
+ if (checkpoint.status === 'succeeded') return checkpoint;
52
+ for (let batch = 0; batch < maxBatches; batch++) {
53
+ if (options.signal?.aborted) {
54
+ checkpoint = { ...checkpoint, status: 'cancelled', updatedAt: now() };
55
+ await effects.save(checkpoint);
56
+ return checkpoint;
57
+ }
58
+ if (await effects.beforeBatch?.(checkpoint) === 'pause') {
59
+ checkpoint = { ...checkpoint, status: 'paused', updatedAt: now() };
60
+ await effects.save(checkpoint);
61
+ await effects.onProgress?.(checkpoint);
62
+ return checkpoint;
63
+ }
64
+ let result: BackfillBatchResult | undefined;
65
+ let lastError: unknown;
66
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
67
+ try {
68
+ result = await effects.runBatch({ jobId: options.jobId, idempotencyKey: options.idempotencyKey, cursor: checkpoint.cursor, limit: batchSize, ...(options.signal ? { signal: options.signal } : {}) });
69
+ break;
70
+ } catch (error) {
71
+ lastError = error;
72
+ if (attempt < maxAttempts) await effects.retry?.(error, attempt);
73
+ }
74
+ }
75
+ if (!result) {
76
+ checkpoint = { ...checkpoint, status: 'failed', updatedAt: now(), error: lastError instanceof Error ? lastError.message : String(lastError) };
77
+ await effects.save(checkpoint);
78
+ await effects.onProgress?.(checkpoint);
79
+ return checkpoint;
80
+ }
81
+ if (!result.done && result.nextCursor === checkpoint.cursor) throw new Error(`backfill job ${options.jobId} did not advance its cursor`);
82
+ checkpoint = { jobId: checkpoint.jobId, idempotencyKey: checkpoint.idempotencyKey, cursor: result.nextCursor, processed: checkpoint.processed + result.processed, batches: checkpoint.batches + 1, status: result.done ? 'succeeded' : 'running', updatedAt: now() };
83
+ await effects.save(checkpoint);
84
+ await effects.onProgress?.(checkpoint);
85
+ if (result.done) return checkpoint;
86
+ }
87
+ return checkpoint;
88
+ }
@@ -0,0 +1,119 @@
1
+ import { z } from 'zod';
2
+ import type { SchemaJSON } from '../serialize.js';
3
+ import type { BackfillValue, RenameHints } from '../diff.js';
4
+ import type { MigrationStep } from '../diff.js';
5
+
6
+ export const deploymentPhaseSchema = z.enum(['intent', 'expand', 'dual_write', 'backfill', 'verify', 'switch', 'contract', 'recover']);
7
+ export type DeploymentPhase = z.infer<typeof deploymentPhaseSchema>;
8
+ export const deploymentOwnerSchema = z.enum(['application', 'application_migration', 'ablo']);
9
+ export type DeploymentOwner = z.infer<typeof deploymentOwnerSchema>;
10
+ export const deploymentSeveritySchema = z.enum(['blocker', 'error', 'warning', 'info']);
11
+ export type DeploymentSeverity = z.infer<typeof deploymentSeveritySchema>;
12
+ export const deploymentCategorySchema = z.enum(['policy_intent', 'physical_contract', 'compatibility', 'data_movement', 'destructive_contract', 'advisory', 'observation']);
13
+ export type DeploymentCategory = z.infer<typeof deploymentCategorySchema>;
14
+ export const deploymentDirectionSchema = z.enum(['source_to_active', 'source_to_database', 'active_to_database', 'client_to_active']);
15
+ export type DeploymentDirection = z.infer<typeof deploymentDirectionSchema>;
16
+
17
+ export const databaseColumnSnapshotSchema = z.object({
18
+ name: z.string(), dataType: z.string(), nullable: z.boolean(), default: z.string().nullable(), primary: z.boolean(), unique: z.boolean(),
19
+ /** Capped count of rows whose required routing value is NULL; absent for ordinary columns. */
20
+ nullCount: z.number().int().nonnegative().nullable().optional(),
21
+ });
22
+ export type DatabaseColumnSnapshot = z.infer<typeof databaseColumnSnapshotSchema>;
23
+ export const databaseIndexSnapshotSchema = z.object({
24
+ name: z.string(), columns: z.array(z.string()), unique: z.boolean(), valid: z.boolean(), ready: z.boolean(), predicate: z.string().nullable(),
25
+ });
26
+ export const databaseForeignKeySnapshotSchema = z.object({
27
+ name: z.string(), columns: z.array(z.string()), referencedSchema: z.string(), referencedTable: z.string(), referencedColumns: z.array(z.string()), validated: z.boolean(),
28
+ });
29
+ export const databaseTableSnapshotSchema = z.object({
30
+ schema: z.string(), name: z.string(), columns: z.record(z.string(), databaseColumnSnapshotSchema),
31
+ indexes: z.array(databaseIndexSnapshotSchema).optional(), foreignKeys: z.array(databaseForeignKeySnapshotSchema).optional(),
32
+ rowLevelSecurity: z.boolean().nullable(), forceRowLevelSecurity: z.boolean().nullable(),
33
+ replicaIdentity: z.string().nullable(), publicationMember: z.boolean().nullable(),
34
+ });
35
+ export type DatabaseTableSnapshot = z.infer<typeof databaseTableSnapshotSchema>;
36
+ export const databaseSnapshotSchema = z.object({
37
+ observedAt: z.string(), subject: z.string(), fingerprint: z.string(), appSchema: z.string(), ownership: z.enum(['application', 'ablo']),
38
+ tables: z.record(z.string(), databaseTableSnapshotSchema),
39
+ });
40
+ export type DatabaseSnapshot = z.infer<typeof databaseSnapshotSchema>;
41
+
42
+ export interface SourceSchemaSnapshot { readonly observedAt: string; readonly path: string; readonly hash: string; readonly schema: SchemaJSON; }
43
+ export interface ActiveSchemaSnapshot { readonly observedAt: string; readonly schemaId: string; readonly version: number; readonly hash: string; readonly pushedAt: string | null; readonly schema: SchemaJSON; }
44
+ export interface DeploymentTarget { readonly organizationId: string | null; readonly projectId: string | null; readonly branchId: string | null; readonly databaseSubject: string | null; readonly confirmed: boolean; }
45
+ export const deploymentGateSchema = z.object({
46
+ id: z.string().min(1),
47
+ phase: z.enum(['expand', 'dual_write', 'backfill', 'verify', 'switch', 'contract']),
48
+ owner: deploymentOwnerSchema,
49
+ resource: z.string().min(1),
50
+ title: z.string().min(1),
51
+ action: z.string().min(1),
52
+ status: z.enum(['pending', 'ready', 'satisfied']),
53
+ dependsOn: z.array(z.string()).default([]),
54
+ approval: z.string().min(1).optional(),
55
+ });
56
+ export const deploymentManifestSchema = z.object({
57
+ id: z.string().min(1),
58
+ live: z.boolean().default(true),
59
+ targetPhase: z.enum(['expand', 'dual_write', 'backfill', 'verify', 'switch', 'contract']).default('expand'),
60
+ gates: z.array(deploymentGateSchema),
61
+ });
62
+ export type DeploymentGate = z.infer<typeof deploymentGateSchema>;
63
+ export type DeploymentManifest = z.infer<typeof deploymentManifestSchema>;
64
+ export interface DeploymentIntent { readonly renames?: RenameHints; readonly backfills?: readonly BackfillValue[]; readonly acceptDestructive?: boolean; readonly manifest?: DeploymentManifest; }
65
+ export interface DeploymentObservation { readonly target: DeploymentTarget; readonly source: SourceSchemaSnapshot; readonly active: ActiveSchemaSnapshot | null; readonly database: DatabaseSnapshot | null; readonly intent?: DeploymentIntent; readonly supplementalFindings?: readonly DeploymentFinding[]; }
66
+
67
+ export interface DeploymentFinding {
68
+ readonly id: string; readonly code: string; readonly category: DeploymentCategory; readonly severity: DeploymentSeverity;
69
+ readonly direction: DeploymentDirection; readonly phase: DeploymentPhase; readonly owner: DeploymentOwner;
70
+ readonly model?: string; readonly field?: string; readonly column?: string; readonly from?: unknown; readonly to?: unknown;
71
+ readonly message: string; readonly action: string;
72
+ readonly dependsOn?: readonly string[];
73
+ }
74
+ export interface DeploymentStep {
75
+ readonly id: string; readonly phase: DeploymentPhase; readonly owner: DeploymentOwner; readonly title: string; readonly action: string;
76
+ readonly dependsOn: readonly string[]; readonly findingIds: readonly string[]; readonly status: 'ready' | 'blocked' | 'advisory'; readonly executableByAblo: boolean;
77
+ }
78
+ export interface SchemaDeploymentPlan {
79
+ readonly id: 'ablo-schema-deployment-plan-v1'; readonly mode: 'plan'; readonly createdAt: string; readonly fingerprint: string; readonly target: DeploymentTarget;
80
+ readonly states: { readonly source: Omit<SourceSchemaSnapshot, 'schema'>; readonly active: Omit<ActiveSchemaSnapshot, 'schema'> | null; readonly database: Omit<DatabaseSnapshot, 'tables'> | null; };
81
+ readonly findings: readonly DeploymentFinding[]; readonly steps: readonly DeploymentStep[]; readonly outcome: 'aligned' | 'ready' | 'blocked';
82
+ readonly operations: { readonly sourceToActive: readonly MigrationStep[]; readonly provision: readonly MigrationStep[] };
83
+ readonly rollbackTarget: { readonly schemaId: string; readonly version: number; readonly hash: string; readonly strategy: 'reactivate_artifact'; } | null;
84
+ readonly recovery: 'rollback' | 'forward_only';
85
+ }
86
+ export interface DeploymentApplyResult { readonly plan: SchemaDeploymentPlan; readonly appliedStepIds: readonly string[]; readonly verification: SchemaDeploymentPlan; readonly recorded: boolean; }
87
+
88
+ export const deploymentTargetSchema = z.object({
89
+ organizationId: z.string().nullable(), projectId: z.string().nullable(), branchId: z.string().nullable(), databaseSubject: z.string().nullable(), confirmed: z.boolean(),
90
+ });
91
+ export const deploymentFindingSchema = z.object({
92
+ id: z.string(), code: z.string(), category: deploymentCategorySchema, severity: deploymentSeveritySchema,
93
+ direction: deploymentDirectionSchema, phase: deploymentPhaseSchema, owner: deploymentOwnerSchema,
94
+ model: z.string().optional(), field: z.string().optional(), column: z.string().optional(), from: z.unknown().optional(), to: z.unknown().optional(),
95
+ message: z.string(), action: z.string(),
96
+ dependsOn: z.array(z.string()).readonly().optional(),
97
+ });
98
+ export const deploymentStepSchema = z.object({
99
+ id: z.string(), phase: deploymentPhaseSchema, owner: deploymentOwnerSchema, title: z.string(), action: z.string(),
100
+ dependsOn: z.array(z.string()).readonly(), findingIds: z.array(z.string()).readonly(), status: z.enum(['ready', 'blocked', 'advisory']), executableByAblo: z.boolean(),
101
+ });
102
+ export const schemaDeploymentPlanSchema = z.object({
103
+ id: z.literal('ablo-schema-deployment-plan-v1'), mode: z.literal('plan'), createdAt: z.string(), fingerprint: z.string(), target: deploymentTargetSchema,
104
+ states: z.object({
105
+ source: z.object({ observedAt: z.string(), path: z.string(), hash: z.string() }),
106
+ active: z.object({ observedAt: z.string(), schemaId: z.string(), version: z.number(), hash: z.string(), pushedAt: z.string().nullable() }).nullable(),
107
+ database: z.object({ observedAt: z.string(), subject: z.string(), fingerprint: z.string(), appSchema: z.string(), ownership: z.enum(['application', 'ablo']) }).nullable(),
108
+ }),
109
+ findings: z.array(deploymentFindingSchema).readonly(), steps: z.array(deploymentStepSchema).readonly(), outcome: z.enum(['aligned', 'ready', 'blocked']),
110
+ // Submitted operations are never executed. Apply re-observes and returns a
111
+ // server-built plan; this field is retained only to validate the full plan
112
+ // envelope and obtain its fingerprint.
113
+ operations: z.object({
114
+ sourceToActive: z.array(z.custom<MigrationStep>()).readonly(),
115
+ provision: z.array(z.custom<MigrationStep>()).readonly(),
116
+ }),
117
+ rollbackTarget: z.object({ schemaId: z.string(), version: z.number(), hash: z.string(), strategy: z.literal('reactivate_artifact') }).nullable(),
118
+ recovery: z.enum(['rollback', 'forward_only']),
119
+ });
@@ -0,0 +1,13 @@
1
+ function canonical(value: unknown): string {
2
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
3
+ if (value && typeof value === 'object') return `{${Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(',')}}`;
4
+ return JSON.stringify(value);
5
+ }
6
+
7
+ /** Stable non-cryptographic identity used only to detect a changed reviewed plan. */
8
+ export function deploymentFingerprint(value: unknown): string {
9
+ const input = canonical(value);
10
+ let hash = 0xcbf29ce484222325n;
11
+ for (let index = 0; index < input.length; index++) { hash ^= BigInt(input.charCodeAt(index)); hash = BigInt.asUintN(64, hash * 0x100000001b3n); }
12
+ return `plan_${hash.toString(16).padStart(16, '0')}`;
13
+ }
@@ -0,0 +1,132 @@
1
+ import type { DeploymentApplyResult, DeploymentFinding, DeploymentObservation, DeploymentStep, SchemaDeploymentPlan } from './contracts.js';
2
+ import { deploymentFingerprint } from './fingerprint.js';
3
+ import { reconcileDeploymentManifest, reconcilePolicyIntent, reconcileSchemaToDatabase, reconcileSourceToActiveResult } from './reconcile.js';
4
+ import { sequenceDeployment } from './sequence.js';
5
+
6
+ export * from './contracts.js';
7
+ export { deploymentFingerprint } from './fingerprint.js';
8
+ export { reconcileClientToActive, reconcileDeploymentManifest, reconcilePolicyIntent, reconcileSchemaToDatabase, reconcileSourceToActive, reconcileSourceToActiveResult } from './reconcile.js';
9
+ export { sequenceDeployment } from './sequence.js';
10
+ export * from './backfill.js';
11
+ export * from './postgresCatalog.js';
12
+
13
+ function physicalEvidenceKey(finding: DeploymentFinding): string {
14
+ return JSON.stringify([
15
+ finding.code,
16
+ finding.category,
17
+ finding.severity,
18
+ finding.phase,
19
+ finding.owner,
20
+ finding.model,
21
+ finding.field,
22
+ finding.column,
23
+ finding.from,
24
+ finding.to,
25
+ finding.message,
26
+ finding.action,
27
+ ]);
28
+ }
29
+
30
+ function physicalResourceKey(finding: DeploymentFinding): string {
31
+ return JSON.stringify([finding.model, finding.column, finding.field]);
32
+ }
33
+
34
+ function planStates(observation: DeploymentObservation): SchemaDeploymentPlan['states'] {
35
+ const { schema: _sourceSchema, ...source } = observation.source;
36
+ const active = observation.active ? (({ schema: _activeSchema, ...state }) => state)(observation.active) : null;
37
+ const database = observation.database ? (({ tables: _tables, ...state }) => state)(observation.database) : null;
38
+ return { source, active, database };
39
+ }
40
+
41
+ /** The one pure reconciliation skeleton every lifecycle surface projects. */
42
+ export function buildSchemaDeploymentPlan(observation: DeploymentObservation, now = new Date().toISOString()): SchemaDeploymentPlan {
43
+ const sourceToActive = reconcileSourceToActiveResult(
44
+ observation.active?.schema ?? null,
45
+ observation.source.schema,
46
+ observation.intent?.renames,
47
+ observation.intent?.backfills,
48
+ observation.database,
49
+ );
50
+ const provision = reconcileSourceToActiveResult(null, observation.source.schema).operations;
51
+ const sourceToDatabase = reconcileSchemaToDatabase(observation.source.schema, observation.database, 'source_to_database');
52
+ const sourcePhysicalEvidence = new Set(sourceToDatabase.map(physicalEvidenceKey));
53
+ const sourcePhysicalResources = new Set(sourceToDatabase.map(physicalResourceKey));
54
+ const activeDatabaseFindings = observation.active
55
+ ? reconcileSchemaToDatabase(observation.active.schema, observation.database, 'active_to_database')
56
+ : [];
57
+ const candidateAlignedActiveFindings: DeploymentFinding[] = [];
58
+ const activeToDatabase = activeDatabaseFindings.filter((finding) => {
59
+ if (sourcePhysicalEvidence.has(physicalEvidenceKey(finding))) return false;
60
+ if (!sourcePhysicalResources.has(physicalResourceKey(finding))) {
61
+ candidateAlignedActiveFindings.push(finding);
62
+ return false;
63
+ }
64
+ return true;
65
+ });
66
+ const candidateAlignmentEvidence: DeploymentFinding[] = candidateAlignedActiveFindings.length === 0 ? [] : [{
67
+ id: 'active_to_database:candidate_alignment_verified',
68
+ code: 'candidate_alignment_verified',
69
+ category: 'observation',
70
+ severity: 'info',
71
+ direction: 'active_to_database',
72
+ phase: 'verify',
73
+ owner: observation.database?.ownership === 'ablo' ? 'ablo' : 'application_migration',
74
+ from: { activePhysicalDifferences: candidateAlignedActiveFindings.length },
75
+ to: 'source_database_alignment',
76
+ message: `PostgreSQL differs from the active artifact at ${candidateAlignedActiveFindings.length} physical contract location(s), and the candidate source already matches those locations.`,
77
+ action: 'Treat these differences as completed expand work; review the remaining source-to-active compatibility findings before activation.',
78
+ }];
79
+ const findings = [
80
+ ...reconcilePolicyIntent(observation.source.schema),
81
+ ...reconcileDeploymentManifest(observation.intent?.manifest),
82
+ ...sourceToActive.findings,
83
+ ...sourceToDatabase,
84
+ ...activeToDatabase,
85
+ ...candidateAlignmentEvidence,
86
+ ...(observation.supplementalFindings ?? []),
87
+ ];
88
+ const unique = [...new Map(findings.map((finding) => [finding.id, finding])).values()].map((finding) =>
89
+ observation.intent?.acceptDestructive && finding.category === 'destructive_contract' &&
90
+ finding.code !== 'mixed_expand_contract' && finding.code !== 'contract_approval_required' && finding.code !== 'lifecycle_dependency_unsatisfied'
91
+ ? { ...finding, severity: 'warning' as const, action: `${finding.action} Destructive intent was explicitly accepted for this reviewed plan.` }
92
+ : finding
93
+ );
94
+ const steps = sequenceDeployment(unique);
95
+ const blocking = unique.some(({ severity }) => severity === 'blocker' || severity === 'error');
96
+ const meaningful = unique.some(({ category }) => category !== 'advisory');
97
+ const states = planStates(observation);
98
+ const destructive = unique.some(({ category }) => category === 'destructive_contract');
99
+ const rollbackTarget = observation.active && !destructive ? { schemaId: observation.active.schemaId, version: observation.active.version, hash: observation.active.hash, strategy: 'reactivate_artifact' as const } : null;
100
+ const fingerprint = deploymentFingerprint({
101
+ target: observation.target,
102
+ states: {
103
+ source: { hash: states.source.hash },
104
+ active: states.active ? { schemaId: states.active.schemaId, version: states.active.version, hash: states.active.hash } : null,
105
+ database: states.database ? { subject: states.database.subject, fingerprint: states.database.fingerprint, ownership: states.database.ownership } : null,
106
+ },
107
+ intent: observation.intent ?? {}, findings: unique, steps, operations: { sourceToActive: sourceToActive.operations, provision },
108
+ });
109
+ return { id: 'ablo-schema-deployment-plan-v1', mode: 'plan', createdAt: now, fingerprint, target: observation.target, states, findings: unique, steps, operations: { sourceToActive: sourceToActive.operations, provision }, outcome: blocking ? 'blocked' : meaningful ? 'ready' : 'aligned', rollbackTarget, recovery: rollbackTarget ? 'rollback' : 'forward_only' };
110
+ }
111
+
112
+ export interface SchemaDeploymentLifecycleEffects {
113
+ readonly observe: () => Promise<DeploymentObservation>;
114
+ readonly approve?: (plan: SchemaDeploymentPlan) => Promise<boolean>;
115
+ readonly apply?: (step: DeploymentStep, plan: SchemaDeploymentPlan) => Promise<void>;
116
+ readonly record?: (result: Omit<DeploymentApplyResult, 'recorded'>) => Promise<void>;
117
+ }
118
+
119
+ /** One observe → reconcile → sequence → approve → apply → verify → record path. */
120
+ export async function runSchemaDeploymentLifecycle(effects: SchemaDeploymentLifecycleEffects, mode: 'plan' | 'apply' = 'plan'): Promise<SchemaDeploymentPlan | DeploymentApplyResult> {
121
+ const plan = buildSchemaDeploymentPlan(await effects.observe());
122
+ if (mode === 'plan') return plan;
123
+ if (plan.outcome === 'blocked') throw new Error(`schema deployment plan ${plan.fingerprint} is blocked`);
124
+ if (!effects.apply) throw new Error('schema deployment apply effect is not configured');
125
+ if (effects.approve && !(await effects.approve(plan))) throw new Error('schema deployment was not approved');
126
+ const appliedStepIds: string[] = [];
127
+ for (const step of plan.steps) if (step.executableByAblo && step.status === 'ready') { await effects.apply(step, plan); appliedStepIds.push(step.id); }
128
+ const verification = buildSchemaDeploymentPlan(await effects.observe());
129
+ const unrecorded = { plan, appliedStepIds, verification };
130
+ await effects.record?.(unrecorded);
131
+ return { ...unrecorded, recorded: effects.record !== undefined };
132
+ }
@@ -0,0 +1,131 @@
1
+ import type { DatabaseTableSnapshot } from './contracts.js';
2
+
3
+ export interface PostgresColumnCatalogRow {
4
+ tableName: string;
5
+ columnName: string;
6
+ dataType: string;
7
+ nullable: boolean;
8
+ defaultValue: string | null;
9
+ primary: boolean;
10
+ uniqueColumn: boolean;
11
+ rowLevelSecurity: boolean;
12
+ forceRowLevelSecurity: boolean;
13
+ replicaIdentity: string;
14
+ publicationMember: boolean;
15
+ }
16
+
17
+ export interface PostgresIndexCatalogRow {
18
+ tableName: string;
19
+ indexName: string;
20
+ columns: string[];
21
+ uniqueIndex: boolean;
22
+ valid: boolean;
23
+ ready: boolean;
24
+ predicate: string | null;
25
+ }
26
+
27
+ export interface PostgresForeignKeyCatalogRow {
28
+ tableName: string;
29
+ constraintName: string;
30
+ columns: string[];
31
+ referencedSchema: string;
32
+ referencedTable: string;
33
+ referencedColumns: string[];
34
+ validated: boolean;
35
+ }
36
+
37
+ export const POSTGRES_COLUMN_CATALOG_SQL = `
38
+ SELECT c.relname AS "tableName", a.attname AS "columnName",
39
+ format_type(a.atttypid, a.atttypmod) AS "dataType", NOT a.attnotnull AS nullable,
40
+ pg_get_expr(d.adbin, d.adrelid) AS "defaultValue",
41
+ EXISTS (SELECT 1 FROM pg_constraint k WHERE k.conrelid = c.oid AND k.contype = 'p' AND cardinality(k.conkey) = 1 AND a.attnum = ANY(k.conkey)) AS primary,
42
+ EXISTS (SELECT 1 FROM pg_constraint k WHERE k.conrelid = c.oid AND k.contype IN ('p','u') AND cardinality(k.conkey) = 1 AND a.attnum = ANY(k.conkey)) AS "uniqueColumn",
43
+ c.relrowsecurity AS "rowLevelSecurity", c.relforcerowsecurity AS "forceRowLevelSecurity",
44
+ c.relreplident::text AS "replicaIdentity",
45
+ EXISTS (SELECT 1 FROM pg_publication_tables p WHERE p.schemaname = n.nspname AND p.tablename = c.relname) AS "publicationMember"
46
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
47
+ JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
48
+ LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = a.attnum
49
+ WHERE n.nspname = $1 AND c.relkind IN ('r','p') ORDER BY c.relname, a.attnum
50
+ `;
51
+
52
+ export const POSTGRES_INDEX_CATALOG_SQL = `
53
+ SELECT t.relname AS "tableName", i.relname AS "indexName",
54
+ ARRAY(SELECT a.attname FROM unnest(ix.indkey) WITH ORDINALITY keys(attnum, ord) JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = keys.attnum ORDER BY keys.ord) AS columns,
55
+ ix.indisunique AS "uniqueIndex", ix.indisvalid AS valid, ix.indisready AS ready,
56
+ pg_get_expr(ix.indpred, ix.indrelid) AS predicate
57
+ FROM pg_index ix JOIN pg_class t ON t.oid = ix.indrelid JOIN pg_class i ON i.oid = ix.indexrelid
58
+ JOIN pg_namespace n ON n.oid = t.relnamespace WHERE n.nspname = $1 ORDER BY t.relname, i.relname
59
+ `;
60
+
61
+ export const POSTGRES_FOREIGN_KEY_CATALOG_SQL = `
62
+ SELECT t.relname AS "tableName", c.conname AS "constraintName",
63
+ ARRAY(SELECT a.attname FROM unnest(c.conkey) WITH ORDINALITY keys(attnum, ord) JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = keys.attnum ORDER BY keys.ord) AS columns,
64
+ rn.nspname AS "referencedSchema", rt.relname AS "referencedTable",
65
+ ARRAY(SELECT a.attname FROM unnest(c.confkey) WITH ORDINALITY keys(attnum, ord) JOIN pg_attribute a ON a.attrelid = c.confrelid AND a.attnum = keys.attnum ORDER BY keys.ord) AS "referencedColumns",
66
+ c.convalidated AS validated
67
+ FROM pg_constraint c JOIN pg_class t ON t.oid = c.conrelid JOIN pg_namespace n ON n.oid = t.relnamespace
68
+ JOIN pg_class rt ON rt.oid = c.confrelid JOIN pg_namespace rn ON rn.oid = rt.relnamespace
69
+ WHERE c.contype = 'f' AND n.nspname = $1 ORDER BY t.relname, c.conname
70
+ `;
71
+
72
+ export function quotePostgresIdentifier(value: string): string {
73
+ return `"${value.replace(/"/g, '""')}"`;
74
+ }
75
+
76
+ export function postgresNullCountSql(appSchema: string, table: string, column: string): string {
77
+ const qualified = `${quotePostgresIdentifier(appSchema)}.${quotePostgresIdentifier(table)}`;
78
+ return `SELECT count(*)::int AS n FROM (SELECT 1 FROM ${qualified} WHERE ${quotePostgresIdentifier(column)} IS NULL LIMIT 501) unstamped`;
79
+ }
80
+
81
+ export function foldPostgresCatalog(
82
+ appSchema: string,
83
+ columns: readonly PostgresColumnCatalogRow[],
84
+ indexes: readonly PostgresIndexCatalogRow[],
85
+ foreignKeys: readonly PostgresForeignKeyCatalogRow[],
86
+ ): Record<string, DatabaseTableSnapshot> {
87
+ const tables: Record<string, DatabaseTableSnapshot> = {};
88
+ for (const row of columns) {
89
+ const table = tables[row.tableName] ?? {
90
+ schema: appSchema,
91
+ name: row.tableName,
92
+ columns: {},
93
+ indexes: [],
94
+ foreignKeys: [],
95
+ rowLevelSecurity: row.rowLevelSecurity,
96
+ forceRowLevelSecurity: row.forceRowLevelSecurity,
97
+ replicaIdentity: row.replicaIdentity,
98
+ publicationMember: row.publicationMember,
99
+ };
100
+ table.columns[row.columnName] = {
101
+ name: row.columnName,
102
+ dataType: row.dataType,
103
+ nullable: row.nullable,
104
+ default: row.defaultValue,
105
+ primary: row.primary,
106
+ unique: row.uniqueColumn,
107
+ };
108
+ tables[row.tableName] = table;
109
+ }
110
+ for (const row of indexes) {
111
+ tables[row.tableName]?.indexes?.push({
112
+ name: row.indexName,
113
+ columns: row.columns,
114
+ unique: row.uniqueIndex,
115
+ valid: row.valid,
116
+ ready: row.ready,
117
+ predicate: row.predicate,
118
+ });
119
+ }
120
+ for (const row of foreignKeys) {
121
+ tables[row.tableName]?.foreignKeys?.push({
122
+ name: row.constraintName,
123
+ columns: row.columns,
124
+ referencedSchema: row.referencedSchema,
125
+ referencedTable: row.referencedTable,
126
+ referencedColumns: row.referencedColumns,
127
+ validated: row.validated,
128
+ });
129
+ }
130
+ return tables;
131
+ }