gencow 0.1.299 → 0.2.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 (151) hide show
  1. package/bin/gencow.mjs +0 -6
  2. package/core/package.json +1 -1
  3. package/docs/packaging.md +14 -4
  4. package/lib/cli-artifact-guard.mjs +53 -3
  5. package/lib/cli-dev-runtime.mjs +1 -0
  6. package/lib/cli-project-runtime.mjs +26 -14
  7. package/lib/codegen-command.mjs +16 -0
  8. package/lib/coding-guardrails.mjs +2 -0
  9. package/lib/dashboard-artifact.mjs +65 -0
  10. package/lib/dashboard-assets.mjs +20 -0
  11. package/lib/db-command.mjs +121 -80
  12. package/lib/db-migration-command-steps.mjs +19 -16
  13. package/lib/db-push-command.mjs +1 -1
  14. package/lib/deploy-codegen-preflight.mjs +1 -0
  15. package/lib/dev-cloud-command.mjs +1 -1
  16. package/lib/dev-local-command.mjs +19 -56
  17. package/lib/document-local-converter.mjs +11 -0
  18. package/lib/local-dashboard-plan.mjs +60 -0
  19. package/lib/local-database-commands.mjs +127 -0
  20. package/lib/local-development-migrations.mjs +157 -0
  21. package/lib/local-drizzle-database.config.mjs +10 -0
  22. package/lib/local-runtime-features.mjs +12 -0
  23. package/lib/rag-selection.mjs +7 -0
  24. package/lib/runtime-local-worker.mjs +116 -0
  25. package/lib/runtime-mode.mjs +3 -0
  26. package/lib/standalone-codegen-adapter.mjs +91 -0
  27. package/lib/ts-codegen-import-extension.mjs +228 -19
  28. package/package.json +15 -8
  29. package/runtime/config.mjs +218 -2
  30. package/runtime/engine/chunk-2HA4CUMS.mjs +90 -0
  31. package/runtime/engine/chunk-2JLO3KMM.mjs +305 -0
  32. package/runtime/engine/chunk-2SR2M7SR.mjs +1045 -0
  33. package/runtime/engine/chunk-3D7MHEUC.mjs +253 -0
  34. package/runtime/engine/chunk-3R7COBWG.mjs +309 -0
  35. package/runtime/engine/chunk-3ZKA54UW.mjs +1560 -0
  36. package/runtime/engine/chunk-45I4YR2J.mjs +9 -0
  37. package/runtime/engine/chunk-4MLRXO7F.mjs +74 -0
  38. package/runtime/engine/chunk-5575APCJ.mjs +215 -0
  39. package/runtime/engine/chunk-5GUJZQF3.mjs +114 -0
  40. package/runtime/engine/chunk-5MXY3T75.mjs +428 -0
  41. package/runtime/engine/chunk-5TACQ2US.mjs +44 -0
  42. package/runtime/engine/chunk-66G4YEDT.mjs +3104 -0
  43. package/runtime/engine/chunk-67YO53WW.mjs +1426 -0
  44. package/runtime/engine/chunk-6GQRM7XY.mjs +87 -0
  45. package/runtime/engine/chunk-6JO72SPP.mjs +68 -0
  46. package/runtime/engine/chunk-6W653LXI.mjs +13 -0
  47. package/runtime/engine/chunk-7ITSMI3S.mjs +69 -0
  48. package/runtime/engine/chunk-7KUJ2H2S.mjs +128 -0
  49. package/runtime/engine/chunk-A5BMQ5IC.mjs +45 -0
  50. package/runtime/engine/chunk-ADF3UR6L.mjs +428 -0
  51. package/runtime/engine/chunk-AEBW7XZJ.mjs +4510 -0
  52. package/runtime/engine/chunk-AGPQ5XIV.mjs +156 -0
  53. package/runtime/engine/chunk-CPU4OZSX.mjs +753 -0
  54. package/runtime/engine/chunk-CSWPPWBL.mjs +50 -0
  55. package/runtime/engine/chunk-DPWXSMWO.mjs +53 -0
  56. package/runtime/engine/chunk-EAIELFKU.mjs +151 -0
  57. package/runtime/engine/chunk-EDU5CBKT.mjs +10 -0
  58. package/runtime/engine/chunk-EQCTAET7.mjs +173 -0
  59. package/runtime/engine/chunk-EQCXDF2Z.mjs +70 -0
  60. package/runtime/engine/chunk-F3G4UGV4.mjs +330 -0
  61. package/runtime/engine/chunk-F62NUNOO.mjs +26 -0
  62. package/runtime/engine/chunk-FKPNIFRP.mjs +2492 -0
  63. package/runtime/engine/chunk-FM23RGVI.mjs +81 -0
  64. package/runtime/engine/chunk-FW5AK4YP.mjs +1041 -0
  65. package/runtime/engine/chunk-GDWYAGWV.mjs +23 -0
  66. package/runtime/engine/chunk-GO5PZUYW.mjs +53 -0
  67. package/runtime/engine/chunk-GOLP7OSG.mjs +340 -0
  68. package/runtime/engine/chunk-GSLM44EF.mjs +242 -0
  69. package/runtime/engine/chunk-GYAJ7OX2.mjs +125 -0
  70. package/runtime/engine/chunk-I3GWR43K.mjs +14 -0
  71. package/runtime/engine/chunk-IFMOTJNU.mjs +106 -0
  72. package/runtime/engine/chunk-IKQKBE2G.mjs +128 -0
  73. package/runtime/engine/chunk-ITH2NEKM.mjs +282 -0
  74. package/runtime/engine/chunk-J6SDRCG4.mjs +96 -0
  75. package/runtime/engine/chunk-JODRNM3S.mjs +29596 -0
  76. package/runtime/engine/chunk-JUDKX53X.mjs +137 -0
  77. package/runtime/engine/chunk-K2YZVPJ4.mjs +827 -0
  78. package/runtime/engine/chunk-KEZJUXEE.mjs +151 -0
  79. package/runtime/engine/chunk-KVLTJFCH.mjs +234 -0
  80. package/runtime/engine/chunk-KX2PRQPS.mjs +126 -0
  81. package/runtime/engine/chunk-LEW5ZMLR.mjs +76 -0
  82. package/runtime/engine/chunk-LINVSJEM.mjs +175 -0
  83. package/runtime/engine/chunk-M7K2ICSM.mjs +11 -0
  84. package/runtime/engine/chunk-MZXDXSDC.mjs +292 -0
  85. package/runtime/engine/chunk-N2TA2IK2.mjs +678 -0
  86. package/runtime/engine/chunk-N4LTCKJP.mjs +695 -0
  87. package/runtime/engine/chunk-N6GCLOUX.mjs +13 -0
  88. package/runtime/engine/chunk-NAG2OXS5.mjs +37 -0
  89. package/runtime/engine/chunk-NNZ2QJUG.mjs +381 -0
  90. package/runtime/engine/chunk-NZPPLDNW.mjs +15 -0
  91. package/runtime/engine/chunk-ODWM57W6.mjs +138 -0
  92. package/runtime/engine/chunk-P5IIXAIE.mjs +23 -0
  93. package/runtime/engine/chunk-PBOXB2BV.mjs +6 -0
  94. package/runtime/engine/chunk-PMOJLN2P.mjs +8 -0
  95. package/runtime/engine/chunk-PZFMKFHO.mjs +180 -0
  96. package/runtime/engine/chunk-QL2TQX2N.mjs +114 -0
  97. package/runtime/engine/chunk-RITT2RSJ.mjs +258 -0
  98. package/runtime/engine/chunk-RODBVJ5M.mjs +135 -0
  99. package/runtime/engine/chunk-RW65MPVY.mjs +261 -0
  100. package/runtime/engine/chunk-S67UYPB6.mjs +25 -0
  101. package/runtime/engine/chunk-SVJCOUI3.mjs +47 -0
  102. package/runtime/engine/chunk-TCN3ZASV.mjs +957 -0
  103. package/runtime/engine/chunk-U2NRG6KC.mjs +32 -0
  104. package/runtime/engine/chunk-UM3F7HUV.mjs +432 -0
  105. package/runtime/engine/chunk-VWU7JJ3P.mjs +146 -0
  106. package/runtime/engine/chunk-WDTKPPMU.mjs +310 -0
  107. package/runtime/engine/chunk-WJOO4XTB.mjs +31 -0
  108. package/runtime/engine/chunk-XNFVL2OY.mjs +63 -0
  109. package/runtime/engine/chunk-XPWJXP2J.mjs +58 -0
  110. package/runtime/engine/chunk-Y3HSBJ3I.mjs +1132 -0
  111. package/runtime/engine/chunk-YMH4RYSX.mjs +317 -0
  112. package/runtime/engine/chunk-YNOMPSGS.mjs +8 -0
  113. package/runtime/engine/chunk-YRBAYTEZ.mjs +251 -0
  114. package/runtime/engine/chunk-YRHM272W.mjs +528 -0
  115. package/runtime/engine/chunk-ZQUZAGIQ.mjs +149 -0
  116. package/runtime/engine/chunk-ZXMM7QFP.mjs +176 -0
  117. package/runtime/engine/chunk-ZZJSIPV2.mjs +262 -0
  118. package/runtime/engine/composition.mjs +325 -0
  119. package/runtime/engine/document-local.mjs +504 -0
  120. package/runtime/engine/graph.json +4134 -0
  121. package/runtime/engine/index.mjs +265 -0
  122. package/runtime/engine/local-postgres-support.mjs +69 -0
  123. package/runtime/engine/local.mjs +3275 -0
  124. package/runtime/engine/pglite-directory-lock.mjs +8 -0
  125. package/runtime/engine/rag.mjs +11 -0
  126. package/runtime/engine/search.mjs +18 -0
  127. package/runtime/framework-migrations/foundation-bootstrap/rag.sql +115 -0
  128. package/runtime/framework-migrations/foundation-bootstrap/workflow.sql +194 -0
  129. package/runtime/framework-migrations/journal-bootstrap/migration.sql +26 -0
  130. package/runtime/framework-migrations/manifest.json +56 -0
  131. package/runtime/framework-migrations/rag/20261006111509_mushy_warhawk/migration.sql +121 -0
  132. package/runtime/framework-migrations/rag/20261013234621_rag_v2_lifecycle_markers/migration.sql +6 -0
  133. package/runtime/framework-migrations/workflow/20261006111508_perpetual_star_brand/migration.sql +31 -0
  134. package/runtime/runtime-metadata.json +27 -0
  135. package/runtime/tooling.mjs +10399 -8951
  136. package/scripts/bundle-runtime-config.mjs +23 -0
  137. package/scripts/bundle-runtime.mjs +100 -0
  138. package/scripts/bundle-runtime.test.mjs +33 -0
  139. package/scripts/bundle-shared.mjs +3 -0
  140. package/scripts/copy-dashboard.mjs +16 -0
  141. package/scripts/pre-publish-check.mjs +23 -11
  142. package/templateFeature/ai/ai-facade.ts +38 -15
  143. package/templateFeature/ai/manifest.json +1 -0
  144. package/templateFeature/sso/sso-auth-callback.tsx +37 -5
  145. package/templateFeature/tools/manifest.json +5 -2
  146. package/templateFeature/tools/tools.ts +3 -3
  147. package/runtime/server.mjs +0 -14389
  148. package/scripts/bundle-server.mjs +0 -223
  149. package/server/config.js +0 -1
  150. package/server/index.js +0 -1
  151. package/server/package.json +0 -6
@@ -0,0 +1,827 @@
1
+ import {
2
+ normalizeFrameworkSqlExpression
3
+ } from "./chunk-GSLM44EF.mjs";
4
+ import {
5
+ workflowTerminalGuardSchema
6
+ } from "./chunk-ZXMM7QFP.mjs";
7
+ import {
8
+ assertLocalPostgresSecurityPolicy
9
+ } from "./chunk-5MXY3T75.mjs";
10
+ import {
11
+ assertFrameworkSchemaReady,
12
+ createFrameworkSchemaReady,
13
+ revokeFrameworkSchemaReady
14
+ } from "./chunk-U2NRG6KC.mjs";
15
+ import {
16
+ inspectRuntimeDatabaseSchemaPlan
17
+ } from "./chunk-3D7MHEUC.mjs";
18
+ import {
19
+ runtimeDatabaseSetupError,
20
+ runtimeDatabaseSetupInterrupted
21
+ } from "./chunk-SVJCOUI3.mjs";
22
+
23
+ // ../runtime/dist/framework-schema/coordinator.js
24
+ import { randomUUID } from "node:crypto";
25
+
26
+ // ../runtime/dist/framework-schema/catalog-admission.js
27
+ function key(schema, table, name) {
28
+ return JSON.stringify([schema, table, name]);
29
+ }
30
+ function byName(values) {
31
+ return new Map(values.map((value) => [key(value.schema, value.table, value.name), value]));
32
+ }
33
+ function relation(table) {
34
+ return { schema: table.schema, table: table.name };
35
+ }
36
+ function normalize(value, table) {
37
+ return value === null || value === void 0 ? null : normalizeFrameworkSqlExpression(value, relation(table));
38
+ }
39
+ function sameDeparsedExpression(expected, actual, table, knownVariants = []) {
40
+ const context = relation(table);
41
+ const expectedNormalized = normalizeFrameworkSqlExpression(expected, context);
42
+ const actualNormalized = normalizeFrameworkSqlExpression(actual, context);
43
+ return expectedNormalized === actualNormalized || knownVariants.some((variant) => expectedNormalized === normalizeFrameworkSqlExpression(variant.expected, context) && actualNormalized === normalizeFrameworkSqlExpression(variant.actual, context));
44
+ }
45
+ var ragIndexExpressionVariants = Object.freeze([
46
+ {
47
+ expected: "to_tsvector('simple', lower(normalize(regexp_replace(coalesce(lexical_text::text, ''), '[[:space:]]+', ' ', 'g'), nfc)))",
48
+ actual: "to_tsvector('simple'::regconfig, lower(normalize(regexp_replace(coalesce(lexical_text, ''::text), '[[:space:]]+'::text, ' '::text, 'g'::text), nfc)))"
49
+ },
50
+ {
51
+ expected: "to_tsvector('simple', lower(normalize(regexp_replace(coalesce(chunk_text::text, ''), '[[:space:]]+', ' ', 'g'), nfc)))",
52
+ actual: "to_tsvector('simple'::regconfig, lower(normalize(regexp_replace(coalesce(chunk_text, ''::text), '[[:space:]]+'::text, ' '::text, 'g'::text), nfc)))"
53
+ },
54
+ {
55
+ expected: "lower(normalize(regexp_replace(coalesce(lexical_text::text, ''), '[[:space:]]+', ' ', 'g'), nfc))",
56
+ actual: "lower(normalize(regexp_replace(coalesce(lexical_text, ''::text), '[[:space:]]+'::text, ' '::text, 'g'::text), nfc))"
57
+ },
58
+ {
59
+ expected: "lower(normalize(regexp_replace(coalesce(chunk_text::text, ''), '[[:space:]]+', ' ', 'g'), nfc))",
60
+ actual: "lower(normalize(regexp_replace(coalesce(chunk_text, ''::text), '[[:space:]]+'::text, ' '::text, 'g'::text), nfc))"
61
+ }
62
+ ]);
63
+ var frameworkJournalCheckExpressionVariants = Object.freeze([
64
+ {
65
+ schema: "drizzle",
66
+ table: "__gencow_framework_migrations",
67
+ name: "__gencow_framework_migrations_component_id_check",
68
+ expected: "length(component_id) between 1 and 63",
69
+ actual: "((length(component_id) >= 1) AND (length(component_id) <= 63))"
70
+ },
71
+ {
72
+ schema: "drizzle",
73
+ table: "__gencow_framework_migrations",
74
+ name: "__gencow_framework_migrations_migration_id_check",
75
+ expected: "length(migration_id) between 1 and 128",
76
+ actual: "((length(migration_id) >= 1) AND (length(migration_id) <= 128))"
77
+ },
78
+ {
79
+ schema: "drizzle",
80
+ table: "__gencow_framework_migrations",
81
+ name: "__gencow_framework_migrations_order_check",
82
+ expected: "migration_order > 0",
83
+ actual: "(migration_order > 0)"
84
+ },
85
+ {
86
+ schema: "drizzle",
87
+ table: "__gencow_framework_migrations",
88
+ name: "__gencow_framework_migrations_hash_check",
89
+ expected: "hash ~ '^[0-9a-f]{64}$'",
90
+ actual: "(hash ~ '^[0-9a-f]{64}$'::text)"
91
+ },
92
+ {
93
+ schema: "drizzle",
94
+ table: "__gencow_framework_migrations",
95
+ name: "__gencow_framework_migrations_created_at_check",
96
+ expected: "created_at > 0",
97
+ actual: "(created_at > 0)"
98
+ },
99
+ {
100
+ schema: "drizzle",
101
+ table: "__gencow_framework_migrations",
102
+ name: "__gencow_framework_migrations_applied_via_check",
103
+ expected: "applied_via in ('migration', 'baseline')",
104
+ actual: "(applied_via = ANY (ARRAY['migration'::text, 'baseline'::text]))"
105
+ }
106
+ ]);
107
+ function indexExpressionMatches(expected, actual, table) {
108
+ return sameDeparsedExpression(expected, actual, table, table.schema === "public" && table.name === "rag_chunks" ? ragIndexExpressionVariants : []);
109
+ }
110
+ function indexPredicateMatches(expected, actual, table) {
111
+ if (expected.predicate === null || actual === null)
112
+ return normalize(expected.predicate, table) === normalize(actual, table);
113
+ const variants = table.schema === "public" && table.name === "_gencow_workflow_runs_v2" && expected.name === "idx__gencow_workflow_runs_v2_lease" ? [
114
+ {
115
+ expected: "status = 'running' and completed_at is null",
116
+ actual: "status = 'running'::text and completed_at is null"
117
+ }
118
+ ] : table.schema === "public" && table.name === "_gencow_workflow_outbox_v2" && expected.name === "idx__gencow_workflow_outbox_v2_due_pending" ? [
119
+ {
120
+ expected: "status in ('pending', 'sending')",
121
+ actual: "status = any (array['pending'::text, 'sending'::text])"
122
+ }
123
+ ] : table.schema === "public" && table.name === "_gencow_workflow_timers_v2" && expected.name === "idx__gencow_workflow_timers_v2_due_pending" ? [
124
+ {
125
+ expected: "status = 'pending'",
126
+ actual: "status = 'pending'::text"
127
+ }
128
+ ] : [];
129
+ return sameDeparsedExpression(expected.predicate, actual, table, variants);
130
+ }
131
+ function columnDefaultMatches(table, column, actual) {
132
+ if (column.defaultValue === null || actual === null || actual === void 0)
133
+ return normalize(column.defaultValue, table) === normalize(actual, table);
134
+ const variants = table.schema === "public" && table.name === "_gencow_workflow_events" && column.name === "id" ? [{ expected: "gen_random_uuid()::text", actual: "(gen_random_uuid())::text" }] : [];
135
+ return sameDeparsedExpression(column.defaultValue, actual, table, variants);
136
+ }
137
+ function sameStrings(left, right) {
138
+ return left.length === right.length && left.every((value, index) => value === right[index]);
139
+ }
140
+ function constraintMatches(expected, actual, table) {
141
+ const knownCheckVariant = expected.kind === "check" ? frameworkJournalCheckExpressionVariants.find((variant) => variant.schema === table.schema && variant.table === table.name && variant.name === expected.name) : void 0;
142
+ const expressionMatches = expected.kind === "check" ? expected.expression !== void 0 && actual.expression !== null && sameDeparsedExpression(expected.expression, actual.expression, table, knownCheckVariant ? [knownCheckVariant] : []) : normalize(expected.expression ?? null, table) === normalize(actual.expression, table);
143
+ return expected.kind === actual.kind && (expected.kind === "check" || sameStrings(expected.columns, actual.columns)) && actual.validated && !actual.deferrable && (expected.nullsNotDistinct ?? false) === actual.nullsNotDistinct && expressionMatches && (expected.kind === "foreign" ? Boolean(expected.target && actual.target && expected.target.schema === actual.target.schema && expected.target.table === actual.target.table && sameStrings(expected.target.columns, actual.target.columns) && expected.target.deleteAction === actual.target.deleteAction && expected.target.updateAction === actual.target.updateAction) : actual.target === void 0);
144
+ }
145
+ function indexMatches(expected, actual, table) {
146
+ if (expected.method !== actual.method || expected.unique !== actual.unique || !indexPredicateMatches(expected, actual.predicate, table) || !actual.valid || !actual.ready || actual.includes.length !== 0 || expected.keys.length !== actual.keys.length || actual.options.length !== actual.keys.length)
147
+ return false;
148
+ for (let index = 0; index < expected.keys.length; index++) {
149
+ const key2 = expected.keys[index];
150
+ const options = actual.options[index];
151
+ const expectedOptions = (key2.order === "desc" ? 1 : 0) | (key2.nulls === "first" ? 2 : 0);
152
+ const operator = actual.operatorClasses?.[index];
153
+ if (!indexExpressionMatches(key2.expression, actual.keys[index], table) || !Number.isSafeInteger(options) || options !== expectedOptions || (key2.defaultOperatorClass ? operator?.isDefault !== true : !operator || operator.isDefault || operator.name !== key2.operatorClass?.name || key2.operatorClass.schema !== void 0 && operator.schema !== key2.operatorClass.schema))
154
+ return false;
155
+ }
156
+ return true;
157
+ }
158
+ function constraintBackedIndexMatches(table, actual, snapshot) {
159
+ if (!actual.constraintOwned || !actual.unique || actual.predicate !== null || actual.includes.length)
160
+ return false;
161
+ const expected = table.constraints.find((constraint) => constraint.name === actual.name && (constraint.kind === "primary" || constraint.kind === "unique"));
162
+ const observed = snapshot.constraints.find((constraint) => constraint.schema === table.schema && constraint.table === table.name && constraint.name === actual.name && (constraint.kind === "primary" || constraint.kind === "unique"));
163
+ return Boolean(expected && observed && constraintMatches(expected, observed, table) && actual.keys.length === expected.columns.length && expected.columns.every((column, position) => normalizeFrameworkSqlExpression(actual.keys[position], relation(table)) === normalizeFrameworkSqlExpression(column, relation(table)) && (actual.options[position] ?? 0) === 0));
164
+ }
165
+ function compareFrameworkProjection(snapshot, projection, options = {}) {
166
+ const mismatches = [];
167
+ const relations = new Map(snapshot.relations.map((relation2) => [key(relation2.schema, relation2.name, relation2.name), relation2]));
168
+ const allowedTriggers = new Set(options.allowedTriggers ?? []);
169
+ for (const table of projection) {
170
+ const relation2 = relations.get(key(table.schema, table.name, table.name));
171
+ if (!relation2 || relation2.kind !== "r" || relation2.rowSecurity !== table.rowSecurity || relation2.forceRowSecurity)
172
+ mismatches.push(`relation:${table.schema}.${table.name}`);
173
+ const actualColumns = snapshot.columns.filter((column) => column.schema === table.schema && column.table === table.name);
174
+ const columns = new Map(actualColumns.map((column) => [column.name, column]));
175
+ for (const expected of table.columns) {
176
+ const actual = columns.get(expected.name);
177
+ const type = actual?.formattedType ?? actual?.type;
178
+ const expectedType = expected.type.toLowerCase();
179
+ const vector = /^public\.vector\(([1-9][0-9]*)\)$/u.exec(expectedType);
180
+ const vectorDimension = vector ? Number(vector[1]) : void 0;
181
+ const typeMatches = vector ? Number.isSafeInteger(vectorDimension) && actual?.type.toLowerCase() === "vector" && actual.typeSchema === "public" && actual.typeModifier === vectorDimension && [`vector(${vectorDimension})`, `public.vector(${vectorDimension})`].includes(actual.formattedType?.toLowerCase() ?? "") : type?.toLowerCase() === expectedType;
182
+ const defaultMatches = expected.defaultValue === "sequence" ? snapshot.sequences.filter((sequence) => sequence.schema === table.schema && sequence.table === table.name && sequence.column === expected.name && sequence.defaultLinked).length === 1 : columnDefaultMatches(table, expected, actual?.defaultValue);
183
+ if (!actual || !typeMatches || expected.nullable !== actual.nullable || !defaultMatches || expected.identity !== actual.identity || expected.generated !== actual.generated)
184
+ mismatches.push(`column:${table.schema}.${table.name}.${expected.name}`);
185
+ }
186
+ for (const actual of actualColumns) {
187
+ if (table.columns.some((column) => column.name === actual.name))
188
+ continue;
189
+ if (!actual.nullable && actual.defaultValue === null && !actual.identity && !actual.generated)
190
+ mismatches.push(`extra-required-column:${table.schema}.${table.name}.${actual.name}`);
191
+ }
192
+ const allConstraints = snapshot.constraints.filter((constraint) => constraint.schema === table.schema && constraint.table === table.name);
193
+ const actualConstraints = allConstraints.filter((constraint) => constraint.kind !== "trigger" || !allowedTriggers.has(`${table.schema}.${table.name}.${constraint.name}`));
194
+ const constraints = byName(actualConstraints);
195
+ for (const expected of table.constraints) {
196
+ const actual = constraints.get(key(table.schema, table.name, expected.name));
197
+ if (!actual || !constraintMatches(expected, actual, table))
198
+ mismatches.push(`constraint:${table.schema}.${table.name}.${expected.name}`);
199
+ }
200
+ for (const actual of actualConstraints) {
201
+ if (!table.constraints.some((constraint) => constraint.name === actual.name))
202
+ mismatches.push(`extra-constraint:${table.schema}.${table.name}.${actual.name}`);
203
+ }
204
+ const actualIndexes = snapshot.indexes.filter((index) => index.schema === table.schema && index.table === table.name);
205
+ const indexes = byName(actualIndexes);
206
+ for (const expected of table.indexes) {
207
+ const actual = indexes.get(key(table.schema, table.name, expected.name));
208
+ if (!actual || !indexMatches(expected, actual, table))
209
+ mismatches.push(`index:${table.schema}.${table.name}.${expected.name}`);
210
+ }
211
+ for (const actual of actualIndexes) {
212
+ if (constraintBackedIndexMatches(table, actual, snapshot))
213
+ continue;
214
+ if (table.indexes.some((index) => index.name === actual.name))
215
+ continue;
216
+ if (actual.unique || !actual.valid || !actual.ready)
217
+ mismatches.push(`extra-index:${table.schema}.${table.name}.${actual.name}`);
218
+ }
219
+ const behavior = snapshot.relationBehavior?.find((candidate) => candidate.schema === table.schema && candidate.name === table.name);
220
+ if (!behavior || behavior.inherited || behavior.rules.length > 0 || behavior.policies.length > 0 || behavior.nonInternalTriggers.some((trigger) => !allowedTriggers.has(`${table.schema}.${table.name}.${trigger}`)))
221
+ mismatches.push(`behavior:${table.schema}.${table.name}`);
222
+ }
223
+ return Object.freeze([...new Set(mismatches)]);
224
+ }
225
+ function missingFrameworkAccess(snapshot, requirements) {
226
+ const missing = [];
227
+ requirements.forEach((requirement, requirementIndex) => {
228
+ const names = requirement.kind === "schema" ? [requirement.schema] : requirement.kind === "table" ? [requirement.name] : snapshot.sequences.filter((sequence) => sequence.schema === requirement.schema && sequence.table === requirement.table && sequence.column === requirement.column && sequence.defaultLinked).map((sequence) => sequence.name);
229
+ if (names.length !== 1 && requirement.kind === "owned-sequence") {
230
+ for (const path of requirement.paths)
231
+ for (const privilege of requirement.privileges)
232
+ missing.push({ requirementIndex, path, privilege });
233
+ return;
234
+ }
235
+ for (const path of requirement.paths) {
236
+ const actual = snapshot.access.find((entry) => entry.path === path && entry.schema === requirement.schema && entry.name === names[0] && entry.kind === (requirement.kind === "owned-sequence" ? "sequence" : requirement.kind));
237
+ for (const privilege of requirement.privileges)
238
+ if (!actual?.privileges.includes(privilege))
239
+ missing.push({ requirementIndex, path, privilege });
240
+ }
241
+ });
242
+ return Object.freeze(missing);
243
+ }
244
+ function frameworkProjectionAbsent(snapshot, projection, adjuncts = []) {
245
+ const relationExists = (schema, name) => snapshot.relations.some((relation2) => relation2.schema === schema && relation2.name === name);
246
+ const relationBehaviors = snapshot.relationBehavior ?? [];
247
+ for (const table of projection) {
248
+ if (relationExists(table.schema, table.name))
249
+ return false;
250
+ for (const index of table.indexes)
251
+ if (relationExists(table.schema, index.name) || snapshot.indexes.some((actual) => actual.schema === table.schema && actual.name === index.name))
252
+ return false;
253
+ for (const constraint of table.constraints)
254
+ if (relationExists(table.schema, constraint.name) || snapshot.indexes.some((actual) => actual.schema === table.schema && actual.name === constraint.name))
255
+ return false;
256
+ for (const column of table.columns) {
257
+ if (!column.ownedSequence)
258
+ continue;
259
+ if (snapshot.sequences.some((sequence) => sequence.schema === table.schema && sequence.table === table.name && sequence.column === column.name))
260
+ return false;
261
+ const sequenceName = `${table.name}_${column.name}_seq`.slice(0, 63);
262
+ if (relationExists(table.schema, sequenceName))
263
+ return false;
264
+ }
265
+ if (relationBehaviors.some((behavior) => behavior.schema === table.schema && behavior.name === table.name))
266
+ return false;
267
+ }
268
+ for (const adjunct of adjuncts) {
269
+ const kind = adjunct.kind;
270
+ const schema = adjunct.schema;
271
+ if (kind === "function") {
272
+ if (!("name" in adjunct) || typeof adjunct.name !== "string")
273
+ return false;
274
+ const name = adjunct.name;
275
+ if (relationExists(schema, name) || snapshot.routines?.some((row) => row.schema === schema && row.name === name))
276
+ return false;
277
+ }
278
+ if (kind === "trigger") {
279
+ if (!("name" in adjunct) || typeof adjunct.name !== "string" || !("table" in adjunct) || typeof adjunct.table !== "string")
280
+ return false;
281
+ const { name, table } = adjunct;
282
+ if (snapshot.triggers?.some((row) => row.schema === schema && row.table === table && row.name === name) || relationBehaviors.some((row) => row.schema === schema && row.name === table && row.nonInternalTriggers.includes(name)))
283
+ return false;
284
+ }
285
+ }
286
+ return true;
287
+ }
288
+
289
+ // ../runtime/dist/framework-schema/migration-plan.js
290
+ function invalidHistory() {
291
+ throw runtimeDatabaseSetupError("RUNTIME_FRAMEWORK_SCHEMA_HISTORY_INVALID");
292
+ }
293
+ function unsatisfiedDependency() {
294
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_DEPENDENCY_UNSATISFIED");
295
+ }
296
+ function freeze(value, seen = /* @__PURE__ */ new WeakSet()) {
297
+ if (value && typeof value === "object" && !seen.has(value)) {
298
+ seen.add(value);
299
+ for (const child of Object.values(value))
300
+ freeze(child, seen);
301
+ Object.freeze(value);
302
+ }
303
+ return value;
304
+ }
305
+ function copyBundle(bundle) {
306
+ if (!bundle || !/^[a-z][a-z0-9-]{0,62}$/u.test(bundle.componentId) || typeof bundle.targetHead !== "string" || !Array.isArray(bundle.migrations) || bundle.migrations.length === 0)
307
+ return invalidHistory();
308
+ const migrations = bundle.migrations.map((migration, index) => {
309
+ if (!migration || typeof migration.migrationId !== "string" || !/^[0-9]{14}_[a-z0-9_]{1,48}$/u.test(migration.migrationId) || !Number.isSafeInteger(migration.migrationOrder) || migration.migrationOrder !== index + 1 || !Number.isSafeInteger(migration.createdAt) || migration.createdAt <= 0 || !/^[0-9a-f]{64}$/u.test(migration.hash) || migration.executionEligibility !== "startup-compatible" && migration.executionEligibility !== "owner-maintenance" || !Array.isArray(migration.statements) || migration.statements.length === 0 || migration.statements.length > 256 || migration.statements.some((statement) => typeof statement !== "string" || !statement.trim() || Buffer.byteLength(statement, "utf8") > 65536))
310
+ return invalidHistory();
311
+ return {
312
+ migrationId: migration.migrationId,
313
+ migrationOrder: migration.migrationOrder,
314
+ createdAt: migration.createdAt,
315
+ hash: migration.hash,
316
+ executionEligibility: migration.executionEligibility,
317
+ statements: [...migration.statements]
318
+ };
319
+ });
320
+ if (bundle.targetHead !== migrations.at(-1)?.migrationId)
321
+ return invalidHistory();
322
+ return freeze({ componentId: bundle.componentId, targetHead: bundle.targetHead, migrations });
323
+ }
324
+ function topologicalComponentOrder(ids, dependencies) {
325
+ const visiting = /* @__PURE__ */ new Set();
326
+ const visited = /* @__PURE__ */ new Set();
327
+ const order = [];
328
+ const visit = (id) => {
329
+ if (visiting.has(id))
330
+ return unsatisfiedDependency();
331
+ if (visited.has(id))
332
+ return;
333
+ visiting.add(id);
334
+ for (const edge of dependencies.filter((candidate) => candidate.fromComponentId === id))
335
+ visit(edge.componentId);
336
+ visiting.delete(id);
337
+ visited.add(id);
338
+ order.push(id);
339
+ };
340
+ for (const id of ids)
341
+ visit(id);
342
+ return order;
343
+ }
344
+ function planFrameworkMigrationTransition(input) {
345
+ if (!input || !Array.isArray(input.bundles) || !Array.isArray(input.rows) || !Array.isArray(input.baselines ?? []))
346
+ return invalidHistory();
347
+ let bundles;
348
+ try {
349
+ bundles = input.bundles.map(copyBundle);
350
+ } catch {
351
+ return invalidHistory();
352
+ }
353
+ const bundleById = new Map(bundles.map((bundle) => [bundle.componentId, bundle]));
354
+ if (bundleById.size !== bundles.length)
355
+ return invalidHistory();
356
+ const dependencies = input.dependencies ?? [];
357
+ if (!Array.isArray(dependencies))
358
+ return unsatisfiedDependency();
359
+ const dependencyKeys = /* @__PURE__ */ new Set();
360
+ for (const edge of dependencies) {
361
+ if (!edge || !/^[a-z][a-z0-9-]{0,62}$/u.test(edge.fromComponentId) || !/^[a-z][a-z0-9-]{0,62}$/u.test(edge.componentId) || edge.fromComponentId === edge.componentId || typeof edge.minimumMigrationId !== "string")
362
+ return unsatisfiedDependency();
363
+ const key2 = JSON.stringify([edge.fromComponentId, edge.componentId, edge.minimumMigrationId]);
364
+ if (dependencyKeys.has(key2))
365
+ return unsatisfiedDependency();
366
+ dependencyKeys.add(key2);
367
+ const provider = bundleById.get(edge.componentId);
368
+ const consumer = bundleById.get(edge.fromComponentId);
369
+ if (!consumer || !provider)
370
+ return unsatisfiedDependency();
371
+ const requiredOrder = provider.migrations.findIndex((migration) => migration.migrationId === edge.minimumMigrationId);
372
+ const targetOrder = provider.migrations.findIndex((migration) => migration.migrationId === provider.targetHead);
373
+ if (requiredOrder < 0 || targetOrder < requiredOrder)
374
+ return unsatisfiedDependency();
375
+ }
376
+ const baselineById = /* @__PURE__ */ new Map();
377
+ for (const baseline of input.baselines ?? []) {
378
+ const bundle = baseline && bundleById.get(baseline.componentId);
379
+ if (!bundle || baselineById.has(baseline.componentId) || !Number.isSafeInteger(baseline.migrationCount) || baseline.migrationCount < 1 || baseline.migrationCount > bundle.migrations.length)
380
+ return invalidHistory();
381
+ baselineById.set(baseline.componentId, baseline.migrationCount);
382
+ }
383
+ const byComponent = /* @__PURE__ */ new Map();
384
+ for (const candidate of input.rows) {
385
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate))
386
+ return invalidHistory();
387
+ const componentId = candidate.componentId;
388
+ if (typeof componentId !== "string" || componentId.length > 63)
389
+ return invalidHistory();
390
+ if (!bundleById.has(componentId))
391
+ continue;
392
+ const row = candidate;
393
+ if (typeof row.migrationId !== "string" || !/^[0-9]{14}_[a-z0-9_]{1,48}$/u.test(row.migrationId) || !Number.isSafeInteger(row.migrationOrder) || row.migrationOrder < 1 || !Number.isSafeInteger(row.createdAt) || row.createdAt <= 0 || !/^[0-9a-f]{64}$/u.test(row.hash) || row.appliedVia !== "migration" && row.appliedVia !== "baseline")
394
+ return invalidHistory();
395
+ const componentRows = byComponent.get(componentId) ?? [];
396
+ componentRows.push({ ...row });
397
+ byComponent.set(componentId, componentRows);
398
+ }
399
+ const transitions = /* @__PURE__ */ new Map();
400
+ for (const bundle of bundles) {
401
+ const recorded = (byComponent.get(bundle.componentId) ?? []).sort((left, right) => left.migrationOrder - right.migrationOrder);
402
+ const baselineCount = baselineById.get(bundle.componentId) ?? 0;
403
+ if (recorded.length && baselineCount)
404
+ return invalidHistory();
405
+ const startCount = recorded.length || baselineCount;
406
+ if (startCount > bundle.migrations.length)
407
+ return invalidHistory();
408
+ let sawMigration = false;
409
+ for (let index = 0; index < startCount; index++) {
410
+ const migration = bundle.migrations[index];
411
+ if (baselineCount && index >= baselineCount)
412
+ break;
413
+ const row = recorded[index];
414
+ if (recorded.length) {
415
+ if (!row || row.migrationOrder !== index + 1 || row.migrationId !== migration.migrationId || row.hash !== migration.hash || row.createdAt !== migration.createdAt || row.appliedVia === "baseline" && sawMigration)
416
+ return invalidHistory();
417
+ if (row.appliedVia === "migration")
418
+ sawMigration = true;
419
+ }
420
+ }
421
+ transitions.set(bundle.componentId, freeze({
422
+ componentId: bundle.componentId,
423
+ recordBaseline: bundle.migrations.slice(0, baselineCount),
424
+ pending: bundle.migrations.slice(startCount)
425
+ }));
426
+ }
427
+ const order = topologicalComponentOrder(bundles.map((bundle) => bundle.componentId), dependencies);
428
+ return freeze(order.map((componentId) => transitions.get(componentId)));
429
+ }
430
+
431
+ // ../runtime/dist/framework-schema/provider-port.js
432
+ function withSecurityStage(observation, stage) {
433
+ return Object.freeze({
434
+ ...observation,
435
+ security: Object.freeze({ ...observation.security, stage })
436
+ });
437
+ }
438
+
439
+ // ../runtime/dist/framework-schema/coordinator.js
440
+ function incompatible() {
441
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_SCHEMA_INCOMPATIBLE");
442
+ }
443
+ function invalidHistory2() {
444
+ throw runtimeDatabaseSetupError("RUNTIME_FRAMEWORK_SCHEMA_HISTORY_INVALID");
445
+ }
446
+ function requireStartupCompatiblePending(transitions) {
447
+ if (transitions.some((transition) => transition.pending.some((migration) => migration.executionEligibility === "owner-maintenance")))
448
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_MAINTENANCE_REQUIRED");
449
+ }
450
+ function selectedTriggerNames(plan) {
451
+ return plan.features.flatMap((feature) => feature.adjunctObjects.flatMap((object) => object.kind === "trigger" ? [`${object.schema}.${object.table}.${object.name}`] : []));
452
+ }
453
+ function ragColumnIdentity(column) {
454
+ return JSON.stringify([column.schema, column.table, column.name]);
455
+ }
456
+ function ragForwardOwnedColumns(feature) {
457
+ const foundation = feature.supportedPreimages.find((preimage) => preimage.migrationCount === 1);
458
+ if (!foundation)
459
+ return /* @__PURE__ */ new Set();
460
+ const foundationColumns = new Set(foundation.projection.flatMap((table) => table.columns.map((column) => ragColumnIdentity({ schema: table.schema, table: table.name, name: column.name }))));
461
+ return new Set(feature.supportedPreimages.filter((preimage) => preimage.migrationCount > foundation.migrationCount).flatMap((preimage) => preimage.projection.flatMap((table) => table.columns.map((column) => ragColumnIdentity({ schema: table.schema, table: table.name, name: column.name })).filter((identity) => !foundationColumns.has(identity)))));
462
+ }
463
+ function workflowGuardAbsent(snapshot) {
464
+ return !snapshot.relations.some((entry) => entry.schema === "public" && entry.name === "_gencow_workflow_terminal_guard") && !snapshot.relations.some((entry) => entry.schema === "public" && entry.name === "_gencow_workflow_terminal_guard_pkey") && !(snapshot.routines ?? []).some((entry) => entry.schema === "public" && entry.name === "_gencow_workflow_terminal_guard_check") && !(snapshot.triggers ?? []).some((entry) => entry.schema === "public" && entry.name === "_gencow_workflow_terminal_guard_check");
465
+ }
466
+ function workflowGuardReadyOrAccessOnly(snapshot) {
467
+ const guard = workflowTerminalGuardSchema.inspect(snapshot);
468
+ return guard.state === "ready" || guard.state === "compatible-change" && guard.stepIds.length === 1 && guard.stepIds[0] === "access-workflow-terminal-guard";
469
+ }
470
+ function frameworkAccessRequirements(plan) {
471
+ const requirements = [
472
+ ...plan.features.flatMap((feature) => [...feature.access]),
473
+ ...plan.journal ? [...plan.journal.access] : []
474
+ ];
475
+ const schemas = /* @__PURE__ */ new Map();
476
+ for (const requirement of requirements) {
477
+ if (requirement.kind === "schema")
478
+ continue;
479
+ const paths = schemas.get(requirement.schema) ?? /* @__PURE__ */ new Set();
480
+ for (const path of requirement.paths)
481
+ paths.add(path);
482
+ schemas.set(requirement.schema, paths);
483
+ }
484
+ for (const [schema, paths] of schemas)
485
+ requirements.push({
486
+ schema,
487
+ name: schema,
488
+ kind: "schema",
489
+ paths: [...paths],
490
+ privileges: ["USAGE"]
491
+ });
492
+ return requirements;
493
+ }
494
+ function matchedPreimage(plan, snapshot, featureId) {
495
+ const feature = plan.features.find((entry) => entry.componentId === featureId);
496
+ if (!feature)
497
+ return void 0;
498
+ const triggerNames = selectedTriggerNames(plan);
499
+ const ragForwardColumns = feature.componentId === "rag" ? ragForwardOwnedColumns(feature) : /* @__PURE__ */ new Set();
500
+ const presentRagForwardColumns = new Set(snapshot.columns.map((column) => ragColumnIdentity(column)).filter((identity) => ragForwardColumns.has(identity)));
501
+ const matches = feature.supportedPreimages.filter((preimage) => {
502
+ if (presentRagForwardColumns.size) {
503
+ const candidateColumns = new Set(preimage.projection.flatMap((table) => table.columns.map((column) => ragColumnIdentity({ schema: table.schema, table: table.name, name: column.name }))));
504
+ if ([...presentRagForwardColumns].some((identity) => !candidateColumns.has(identity)))
505
+ return false;
506
+ }
507
+ if (preimage.migrationCount === 0 && preimage.projection.length === 0)
508
+ return frameworkProjectionAbsent(snapshot, feature.targetProjection, feature.adjunctObjects);
509
+ if (compareFrameworkProjection(snapshot, preimage.projection, { allowedTriggers: triggerNames }).length)
510
+ return false;
511
+ if (feature.componentId !== "workflow")
512
+ return true;
513
+ if (preimage.migrationCount === 0)
514
+ return workflowGuardAbsent(snapshot);
515
+ return workflowGuardReadyOrAccessOnly(snapshot);
516
+ });
517
+ if (feature.componentId === "rag" && presentRagForwardColumns.size && matches.length !== 1)
518
+ return incompatible();
519
+ if (matches.length !== 1)
520
+ return void 0;
521
+ return matches[0].migrationCount;
522
+ }
523
+ function classifyPreimage(plan, snapshot, featureId) {
524
+ const matched = matchedPreimage(plan, snapshot, featureId);
525
+ return matched === void 0 ? incompatible() : matched;
526
+ }
527
+ function workflowBaselineForNoHistory(snapshot) {
528
+ if (workflowGuardAbsent(snapshot))
529
+ return 0;
530
+ if (workflowGuardReadyOrAccessOnly(snapshot))
531
+ return 1;
532
+ return incompatible();
533
+ }
534
+ function noFrameworkHistory(journal) {
535
+ if (journal?.state === "absent")
536
+ return true;
537
+ if (journal?.state !== "valid" || typeof journal.hasAnyFrameworkRows !== "boolean")
538
+ return false;
539
+ return !journal.hasAnyFrameworkRows;
540
+ }
541
+ function customTransition(plan, snapshot) {
542
+ if (plan.customComponents.length === 0)
543
+ return [];
544
+ const customPlan = {
545
+ components: plan.customComponents,
546
+ objects: plan.customComponents.flatMap((item) => [...item.objects])
547
+ };
548
+ const inspected = inspectRuntimeDatabaseSchemaPlan(customPlan, snapshot);
549
+ return inspected.map(({ component, steps }) => ({
550
+ componentId: component.id,
551
+ stepIds: steps.map((step) => step.id)
552
+ }));
553
+ }
554
+ function transitionForObservation(plan, observation) {
555
+ const { catalog, journal } = observation;
556
+ for (const feature of plan.features)
557
+ for (const capability of feature.capabilities)
558
+ if (!observation.capabilities.extensions.some((item) => item.schema === capability.schema && item.name === capability.name))
559
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_DEPENDENCY_UNSATISFIED");
560
+ const custom = customTransition(plan, catalog);
561
+ if (journal?.state === "access-unavailable")
562
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_ACCESS_UNAVAILABLE");
563
+ if (plan.journal && !journal)
564
+ return invalidHistory2();
565
+ if (journal?.state === "valid" && typeof journal.hasAnyFrameworkRows !== "boolean")
566
+ return invalidHistory2();
567
+ if (journal?.state === "valid" && !journal.hasAnyFrameworkRows && journal.rows.length > 0)
568
+ return invalidHistory2();
569
+ if (plan.journal && journal?.state === "absent" && !frameworkProjectionAbsent(catalog, plan.journal.projection))
570
+ return invalidHistory2();
571
+ const bootstrapAllowed = noFrameworkHistory(journal);
572
+ const foundationBootstrapComponents = /* @__PURE__ */ new Set();
573
+ const baselines = bootstrapAllowed ? plan.features.flatMap((feature) => {
574
+ if (feature.foundationBootstrap) {
575
+ const matched = matchedPreimage(plan, catalog, feature.componentId);
576
+ if (matched !== void 0 && matched > 0)
577
+ return [{ componentId: feature.componentId, migrationCount: matched }];
578
+ if (feature.componentId === "workflow" && matched === 0)
579
+ return [];
580
+ if (feature.foundationBootstrap.executionEligibility !== "startup-compatible" || feature.migrations.migrations[0]?.executionEligibility !== "startup-compatible")
581
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_MAINTENANCE_REQUIRED");
582
+ const migrationCount2 = feature.componentId === "workflow" ? workflowBaselineForNoHistory(catalog) : 1;
583
+ foundationBootstrapComponents.add(feature.componentId);
584
+ return migrationCount2 ? [{ componentId: feature.componentId, migrationCount: migrationCount2 }] : [];
585
+ }
586
+ const migrationCount = classifyPreimage(plan, catalog, feature.componentId);
587
+ return migrationCount ? [{ componentId: feature.componentId, migrationCount }] : [];
588
+ }) : [];
589
+ const rows = journal?.state === "valid" ? journal.rows : [];
590
+ if (!bootstrapAllowed) {
591
+ const workflow = plan.features.find((feature) => feature.componentId === "workflow");
592
+ if (workflow?.foundationBootstrap && !rows.some((row) => row.componentId === workflow.componentId) && frameworkProjectionAbsent(catalog, workflow.targetProjection, workflow.adjunctObjects)) {
593
+ if (workflow.foundationBootstrap.executionEligibility !== "startup-compatible" || workflow.migrations.migrations[0]?.executionEligibility !== "startup-compatible")
594
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_MAINTENANCE_REQUIRED");
595
+ foundationBootstrapComponents.add(workflow.componentId);
596
+ }
597
+ }
598
+ const planned = planFrameworkMigrationTransition({
599
+ bundles: plan.features.map((feature) => feature.migrations),
600
+ rows,
601
+ baselines,
602
+ dependencies: plan.dependencies
603
+ });
604
+ if (journal?.state === "valid" && !bootstrapAllowed) {
605
+ for (const entry of planned) {
606
+ const feature = plan.features.find((candidate) => candidate.componentId === entry.componentId);
607
+ if (foundationBootstrapComponents.has(feature.componentId))
608
+ continue;
609
+ const count = feature.migrations.migrations.length - entry.pending.length;
610
+ const preimage = feature.supportedPreimages.find((candidate) => candidate.migrationCount === count);
611
+ if (!preimage)
612
+ return invalidHistory2();
613
+ if (compareFrameworkProjection(catalog, preimage.projection, {
614
+ allowedTriggers: selectedTriggerNames(plan)
615
+ }).length || count === 0 && preimage.projection.length === 0 && !frameworkProjectionAbsent(catalog, feature.targetProjection, feature.adjunctObjects) || feature.componentId === "workflow" && count === 0 && !workflowGuardAbsent(catalog))
616
+ return incompatible();
617
+ }
618
+ }
619
+ if (journal?.state === "valid" && !bootstrapAllowed) {
620
+ for (const entry of planned) {
621
+ if (entry.pending.length)
622
+ continue;
623
+ const feature = plan.features.find((candidate) => candidate.componentId === entry.componentId);
624
+ if (compareFrameworkProjection(catalog, feature.targetProjection, {
625
+ allowedTriggers: selectedTriggerNames(plan)
626
+ }).length || feature.componentId === "workflow" && !workflowGuardReadyOrAccessOnly(catalog))
627
+ return incompatible();
628
+ }
629
+ }
630
+ requireStartupCompatiblePending(planned);
631
+ const requirements = frameworkAccessRequirements(plan);
632
+ const grants = missingFrameworkAccess(catalog, requirements).map((grant) => ({ ...grant }));
633
+ const builtIn = planned.map((entry) => {
634
+ const feature = plan.features.find((candidate) => candidate.componentId === entry.componentId);
635
+ if (!feature)
636
+ return invalidHistory2();
637
+ const appliedCount = journal?.state === "valid" && !bootstrapAllowed ? feature.migrations.migrations.length - entry.pending.length : 0;
638
+ return {
639
+ componentId: entry.componentId,
640
+ ...foundationBootstrapComponents.has(feature.componentId) && feature.foundationBootstrap ? {
641
+ foundationBootstrap: Object.freeze({
642
+ artifactId: feature.foundationBootstrap.artifactId,
643
+ hash: feature.foundationBootstrap.hash
644
+ })
645
+ } : {},
646
+ baselineMigrationIds: entry.recordBaseline.map((migration) => migration.migrationId),
647
+ appliedMigrationIds: feature.migrations.migrations.slice(0, appliedCount).map((migration) => migration.migrationId),
648
+ migrationIds: entry.pending.map((migration) => migration.migrationId)
649
+ };
650
+ });
651
+ return Object.freeze({
652
+ bootstrapJournal: Boolean(plan.journal && journal?.state === "absent"),
653
+ features: Object.freeze(builtIn),
654
+ customComponents: Object.freeze(custom),
655
+ grants: Object.freeze(grants)
656
+ });
657
+ }
658
+ function hasFrameworkSchemaTransition(transition) {
659
+ return transition.bootstrapJournal || transition.features.some((feature) => feature.foundationBootstrap !== void 0 || feature.baselineMigrationIds.length || feature.migrationIds.length) || transition.customComponents.some((component) => component.stepIds.length) || transition.grants.length > 0;
660
+ }
661
+ function verifyFrameworkFoundationPostimage(plan, observation, bootstraps) {
662
+ if (!Array.isArray(bootstraps) || bootstraps.length === 0 || new Set(bootstraps.map((artifact) => artifact.componentId)).size !== bootstraps.length)
663
+ return invalidHistory2();
664
+ if (observation.journal?.state !== "valid" || bootstraps.some((artifact) => observation.journal?.state === "valid" && observation.journal.rows.some((row) => row.componentId === artifact.componentId)))
665
+ return invalidHistory2();
666
+ for (const admitted of bootstraps) {
667
+ const feature = plan.features.find((candidate) => candidate.componentId === admitted.componentId);
668
+ const artifact = feature?.foundationBootstrap;
669
+ if (!feature || !artifact || artifact.artifactId !== admitted.artifactId || artifact.hash !== admitted.hash || artifact.executionEligibility !== "startup-compatible")
670
+ return invalidHistory2();
671
+ let projection;
672
+ if (feature.componentId === "workflow") {
673
+ const baseline = feature.supportedPreimages.find((candidate) => candidate.migrationCount === admitted.baselineMigrationIds.length);
674
+ if (admitted.baselineMigrationIds.length !== 0 || !baseline || admitted.baselineMigrationIds.some((id, index) => id !== feature.migrations.migrations[index]?.migrationId))
675
+ return invalidHistory2();
676
+ projection = baseline.projection;
677
+ if (!workflowGuardAbsent(observation.catalog))
678
+ return incompatible();
679
+ } else if (feature.componentId === "rag") {
680
+ const baseline = feature.supportedPreimages.find((candidate) => candidate.migrationCount === 1);
681
+ if (admitted.baselineMigrationIds.length !== 1 || !baseline || admitted.baselineMigrationIds[0] !== feature.migrations.migrations[0]?.migrationId)
682
+ return invalidHistory2();
683
+ projection = baseline.projection;
684
+ } else {
685
+ return invalidHistory2();
686
+ }
687
+ if (compareFrameworkProjection(observation.catalog, projection, {
688
+ allowedTriggers: selectedTriggerNames(plan)
689
+ }).length)
690
+ return incompatible();
691
+ }
692
+ }
693
+ function verifyFrameworkSchemaPostimage(plan, observation) {
694
+ const { catalog, journal } = observation;
695
+ for (const feature of plan.features)
696
+ for (const capability of feature.capabilities)
697
+ if (!observation.capabilities.extensions.some((item) => item.schema === capability.schema && item.name === capability.name))
698
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_DEPENDENCY_UNSATISFIED");
699
+ if (plan.journal && journal?.state !== "valid")
700
+ return invalidHistory2();
701
+ if (plan.features.length) {
702
+ const rows = journal?.state === "valid" ? journal.rows : [];
703
+ const histories = planFrameworkMigrationTransition({
704
+ bundles: plan.features.map((feature) => feature.migrations),
705
+ rows,
706
+ dependencies: plan.dependencies
707
+ });
708
+ if (histories.some((entry) => entry.pending.length || entry.recordBaseline.length))
709
+ return invalidHistory2();
710
+ for (const feature of plan.features) {
711
+ if (compareFrameworkProjection(catalog, feature.targetProjection, {
712
+ allowedTriggers: selectedTriggerNames(plan)
713
+ }).length)
714
+ return incompatible();
715
+ if (feature.componentId === "workflow" && workflowTerminalGuardSchema.inspect(catalog).state !== "ready")
716
+ return incompatible();
717
+ }
718
+ }
719
+ const requirements = frameworkAccessRequirements(plan);
720
+ if (missingFrameworkAccess(catalog, requirements).length)
721
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_ACCESS_UNAVAILABLE");
722
+ if (customTransition(plan, catalog).some((component) => component.stepIds.length))
723
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_ACCESS_UNAVAILABLE", "committed");
724
+ }
725
+ function createFrameworkSchemaResourceOwner(input) {
726
+ const owner = input.database;
727
+ const binding = Object.freeze({ ...input.binding });
728
+ const plan = input.plan;
729
+ const port = input.port;
730
+ const ownerController = new AbortController();
731
+ let closed = false;
732
+ let pending;
733
+ let ready;
734
+ async function prepare(signal = new AbortController().signal) {
735
+ if (closed)
736
+ throw runtimeDatabaseSetupInterrupted(signal);
737
+ if (ready)
738
+ return ready;
739
+ if (pending)
740
+ return pending;
741
+ const ownerSignal = AbortSignal.any([signal, ownerController.signal]);
742
+ pending = (async () => {
743
+ const correlationId = randomUUID();
744
+ const initial = await port.inspectOperational(plan, ownerSignal);
745
+ assertLocalPostgresSecurityPolicy(plan.policy, withSecurityStage(initial, "preparation").security);
746
+ let transition;
747
+ try {
748
+ transition = transitionForObservation(plan, initial);
749
+ } catch (error) {
750
+ const code = error?.diagnostic?.code;
751
+ if (code !== "RUNTIME_DATABASE_SETUP_ACCESS_UNAVAILABLE")
752
+ throw error;
753
+ }
754
+ let impact = "none";
755
+ let readback = initial;
756
+ if (!transition || hasFrameworkSchemaTransition(transition)) {
757
+ const receipt = await port.withSetupTransaction(plan, ownerSignal, async (session) => {
758
+ const locked = await session.observe();
759
+ assertLocalPostgresSecurityPolicy(plan.policy, withSecurityStage(locked, "prewrite").security);
760
+ const admitted = transitionForObservation(plan, locked);
761
+ const postimage = await session.executeAdmittedTransition(admitted);
762
+ assertLocalPostgresSecurityPolicy(plan.policy, withSecurityStage(postimage, "precommit").security);
763
+ verifyFrameworkSchemaPostimage(plan, postimage);
764
+ transition = admitted;
765
+ });
766
+ if (!receipt || receipt.impact !== "none" && receipt.impact !== "committed")
767
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_OUTCOME_UNKNOWN", "unknown", correlationId);
768
+ impact = receipt.impact;
769
+ readback = receipt.operationalObservation;
770
+ }
771
+ assertLocalPostgresSecurityPolicy(plan.policy, withSecurityStage(readback, "readback").security);
772
+ verifyFrameworkSchemaPostimage(plan, readback);
773
+ if (closed || ownerSignal.aborted)
774
+ throw runtimeDatabaseSetupInterrupted(ownerSignal, impact, correlationId);
775
+ ready = createFrameworkSchemaReady({
776
+ owner,
777
+ binding,
778
+ plan,
779
+ components: plan.features.map((feature) => ({
780
+ id: feature.componentId,
781
+ contractVersion: feature.contractVersion
782
+ })),
783
+ impact,
784
+ correlationId
785
+ });
786
+ return ready;
787
+ })();
788
+ return pending;
789
+ }
790
+ return Object.freeze({
791
+ prepare,
792
+ async borrow(componentId, proof) {
793
+ const feature = plan.features.find((candidate) => candidate.componentId === componentId);
794
+ if (!feature)
795
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
796
+ const state = assertFrameworkSchemaReady(proof, owner, binding, plan, componentId, feature.contractVersion);
797
+ if (closed || !ready || ready !== proof || state.owner !== owner)
798
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
799
+ const resource = await input.borrow(componentId);
800
+ if (closed || !ready || ready !== proof || state.owner !== owner)
801
+ throw runtimeDatabaseSetupError("RUNTIME_DATABASE_SETUP_COMPONENT_INVALID");
802
+ return resource;
803
+ },
804
+ async close() {
805
+ closed = true;
806
+ if (ready) {
807
+ revokeFrameworkSchemaReady(ready);
808
+ ready = void 0;
809
+ }
810
+ ownerController.abort();
811
+ await pending?.catch(() => {
812
+ });
813
+ }
814
+ });
815
+ }
816
+
817
+ export {
818
+ compareFrameworkProjection,
819
+ missingFrameworkAccess,
820
+ withSecurityStage,
821
+ frameworkAccessRequirements,
822
+ transitionForObservation,
823
+ hasFrameworkSchemaTransition,
824
+ verifyFrameworkFoundationPostimage,
825
+ verifyFrameworkSchemaPostimage,
826
+ createFrameworkSchemaResourceOwner
827
+ };