gencow 0.1.273 → 0.1.274

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.
@@ -628,6 +628,13 @@ function createDbMigrationCommand(deps, command) {
628
628
  functionsDir,
629
629
  retryCommand,
630
630
  inspectionCommand,
631
+ receiptStatusCommand: (serverReceiptId) =>
632
+ buildMigrationStatusCommand({
633
+ appId,
634
+ environment: envLabel,
635
+ receiptId: serverReceiptId,
636
+ jsonMode,
637
+ }),
631
638
  },
632
639
  )
633
640
  : isCheck
@@ -23,7 +23,7 @@ import {
23
23
  import { buildDeployClaimFromArchive } from "./deploy-package-claim.mjs";
24
24
  import { renderDeployFailureDiagnosticLines } from "./deploy-failure-diagnostic.mjs";
25
25
  import { readJsonObjectResponse } from "./http-response-json.mjs";
26
- import { pollAcceptedDeploymentOperation } from "./deployment-operation-poll.mjs";
26
+ import { formatDeploymentAcceptedLine, pollAcceptedDeploymentOperation } from "./deployment-operation-poll.mjs";
27
27
  import { postDeploymentAdmissionWithTimeout } from "./deploy-admission-boundary.mjs";
28
28
  import { submitDeploymentWithIdempotentRetry } from "./deployment-admission-retry.mjs";
29
29
  import * as deployReceiptStore from "./deploy-receipt-store.mjs";
@@ -548,19 +548,26 @@ export function createDeployPackageRuntime({
548
548
  const spinnerFrames = ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"];
549
549
  const start = Date.now();
550
550
  let index = 0;
551
- return setIntervalImpl(() => {
551
+ const spinner = { label, timer: null, setLabel: (next) => void (spinner.label = next) };
552
+ spinner.timer = setIntervalImpl(() => {
552
553
  const elapsed = ((Date.now() - start) / 1000).toFixed(0);
553
554
  processRef.stdout.write(
554
- `\r ${CYAN}${spinnerFrames[index++ % spinnerFrames.length]}${RESET} ${label} ${DIM}(${elapsed}s)${RESET} `,
555
+ `\r ${CYAN}${spinnerFrames[index++ % spinnerFrames.length]}${RESET} ${spinner.label} ${DIM}(${elapsed}s)${RESET} `,
555
556
  );
556
557
  }, 120);
558
+ return spinner;
557
559
  }
558
560
 
559
- function stopSpinner(spinner) {
560
- clearInterval(spinner);
561
+ // Clears the spinner glyph from the current terminal line before a status line is printed.
562
+ function clearSpinnerLine() {
561
563
  processRef.stdout.write("\r" + " ".repeat(50) + "\r");
562
564
  }
563
565
 
566
+ function stopSpinner(spinner) {
567
+ clearInterval(spinner.timer);
568
+ clearSpinnerLine();
569
+ }
570
+
564
571
  async function deployBundleWithRetry({
565
572
  creds,
566
573
  appId,
@@ -618,6 +625,7 @@ export function createDeployPackageRuntime({
618
625
  body: activeBundleBuffer,
619
626
  signal,
620
627
  });
628
+ let activeSpinner = null;
621
629
  const pollAcceptedDeployment = (initialResponse) =>
622
630
  pollAcceptedDeploymentOperation({
623
631
  initialResponse,
@@ -625,6 +633,11 @@ export function createDeployPackageRuntime({
625
633
  expectedAppName: appId,
626
634
  platformFetch: platformFetchImpl,
627
635
  setTimeoutImpl,
636
+ onAccepted: (accepted) => {
637
+ clearSpinnerLine();
638
+ infoImpl(formatDeploymentAcceptedLine({ ...accepted, envTarget }));
639
+ },
640
+ onPhase: (phase) => activeSpinner?.setLabel(`Deploying... (${phase})`),
628
641
  });
629
642
  const submitDeployAdmission = () => {
630
643
  return submitDeploymentWithIdempotentRetry({
@@ -660,7 +673,7 @@ export function createDeployPackageRuntime({
660
673
 
661
674
  let targetAppId = appId;
662
675
  const startTime = Date.now();
663
- const spinner = startSpinner("Deploying...");
676
+ const spinner = (activeSpinner = startSpinner("Deploying..."));
664
677
  let deployRes;
665
678
  try {
666
679
  deployRes = await submitDeployAdmission();
@@ -672,6 +685,7 @@ export function createDeployPackageRuntime({
672
685
  throw error;
673
686
  } finally {
674
687
  stopSpinner(spinner);
688
+ activeSpinner = null;
675
689
  }
676
690
 
677
691
  if (!deployRes.ok && deployRes.status === 404) {
@@ -715,7 +729,7 @@ export function createDeployPackageRuntime({
715
729
  activeDeployClaim = receipt.deployClaim;
716
730
  }
717
731
  infoImpl("Retrying deploy...");
718
- const retrySpinner = startSpinner("Deploying...");
732
+ const retrySpinner = (activeSpinner = startSpinner("Deploying..."));
719
733
  try {
720
734
  deployRes = await submitDeployAdmission();
721
735
  if (deployRes.status === 202) {
@@ -723,6 +737,7 @@ export function createDeployPackageRuntime({
723
737
  }
724
738
  } finally {
725
739
  stopSpinner(retrySpinner);
740
+ activeSpinner = null;
726
741
  }
727
742
  }
728
743
 
@@ -30,6 +30,17 @@ export function readDeploymentOperationPhase(body) {
30
30
  return { phase: body.phase, reasonCode, deadlineAt };
31
31
  }
32
32
 
33
+ /**
34
+ * One-line acceptance notice for `gencow deploy`. The identity was validated by
35
+ * pollAcceptedDeploymentOperation (positive integer operation ID, safe correlation ID).
36
+ * The status command uses the operation-scoped `--deployment` form, which accepts only `--prod` as
37
+ * a trailing selector, so no `--app` is appended.
38
+ */
39
+ export function formatDeploymentAcceptedLine({ operationId, correlationId, envTarget }) {
40
+ const prodSelector = envTarget === "prod" ? " --prod" : "";
41
+ return `Deployment accepted: ${operationId} (correlation ${correlationId}) - check with: gencow deploy status --deployment ${operationId}${prodSelector}`;
42
+ }
43
+
33
44
  export function formatDeploymentOperationPhase(body) {
34
45
  const phase = readDeploymentOperationPhase(body);
35
46
  if (!phase) return null;
@@ -99,6 +110,11 @@ function isNonterminalResponse(response, body, identity) {
99
110
  );
100
111
  }
101
112
 
113
+ /**
114
+ * Optional observers (no extra requests): `onAccepted` runs once when the
115
+ * accepted operation identity is established; `onPhase` runs when the reported
116
+ * phase name changes.
117
+ */
102
118
  export async function pollAcceptedDeploymentOperation({
103
119
  initialResponse,
104
120
  creds,
@@ -109,6 +125,8 @@ export async function pollAcceptedDeploymentOperation({
109
125
  deadlineClearTimeoutImpl = clearTimeout,
110
126
  nowImpl = () => performance.now(),
111
127
  totalDeadlineMs = DEFAULT_DEPLOYMENT_OPERATION_POLL_DEADLINE_MS,
128
+ onAccepted = null,
129
+ onPhase = null,
112
130
  }) {
113
131
  const expected = {
114
132
  operationId: null,
@@ -126,6 +144,7 @@ export async function pollAcceptedDeploymentOperation({
126
144
  const startedAtMs = nowImpl();
127
145
  const deadlineMs = startedAtMs + totalDeadlineMs;
128
146
  let lastIdentity = null;
147
+ let lastReportedPhase = null;
129
148
  const pendingResponse = () => ({
130
149
  ok: false,
131
150
  status: 503,
@@ -188,10 +207,23 @@ export async function pollAcceptedDeploymentOperation({
188
207
  return invalidOperationResponse("Platform returned an invalid deployment operation");
189
208
  }
190
209
  } else {
210
+ const firstAcceptance = expected.operationId === null;
191
211
  expected.operationId ??= identity.operationId;
192
212
  expected.correlationId ??= identity.correlationId;
193
213
  expected.pollUrl ??= identity.pollUrl;
194
214
  lastIdentity = identity;
215
+ // Diagnostic callbacks must never fail an already-accepted deployment.
216
+ if (firstAcceptance) {
217
+ try {
218
+ onAccepted?.({ operationId: identity.operationId, correlationId: identity.correlationId });
219
+ } catch {}
220
+ }
221
+ if (identity.phase && identity.phase.phase !== lastReportedPhase) {
222
+ lastReportedPhase = identity.phase.phase;
223
+ try {
224
+ onPhase?.(identity.phase.phase);
225
+ } catch {}
226
+ }
195
227
  }
196
228
  if (nowImpl() >= deadlineMs) return pendingResponse();
197
229
  const retryAfter = Number(response.headers?.get?.("Retry-After"));
@@ -222,6 +222,7 @@ export function enrichMigrationDiagnostic(
222
222
  functionsDir,
223
223
  retryCommand,
224
224
  inspectionCommand,
225
+ receiptStatusCommand,
225
226
  readFileSyncImpl = readFileSync,
226
227
  realpathSyncImpl = realpathSync,
227
228
  },
@@ -233,11 +234,20 @@ export function enrichMigrationDiagnostic(
233
234
  diagnostic.retryPolicy !== "BLOCKED" &&
234
235
  (diagnostic.nextAction?.kind === "EDIT_AND_CHECK" || diagnostic.nextAction?.kind === "RETRY");
235
236
  const canAttachInspectionCommand = inspectionCommand && diagnostic.nextAction?.kind === "INSPECT_STATE";
237
+ // An unclassified rollback has no safe retry: its exact next step is the receipt status command.
238
+ const canAttachReceiptStatusCommand =
239
+ typeof receiptStatusCommand === "function" &&
240
+ diagnostic.code === "MIGRATION_TRANSACTION_ROLLED_BACK" &&
241
+ diagnostic.databaseState === "ROLLED_BACK" &&
242
+ diagnostic.nextAction?.kind === "INSPECT_STATE" &&
243
+ typeof diagnostic.receiptId === "string";
236
244
  const nextAction = canAttachRetryCommand
237
245
  ? { kind: diagnostic.nextAction.kind, command: retryCommand }
238
- : canAttachInspectionCommand
239
- ? { kind: "INSPECT_STATE", command: inspectionCommand }
240
- : { kind: diagnostic.nextAction?.kind };
246
+ : canAttachReceiptStatusCommand
247
+ ? { kind: "INSPECT_STATE", command: receiptStatusCommand(diagnostic.receiptId) }
248
+ : canAttachInspectionCommand
249
+ ? { kind: "INSPECT_STATE", command: inspectionCommand }
250
+ : { kind: diagnostic.nextAction?.kind };
241
251
  const base = {
242
252
  ...diagnostic,
243
253
  ...(diagnostic.migration
@@ -316,9 +326,12 @@ function shouldRenderForbiddenActions(diagnostic) {
316
326
  }
317
327
 
318
328
  export function renderMigrationDiagnosticLines(diagnostic) {
329
+ // A rolled-back diagnostic keeps its own title and state; the "temporarily unavailable"
330
+ // wording is reserved for non-rollback platform-action failures.
319
331
  if (
320
332
  diagnostic.failureClass === "PLATFORM_ACTION_REQUIRED" &&
321
- diagnostic.nextAction?.kind !== "UPDATE_CLI"
333
+ diagnostic.nextAction?.kind !== "UPDATE_CLI" &&
334
+ diagnostic.databaseState !== "ROLLED_BACK"
322
335
  ) {
323
336
  const lines = [
324
337
  "Migration check is temporarily unavailable",
@@ -22,6 +22,19 @@ const USER_FIXABLE_CAUSES = new Map([
22
22
  const NOT_NULL_REPAIR_HINT =
23
23
  "For a NOT NULL failure, give the new column a DEFAULT or make it nullable, or split the change into forward migrations (expand → backfill → contract).";
24
24
 
25
+ // Type/data repair hints for the unlocated fallback. Mirrors the server's suggested-fix text in
26
+ // migration-rollback-diagnostic.ts; both must name only the column DEFAULT or literal in schema.ts.
27
+ const TYPE_REPAIR_HINTS = new Map([
28
+ [
29
+ "invalid_text_representation",
30
+ "For a value that does not match its column type, change the column DEFAULT or inserted literal in gencow/schema.ts to a value valid for the declared type (for example, a whole number for an integer column), then run db:generate to replace only this unapplied migration.",
31
+ ],
32
+ [
33
+ "string_data_right_truncation",
34
+ "For a value longer than its column allows, shorten the literal or change the column length in gencow/schema.ts, then run db:generate to replace only this unapplied migration.",
35
+ ],
36
+ ]);
37
+
25
38
  const SAFE_REASON_CODE = /^[a-z0-9_]{1,80}$/u;
26
39
 
27
40
  export function isUserFixableRolledBackDiagnostic(diagnostic) {
@@ -51,7 +64,8 @@ export function renderRollbackCauseLine(diagnostic) {
51
64
  export function renderUnlocatedRollbackFix(diagnostic) {
52
65
  const name = diagnostic?.migration?.name;
53
66
  const code = safeRollbackReasonCode(diagnostic);
54
- const hint = code === "not_null_violation" ? ` ${NOT_NULL_REPAIR_HINT}` : "";
67
+ const typeHint = code ? TYPE_REPAIR_HINTS.get(code) : undefined;
68
+ const hint = code === "not_null_violation" ? ` ${NOT_NULL_REPAIR_HINT}` : typeHint ? ` ${typeHint}` : "";
55
69
  return {
56
70
  title: name
57
71
  ? `Inspect the unapplied migration file ${name}`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gencow",
3
- "version": "0.1.273",
3
+ "version": "0.1.274",
4
4
  "description": "Gencow — AI Backend Engine",
5
5
  "type": "module",
6
6
  "bin": {
@@ -40,11 +40,11 @@
40
40
  "ai": "^6.0.314",
41
41
  "better-auth": "1.7.11",
42
42
  "postgres": "^3.4.9",
43
+ "@gencow/client": "0.2.8",
43
44
  "@gencow/react": "0.2.8",
45
+ "@gencow/core": "0.1.47",
44
46
  "@gencow/server": "0.1.3",
45
- "@gencow/client": "0.2.8",
46
- "@gencow/shared": "0.0.0",
47
- "@gencow/core": "0.1.47"
47
+ "@gencow/shared": "0.0.0"
48
48
  },
49
49
  "scripts": {
50
50
  "build": "node scripts/bundle-core.mjs && node scripts/bundle-shared.mjs && node scripts/bundle-server.mjs",
@@ -8980,7 +8980,7 @@ ${argsDigest}`;const signature=sign3(null,Buffer.from(payload),scheduledJobDeliv
8980
8980
  AND attribute.attnum > 0
8981
8981
  AND NOT attribute.attisdropped
8982
8982
  ORDER BY attribute.attnum
8983
- `):[];const database=databaseRows[0]??{};const schema=schemaRows[0]??{};const journalSecurity=journalSecurityRows[0]??{};const drizzleSchemaExists=schemaRows.length>0;return{databaseCanConnect:toBoolean(database.database_can_connect),databaseCanCreate:toBoolean(database.database_can_create),publicSchemaUsage:toBoolean(database.public_usage),publicSchemaCreate:toBoolean(database.public_create),drizzleSchemaExists,drizzleSchemaOwner:drizzleSchemaExists?toNullableString(schema.owner):null,drizzleSchemaOwnedByDatabaseOwner:drizzleSchemaExists?toBoolean(schema.owned_by_database_owner):false,drizzleSchemaUsage:drizzleSchemaExists?toBoolean(schema.drizzle_usage):false,drizzleSchemaCreate:drizzleSchemaExists?toBoolean(schema.drizzle_create):false,journalTableExists:toBoolean(journalRows[0]?.journal_exists),journalTableOwner:toNullableString(journalSecurity.owner),journalTableOwnedByDatabaseOwner:toBoolean(journalSecurity.owned_by_database_owner),journalColumns:columnRows.map(row=>toNullableString(row.column_name)).filter(isString),journalCanSelect:toBoolean(journalSecurity.can_select),journalCanInsert:toBoolean(journalSecurity.can_insert),journalCanUpdate:toBoolean(journalSecurity.can_update),journalCanDelete:toBoolean(journalSecurity.can_delete),journalCanTruncate:toBoolean(journalSecurity.can_truncate),journalPlanGuardInstalled:toBoolean(journalSecurity.guard_installed)}}async function assertDrizzleMigrationStoreReadyForPrimaryMigrate(params){const snapshot=await collectDrizzleMigrationStoreSnapshot(params.sql,{roleName:params.roleName});const state2=classifyDrizzleMigrationStoreState(snapshot,params.roleName);if(isDrizzleMigrationStoreStateAllowedForPrimaryMigrate(state2)){return snapshot}const code=getDrizzleMigrationStorePreflightErrorCode(state2)??"DB_MIGRATION_STORE_UNSAFE";throw new DrizzleMigrationStorePreflightError({appName:params.appName,state:state2,code})}function hasCompatibleJournalShape(columns){const present=new Set(columns);for(const required3 of REQUIRED_JOURNAL_COLUMNS){if(!present.has(required3))return false}return true}function toBoolean(value2){return value2===true||value2==="true"||value2===1||value2==="1"}function toNullableString(value2){return typeof value2==="string"&&value2.length>0?value2:null}function isString(value2){return typeof value2==="string"}var REQUIRED_JOURNAL_COLUMNS,DrizzleMigrationStorePreflightError;var init_drizzle_migration_store=__esm({"../platform/src/drizzle-migration-store.ts"(){"use strict";REQUIRED_JOURNAL_COLUMNS=new Set(["id","hash","created_at","name"]);DrizzleMigrationStorePreflightError=class extends Error{code;state;constructor(params){super(`${params.code}: ${params.appName} migration store state=${params.state}; run the Drizzle migration store reconciler before deploy.`);this.name="DrizzleMigrationStorePreflightError";this.code=params.code;this.state=params.state}}}});import{createHash as createHash50}from"node:crypto";import{getMigrationsToRun}from"drizzle-orm/migrator.utils";function fingerprint3(value2){return createHash50("sha256").update(JSON.stringify(value2)).digest("hex")}function localFingerprint(migrations){return fingerprint3(migrations.map(migration=>[migration.name,migration.hash,migration.folderMillis,migration.bps]))}function journalFingerprint(rows8){return fingerprint3([...rows8].sort((left,right)=>left.id-right.id).map(row=>[row.id,row.name,row.hash,row.createdAt]))}function safeMigrationName(name){return JSON.stringify(name)}function indexLocalMigrations(migrations){const byName=new Map;for(const migration of migrations){if(!migration.name||byName.has(migration.name)){throw new MigrationExecutionPlanError("MIGRATION_LOCAL_HISTORY_AMBIGUOUS",migration.name?`duplicate local migration name ${safeMigrationName(migration.name)}`:"a local migration has no stable name",{migrationName:migration.name||void 0,migrationHash:migration.hash})}byName.set(migration.name,migration)}return byName}function indexJournalRows(rows8){const byName=new Map;for(const row of rows8){if(!row.name){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HISTORY_AMBIGUOUS","the Drizzle journal contains an applied row without a stable migration name")}if(byName.has(row.name)){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HISTORY_AMBIGUOUS",`the Drizzle journal contains duplicate migration name ${safeMigrationName(row.name)}`)}byName.set(row.name,row)}return byName}function buildMigrationExecutionPlan(input2){const localMigrations=[...input2.localMigrations];const journalRows=[...input2.journalRows];const localByName=indexLocalMigrations(localMigrations);const journalByName=indexJournalRows(journalRows);for(const[name,row]of journalByName){const local=localByName.get(name);if(!local){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_FILE_MISSING",`applied migration ${safeMigrationName(name)} is absent from the deployment bundle`,{migrationName:name,migrationHash:row.hash})}if(local.hash!==row.hash){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HASH_DRIFT",`applied migration ${safeMigrationName(name)} no longer matches its immutable local file`,{migrationName:name,migrationHash:local.hash})}}const pending=getMigrationsToRun({localMigrations,dbMigrations:journalRows.map(row=>({id:row.id,hash:row.hash,created_at:row.createdAt,name:row.name}))});const pendingNames=new Set(pending.map(migration=>migration.name));const appliedVerified=localMigrations.filter(migration=>!pendingNames.has(migration.name));return{appliedVerified,pending,localFingerprint:localFingerprint(localMigrations),journalFingerprint:journalFingerprint(journalRows),planId:`mig_${fingerprint3([localFingerprint(localMigrations),journalFingerprint(journalRows)]).slice(0,24)}`}}function assertMigrationExecutionPlanUnchanged(planned,current){if(localFingerprint(current.localMigrations)!==planned.localFingerprint||journalFingerprint(current.journalRows)!==planned.journalFingerprint){throw new MigrationExecutionPlanError("MIGRATION_PLAN_CHANGED","local migration files or the database journal changed after audit; retry from a fresh plan",{planId:planned.planId})}}function assertMigrationExecutionPostcondition(planned,current){let isSatisfied=localFingerprint(current.localMigrations)===planned.localFingerprint;if(isSatisfied){try{isSatisfied=buildMigrationExecutionPlan(current).pending.length===0}catch{isSatisfied=false}}if(!isSatisfied){throw new MigrationExecutionPlanError("MIGRATION_POSTCONDITION_FAILED","not every audited migration was recorded with its exact immutable hash",{planId:planned.planId})}}var MigrationExecutionPlanError;var init_migration_execution_plan=__esm({"../platform/src/migration-execution-plan.ts"(){"use strict";MigrationExecutionPlanError=class extends Error{code;migrationName;migrationHash;planId;constructor(code,detail,metadata={}){super(`${code}: ${detail}`);this.name="MigrationExecutionPlanError";this.code=code;this.migrationName=metadata.migrationName;this.migrationHash=metadata.migrationHash;this.planId=metadata.planId}}}});function isWordStart(char){return!!char&&/[A-Za-z_\u0080-\uFFFF]/u.test(char)}function isWordPart(char){return!!char&&/[A-Za-z0-9_$\u0080-\uFFFF]/u.test(char)}function readQuotedToken(sql217,start2,quote2,options={}){let index27=start2+1;while(index27<sql217.length){if(options.backslashEscapes&&sql217[index27]==="\\"&&index27+1<sql217.length){index27+=2;continue}if(sql217[index27]!==quote2){index27+=1;continue}if(sql217[index27+1]===quote2){index27+=2;continue}const end=index27+1;const tokenStart=options.tokenStart??start2;const raw2=sql217.slice(tokenStart,end);const quotedValue=sql217.slice(start2+1,index27);return{token:{kind:quote2==="'"?"string":"identifier",value:quote2==="'"?options.backslashEscapes?quotedValue.replace(/''/g,"'").replace(/\\(.)/gsu,"$1"):quotedValue.replace(/''/g,"'"):quotedValue.replace(/""/g,'"'),raw:raw2,start:tokenStart,end},next:end}}return{next:sql217.length,error:quote2==="'"?"unterminated SQL string":"unterminated identifier"}}function readDollarString(sql217,start2){const opener=sql217.slice(start2).match(/^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/)?.[0];if(!opener)return null;const closeIndex=sql217.indexOf(opener,start2+opener.length);if(closeIndex<0)return{next:sql217.length,error:"unterminated dollar-quoted SQL body"};const end=closeIndex+opener.length;const raw2=sql217.slice(start2,end);return{token:{kind:"dollar-string",value:raw2.slice(opener.length,-opener.length),raw:raw2,start:start2,end},next:end}}function skipBlockComment(sql217,start2){let depth=1;let index27=start2+2;while(index27<sql217.length){if(sql217.startsWith("/*",index27)){depth+=1;index27+=2;continue}if(sql217.startsWith("*/",index27)){depth-=1;index27+=2;if(depth===0)return{next:index27};continue}index27+=1}return{next:sql217.length,error:"unterminated SQL block comment"}}function buildStatement(sql217,tokens,end){if(tokens.length===0)return null;return{text:sql217.slice(tokens[0].start,tokens[tokens.length-1].end).trim(),tokens,start:tokens[0].start,end}}function lexSqlStatements(sql217){const statements=[];let statementTokens=[];let index27=0;while(index27<sql217.length){const char=sql217[index27];if(/\s/u.test(char)){index27+=1;continue}if(sql217.startsWith("--",index27)){const newline=sql217.indexOf("\n",index27+2);index27=newline<0?sql217.length:newline+1;continue}if(sql217.startsWith("/*",index27)){const block=skipBlockComment(sql217,index27);if(block.error)return{statements,error:block.error};index27=block.next;continue}if((char==="E"||char==="e")&&sql217[index27+1]==="'"){const quoted=readQuotedToken(sql217,index27+1,"'",{tokenStart:index27,backslashEscapes:true});if(quoted.error||!quoted.token){return{statements,error:quoted.error??"invalid escape string"}}statementTokens.push(quoted.token);index27=quoted.next;continue}if(char==="'"||char==='"'){const quoted=readQuotedToken(sql217,index27,char);if(quoted.error||!quoted.token)return{statements,error:quoted.error??"invalid quoted token"};statementTokens.push(quoted.token);index27=quoted.next;continue}if(char==="$"){const dollar=readDollarString(sql217,index27);if(dollar){if(dollar.error||!dollar.token)return{statements,error:dollar.error??"invalid dollar string"};statementTokens.push(dollar.token);index27=dollar.next;continue}}if(isWordStart(char)){let end=index27+1;while(isWordPart(sql217[end]))end+=1;const raw2=sql217.slice(index27,end);statementTokens.push({kind:"word",value:raw2.toLowerCase(),raw:raw2,start:index27,end});index27=end;continue}if(char===";"){const statement=buildStatement(sql217,statementTokens,index27+1);if(statement)statements.push(statement);statementTokens=[];index27+=1;continue}statementTokens.push({kind:"symbol",value:char,raw:char,start:index27,end:index27+1});index27+=1}const tail=buildStatement(sql217,statementTokens,statementTokens.at(-1)?.end??sql217.length);if(tail)statements.push(tail);return{statements}}function createSqlLineNumberResolver(sql217){const lineStarts=[0];for(let offset=0;offset<sql217.length;offset+=1){if(sql217[offset]==="\n")lineStarts.push(offset+1)}return offset=>{let low=0;let high=lineStarts.length;while(low<high){const middle=Math.floor((low+high)/2);if(lineStarts[middle]<=offset)low=middle+1;else high=middle}return low}}var init_migration_sql_lexer=__esm({"../platform/src/migration-sql-lexer.ts"(){"use strict"}});async function readMigrationPostExecutionSnapshot(params){let lastError;for(const delayMs of POST_EXECUTION_READ_RETRY_DELAYS_MS){if(delayMs>0)await Bun.sleep(delayMs);try{return{local:await params.readLocal(),journal:await params.readJournal()}}catch(error62){lastError=error62}}throw lastError}function safeObjectField(value2,key2){try{return value2[key2]}catch{return void 0}}function collectFailureFacts(error62){const sqlStates=new Set;const errorCodes=new Set;const queries=new Set;const visited=new Set;const pending=[error62];for(let inspected=0;inspected<64&&pending.length>0;inspected+=1){const current=pending.shift();if(!current||typeof current!=="object")continue;if(visited.has(current))continue;visited.add(current);for(const key2 of["code","errno"]){const value2=safeObjectField(current,key2);if(typeof value2==="string"&&/^[a-zA-Z0-9_:-]{1,80}$/u.test(value2)){errorCodes.add(value2);if(/^[0-9A-Z]{5}$/u.test(value2))sqlStates.add(value2)}}const query2=safeObjectField(current,"query");if(typeof query2==="string")queries.add(query2);const cause=safeObjectField(current,"cause");if(cause&&typeof cause==="object")pending.push(cause);const errors=safeObjectField(current,"errors");if(Array.isArray(errors)){pending.push(...errors.slice(0,16))}}return{sqlStates:[...sqlStates],errorCodes:[...errorCodes],queries:[...queries]}}function isExactPostgresSqlStateFailure(error62,sqlState){if(!/^[0-9A-Z]{5}$/u.test(sqlState))return false;const sqlStates=collectFailureFacts(error62).sqlStates;return sqlStates.length>0&&sqlStates.every(observed2=>observed2===sqlState)}function canonicalStatement(statement){return statement.trim().replace(/;\s*$/u,"").trim()}function statementLocation(source,statement,statementIndex){const lexed=lexSqlStatements(source.sqlContent);if(lexed.error)return void 0;const canonical=canonicalStatement(statement);const matches=lexed.statements.filter(candidate=>canonicalStatement(candidate.text)===canonical);if(matches.length!==1)return void 0;const[match2]=matches;const lineAt=createSqlLineNumberResolver(source.sqlContent);return{name:source.metadata.name,sqlSha256:source.metadata.hash,statementIndex,lineStart:lineAt(match2.start),lineEnd:lineAt(Math.max(match2.end-1,match2.start))}}function findExactFailureLocation(queries,pendingSources){const querySet=new Set(queries);const matches=[];for(const source of pendingSources){for(const[index27,statement]of source.metadata.sql.entries()){if(!querySet.has(statement))continue;const location=statementLocation(source,statement,index27+1);if(location)matches.push(location)}}return matches.length===1?matches[0]:void 0}function retryableReason(sqlStates){for(const state2 of sqlStates){const exact=RETRYABLE_SQLSTATES.get(state2);if(exact)return exact;if(state2.startsWith("08"))return"database_connection_lost"}return void 0}function userReason(sqlStates){for(const state2 of sqlStates){const exact=USER_SQLSTATE_REASONS.get(state2);if(exact)return exact;if(/^(22|23|42)/u.test(state2)||state2==="P0001"){return`postgres_sqlstate_${state2.toLowerCase()}`}}return void 0}function platformReason(sqlStates){for(const state2 of sqlStates){const exact=PLATFORM_SQLSTATE_REASONS.get(state2);if(exact)return exact}return void 0}function buildMigrationTransactionRolledBackError(params){const facts=collectFailureFacts(params.cause);const platformFailure=platformReason(facts.sqlStates);if(platformFailure){return new MigrationTransactionRolledBackError({failureClass:"PLATFORM_ACTION_REQUIRED",reasonCode:platformFailure,planId:params.planId})}const transient=retryableReason(facts.sqlStates);if(transient){return new MigrationTransactionRolledBackError({failureClass:"RETRYABLE_INFRA",reasonCode:transient,planId:params.planId})}const migration=findExactFailureLocation(facts.queries,params.pendingSources);const userFailure=userReason(facts.sqlStates);if(userFailure){return new MigrationTransactionRolledBackError({failureClass:"USER_FIXABLE",reasonCode:userFailure,planId:params.planId,...migration?{migration}:{}})}if(facts.sqlStates.length===0){console.warn(`[migration] execution failure had no PostgreSQL SQLSTATE in the redacted cause chain codes=${facts.errorCodes.join(",")||"none"}`)}return new MigrationTransactionRolledBackError({failureClass:"PLATFORM_ACTION_REQUIRED",reasonCode:"execution_failure_unclassified",planId:params.planId})}var RETRYABLE_SQLSTATES,USER_SQLSTATE_REASONS,PLATFORM_SQLSTATE_REASONS,POST_EXECUTION_READ_RETRY_DELAYS_MS,MigrationTransactionRolledBackError;var init_migration_execution_outcome=__esm({"../platform/src/migration-execution-outcome.ts"(){"use strict";init_migration_sql_lexer();RETRYABLE_SQLSTATES=new Map([["40001","serialization_failure"],["40P01","deadlock_detected"],["55P03","lock_not_available"],["57014","statement_timeout_or_cancelled"],["53300","too_many_connections"],["53400","configuration_limit_exceeded"],["57P01","database_admin_shutdown"],["57P02","database_crash_shutdown"],["57P03","database_starting_up"]]);USER_SQLSTATE_REASONS=new Map([["22001","string_data_right_truncation"],["22P02","invalid_text_representation"],["25001","active_sql_transaction"],["23502","not_null_violation"],["23503","foreign_key_violation"],["23505","unique_violation"],["42601","syntax_error"],["42701","duplicate_column"],["42703","undefined_column"],["42P01","undefined_table"],["42P07","duplicate_table"]]);PLATFORM_SQLSTATE_REASONS=new Map([["42501","insufficient_privilege"],["0A000","feature_not_supported"],["28000","invalid_authorization_specification"],["28P01","invalid_password"]]);POST_EXECUTION_READ_RETRY_DELAYS_MS=[0,25,100,250];MigrationTransactionRolledBackError=class extends Error{code="MIGRATION_TRANSACTION_ROLLED_BACK";failureClass;reasonCode;planId;migration;constructor(params){super("MIGRATION_TRANSACTION_ROLLED_BACK: the PostgreSQL transaction was rolled back");this.name="MigrationTransactionRolledBackError";this.failureClass=params.failureClass;this.reasonCode=params.reasonCode;this.planId=params.planId;this.migration=params.migration}}}});function base(error62,correlationId){return{code:error62.code,phase:"EXECUTE",databaseState:"ROLLED_BACK",correlationId}}function buildRolledBackDiagnostic(params){const{error:error62,correlationId,migration}=params;if(error62.failureClass==="RETRYABLE_INFRA"){return retryableInfraDiagnostic({...base(error62,correlationId),retryPolicy:"AFTER_DELAY",retryCondition:"Retry the same immutable bundle after the temporary PostgreSQL condition clears.",retryAfterSeconds:5,reason:{code:error62.reasonCode,summary:"The migration transaction was rolled back after a temporary database failure.",detail:"PostgreSQL confirmed that the transaction and its journal writes did not commit. No source edit is recommended."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}if(error62.failureClass==="USER_FIXABLE"){const hasExactLocation=migration!==void 0;const suggestedFixes=[{id:"repair-pending-migration",title:hasExactLocation?"Repair the exact unapplied migration statement":"Inspect the pending migration candidates",detail:hasExactLocation?"Update the schema source or this unapplied statement, review the generated diff, and create a fresh immutable plan.":"Run db:check to list the pending migrations, locate the statement matching this PostgreSQL reason, then update only unapplied source and create a fresh plan.",target:"PENDING_MIGRATION",confidence:hasExactLocation?"HIGH":"MEDIUM"}];return userFixableDiagnostic({...base(error62,correlationId),retryCondition:"Fix only the exact unapplied statement, then create and check a fresh plan.",...migration?{migration}:{},reason:{code:error62.reasonCode,summary:hasExactLocation?"PostgreSQL rejected an exact pending migration statement and rolled back the transaction.":"PostgreSQL rejected a pending migration, but the exact source span was not unique.",detail:hasExactLocation?"Review the identified statement against the current schema and data. The failed transaction did not commit any migration or journal change.":"Use the stable PostgreSQL reason and the pending list from db:check to identify the customer-owned statement. The transaction and journal did not commit."},suggestedFixes,forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"REDACTED_LITERALS"}})}if(error62.failureClass==="PLATFORM_ACTION_REQUIRED"){return retryableInfraDiagnostic({...base(error62,correlationId),retryPolicy:"AFTER_DELAY",retryAfterSeconds:30,retryCondition:"View the operation receipt and retry only after the Platform DDL permission or runner health has recovered.",reason:{code:error62.reasonCode,summary:"PostgreSQL rolled back because the managed DDL execution boundary was unavailable.",detail:"The transaction and journal did not commit. This is not fixed by editing applied migrations or the journal; use the receipt status before another attempt."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}return retryableInfraDiagnostic({...base(error62,correlationId),retryPolicy:"AFTER_DELAY",retryAfterSeconds:30,retryCondition:"Retry the same immutable bundle after the temporary classification failure clears.",reason:{code:error62.reasonCode,summary:"The transaction rolled back, but the failure could not be classified automatically.",detail:"PostgreSQL proved that the transaction did not commit. Keep the source unchanged and retry after the indicated delay."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}var init_migration_rollback_diagnostic=__esm({"../platform/src/migration-rollback-diagnostic.ts"(){"use strict";init_dist()}});function toJournalRow(row){const id=row.id;const hash9=row.hash;const createdAt=row.created_at;const name=row.name;if(typeof id!=="number"||!Number.isSafeInteger(id)||id<1||typeof hash9!=="string"||hash9.length===0||typeof createdAt!=="string"&&typeof createdAt!=="number"&&typeof createdAt!=="bigint"||name!==null&&(typeof name!=="string"||name.length===0)){throw new MigrationJournalReadError("a journal row has an invalid id, name, hash, or timestamp")}return{id,hash:hash9,createdAt:String(createdAt),name}}async function readDrizzleMigrationJournal(params){if(!params.snapshot.journalTableExists)return[];const rows8=await params.sql.unsafe(`
8983
+ `):[];const database=databaseRows[0]??{};const schema=schemaRows[0]??{};const journalSecurity=journalSecurityRows[0]??{};const drizzleSchemaExists=schemaRows.length>0;return{databaseCanConnect:toBoolean(database.database_can_connect),databaseCanCreate:toBoolean(database.database_can_create),publicSchemaUsage:toBoolean(database.public_usage),publicSchemaCreate:toBoolean(database.public_create),drizzleSchemaExists,drizzleSchemaOwner:drizzleSchemaExists?toNullableString(schema.owner):null,drizzleSchemaOwnedByDatabaseOwner:drizzleSchemaExists?toBoolean(schema.owned_by_database_owner):false,drizzleSchemaUsage:drizzleSchemaExists?toBoolean(schema.drizzle_usage):false,drizzleSchemaCreate:drizzleSchemaExists?toBoolean(schema.drizzle_create):false,journalTableExists:toBoolean(journalRows[0]?.journal_exists),journalTableOwner:toNullableString(journalSecurity.owner),journalTableOwnedByDatabaseOwner:toBoolean(journalSecurity.owned_by_database_owner),journalColumns:columnRows.map(row=>toNullableString(row.column_name)).filter(isString),journalCanSelect:toBoolean(journalSecurity.can_select),journalCanInsert:toBoolean(journalSecurity.can_insert),journalCanUpdate:toBoolean(journalSecurity.can_update),journalCanDelete:toBoolean(journalSecurity.can_delete),journalCanTruncate:toBoolean(journalSecurity.can_truncate),journalPlanGuardInstalled:toBoolean(journalSecurity.guard_installed)}}async function assertDrizzleMigrationStoreReadyForPrimaryMigrate(params){const snapshot=await collectDrizzleMigrationStoreSnapshot(params.sql,{roleName:params.roleName});const state2=classifyDrizzleMigrationStoreState(snapshot,params.roleName);if(isDrizzleMigrationStoreStateAllowedForPrimaryMigrate(state2)){return snapshot}const code=getDrizzleMigrationStorePreflightErrorCode(state2)??"DB_MIGRATION_STORE_UNSAFE";throw new DrizzleMigrationStorePreflightError({appName:params.appName,state:state2,code})}function hasCompatibleJournalShape(columns){const present=new Set(columns);for(const required3 of REQUIRED_JOURNAL_COLUMNS){if(!present.has(required3))return false}return true}function toBoolean(value2){return value2===true||value2==="true"||value2===1||value2==="1"}function toNullableString(value2){return typeof value2==="string"&&value2.length>0?value2:null}function isString(value2){return typeof value2==="string"}var REQUIRED_JOURNAL_COLUMNS,DrizzleMigrationStorePreflightError;var init_drizzle_migration_store=__esm({"../platform/src/drizzle-migration-store.ts"(){"use strict";REQUIRED_JOURNAL_COLUMNS=new Set(["id","hash","created_at","name"]);DrizzleMigrationStorePreflightError=class extends Error{code;state;constructor(params){super(`${params.code}: ${params.appName} migration store state=${params.state}; run the Drizzle migration store reconciler before deploy.`);this.name="DrizzleMigrationStorePreflightError";this.code=params.code;this.state=params.state}}}});import{createHash as createHash50}from"node:crypto";import{getMigrationsToRun}from"drizzle-orm/migrator.utils";function fingerprint3(value2){return createHash50("sha256").update(JSON.stringify(value2)).digest("hex")}function localFingerprint(migrations){return fingerprint3(migrations.map(migration=>[migration.name,migration.hash,migration.folderMillis,migration.bps]))}function journalFingerprint(rows8){return fingerprint3([...rows8].sort((left,right)=>left.id-right.id).map(row=>[row.id,row.name,row.hash,row.createdAt]))}function safeMigrationName(name){return JSON.stringify(name)}function indexLocalMigrations(migrations){const byName=new Map;for(const migration of migrations){if(!migration.name||byName.has(migration.name)){throw new MigrationExecutionPlanError("MIGRATION_LOCAL_HISTORY_AMBIGUOUS",migration.name?`duplicate local migration name ${safeMigrationName(migration.name)}`:"a local migration has no stable name",{migrationName:migration.name||void 0,migrationHash:migration.hash})}byName.set(migration.name,migration)}return byName}function indexJournalRows(rows8){const byName=new Map;for(const row of rows8){if(!row.name){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HISTORY_AMBIGUOUS","the Drizzle journal contains an applied row without a stable migration name")}if(byName.has(row.name)){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HISTORY_AMBIGUOUS",`the Drizzle journal contains duplicate migration name ${safeMigrationName(row.name)}`)}byName.set(row.name,row)}return byName}function buildMigrationExecutionPlan(input2){const localMigrations=[...input2.localMigrations];const journalRows=[...input2.journalRows];const localByName=indexLocalMigrations(localMigrations);const journalByName=indexJournalRows(journalRows);for(const[name,row]of journalByName){const local=localByName.get(name);if(!local){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_FILE_MISSING",`applied migration ${safeMigrationName(name)} is absent from the deployment bundle`,{migrationName:name,migrationHash:row.hash})}if(local.hash!==row.hash){throw new MigrationExecutionPlanError("MIGRATION_APPLIED_HASH_DRIFT",`applied migration ${safeMigrationName(name)} no longer matches its immutable local file`,{migrationName:name,migrationHash:local.hash})}}const pending=getMigrationsToRun({localMigrations,dbMigrations:journalRows.map(row=>({id:row.id,hash:row.hash,created_at:row.createdAt,name:row.name}))});const pendingNames=new Set(pending.map(migration=>migration.name));const appliedVerified=localMigrations.filter(migration=>!pendingNames.has(migration.name));return{appliedVerified,pending,localFingerprint:localFingerprint(localMigrations),journalFingerprint:journalFingerprint(journalRows),planId:`mig_${fingerprint3([localFingerprint(localMigrations),journalFingerprint(journalRows)]).slice(0,24)}`}}function assertMigrationExecutionPlanUnchanged(planned,current){if(localFingerprint(current.localMigrations)!==planned.localFingerprint||journalFingerprint(current.journalRows)!==planned.journalFingerprint){throw new MigrationExecutionPlanError("MIGRATION_PLAN_CHANGED","local migration files or the database journal changed after audit; retry from a fresh plan",{planId:planned.planId})}}function assertMigrationExecutionPostcondition(planned,current){let isSatisfied=localFingerprint(current.localMigrations)===planned.localFingerprint;if(isSatisfied){try{isSatisfied=buildMigrationExecutionPlan(current).pending.length===0}catch{isSatisfied=false}}if(!isSatisfied){throw new MigrationExecutionPlanError("MIGRATION_POSTCONDITION_FAILED","not every audited migration was recorded with its exact immutable hash",{planId:planned.planId})}}var MigrationExecutionPlanError;var init_migration_execution_plan=__esm({"../platform/src/migration-execution-plan.ts"(){"use strict";MigrationExecutionPlanError=class extends Error{code;migrationName;migrationHash;planId;constructor(code,detail,metadata={}){super(`${code}: ${detail}`);this.name="MigrationExecutionPlanError";this.code=code;this.migrationName=metadata.migrationName;this.migrationHash=metadata.migrationHash;this.planId=metadata.planId}}}});function isWordStart(char){return!!char&&/[A-Za-z_\u0080-\uFFFF]/u.test(char)}function isWordPart(char){return!!char&&/[A-Za-z0-9_$\u0080-\uFFFF]/u.test(char)}function readQuotedToken(sql217,start2,quote2,options={}){let index27=start2+1;while(index27<sql217.length){if(options.backslashEscapes&&sql217[index27]==="\\"&&index27+1<sql217.length){index27+=2;continue}if(sql217[index27]!==quote2){index27+=1;continue}if(sql217[index27+1]===quote2){index27+=2;continue}const end=index27+1;const tokenStart=options.tokenStart??start2;const raw2=sql217.slice(tokenStart,end);const quotedValue=sql217.slice(start2+1,index27);return{token:{kind:quote2==="'"?"string":"identifier",value:quote2==="'"?options.backslashEscapes?quotedValue.replace(/''/g,"'").replace(/\\(.)/gsu,"$1"):quotedValue.replace(/''/g,"'"):quotedValue.replace(/""/g,'"'),raw:raw2,start:tokenStart,end},next:end}}return{next:sql217.length,error:quote2==="'"?"unterminated SQL string":"unterminated identifier"}}function readDollarString(sql217,start2){const opener=sql217.slice(start2).match(/^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/)?.[0];if(!opener)return null;const closeIndex=sql217.indexOf(opener,start2+opener.length);if(closeIndex<0)return{next:sql217.length,error:"unterminated dollar-quoted SQL body"};const end=closeIndex+opener.length;const raw2=sql217.slice(start2,end);return{token:{kind:"dollar-string",value:raw2.slice(opener.length,-opener.length),raw:raw2,start:start2,end},next:end}}function skipBlockComment(sql217,start2){let depth=1;let index27=start2+2;while(index27<sql217.length){if(sql217.startsWith("/*",index27)){depth+=1;index27+=2;continue}if(sql217.startsWith("*/",index27)){depth-=1;index27+=2;if(depth===0)return{next:index27};continue}index27+=1}return{next:sql217.length,error:"unterminated SQL block comment"}}function buildStatement(sql217,tokens,end){if(tokens.length===0)return null;return{text:sql217.slice(tokens[0].start,tokens[tokens.length-1].end).trim(),tokens,start:tokens[0].start,end}}function lexSqlStatements(sql217){const statements=[];let statementTokens=[];let index27=0;while(index27<sql217.length){const char=sql217[index27];if(/\s/u.test(char)){index27+=1;continue}if(sql217.startsWith("--",index27)){const newline=sql217.indexOf("\n",index27+2);index27=newline<0?sql217.length:newline+1;continue}if(sql217.startsWith("/*",index27)){const block=skipBlockComment(sql217,index27);if(block.error)return{statements,error:block.error};index27=block.next;continue}if((char==="E"||char==="e")&&sql217[index27+1]==="'"){const quoted=readQuotedToken(sql217,index27+1,"'",{tokenStart:index27,backslashEscapes:true});if(quoted.error||!quoted.token){return{statements,error:quoted.error??"invalid escape string"}}statementTokens.push(quoted.token);index27=quoted.next;continue}if(char==="'"||char==='"'){const quoted=readQuotedToken(sql217,index27,char);if(quoted.error||!quoted.token)return{statements,error:quoted.error??"invalid quoted token"};statementTokens.push(quoted.token);index27=quoted.next;continue}if(char==="$"){const dollar=readDollarString(sql217,index27);if(dollar){if(dollar.error||!dollar.token)return{statements,error:dollar.error??"invalid dollar string"};statementTokens.push(dollar.token);index27=dollar.next;continue}}if(isWordStart(char)){let end=index27+1;while(isWordPart(sql217[end]))end+=1;const raw2=sql217.slice(index27,end);statementTokens.push({kind:"word",value:raw2.toLowerCase(),raw:raw2,start:index27,end});index27=end;continue}if(char===";"){const statement=buildStatement(sql217,statementTokens,index27+1);if(statement)statements.push(statement);statementTokens=[];index27+=1;continue}statementTokens.push({kind:"symbol",value:char,raw:char,start:index27,end:index27+1});index27+=1}const tail=buildStatement(sql217,statementTokens,statementTokens.at(-1)?.end??sql217.length);if(tail)statements.push(tail);return{statements}}function createSqlLineNumberResolver(sql217){const lineStarts=[0];for(let offset=0;offset<sql217.length;offset+=1){if(sql217[offset]==="\n")lineStarts.push(offset+1)}return offset=>{let low=0;let high=lineStarts.length;while(low<high){const middle=Math.floor((low+high)/2);if(lineStarts[middle]<=offset)low=middle+1;else high=middle}return low}}var init_migration_sql_lexer=__esm({"../platform/src/migration-sql-lexer.ts"(){"use strict"}});async function readMigrationPostExecutionSnapshot(params){let lastError;for(const delayMs of POST_EXECUTION_READ_RETRY_DELAYS_MS){if(delayMs>0)await Bun.sleep(delayMs);try{return{local:await params.readLocal(),journal:await params.readJournal()}}catch(error62){lastError=error62}}throw lastError}function safeObjectField(value2,key2){try{return value2[key2]}catch{return void 0}}function collectFailureFacts(error62){const sqlStates=new Set;const errorCodes=new Set;const queries=new Set;const visited=new Set;const pending=[error62];for(let inspected=0;inspected<64&&pending.length>0;inspected+=1){const current=pending.shift();if(!current||typeof current!=="object")continue;if(visited.has(current))continue;visited.add(current);for(const key2 of["code","errno"]){const value2=safeObjectField(current,key2);if(typeof value2==="string"&&/^[a-zA-Z0-9_:-]{1,80}$/u.test(value2)){errorCodes.add(value2);if(/^(?=.*[0-9])[0-9A-Z]{5}$/u.test(value2))sqlStates.add(value2)}}const query2=safeObjectField(current,"query");if(typeof query2==="string")queries.add(query2);const cause=safeObjectField(current,"cause");if(cause&&typeof cause==="object")pending.push(cause);const errors=safeObjectField(current,"errors");if(Array.isArray(errors)){pending.push(...errors.slice(0,16))}}return{sqlStates:[...sqlStates],errorCodes:[...errorCodes],queries:[...queries]}}function isExactPostgresSqlStateFailure(error62,sqlState){if(!/^[0-9A-Z]{5}$/u.test(sqlState))return false;const sqlStates=collectFailureFacts(error62).sqlStates;return sqlStates.length>0&&sqlStates.every(observed2=>observed2===sqlState)}function canonicalStatement(statement){return statement.trim().replace(/;\s*$/u,"").trim()}function statementLocation(source,statement,statementIndex){const lexed=lexSqlStatements(source.sqlContent);if(lexed.error)return void 0;const canonical=canonicalStatement(statement);const matches=lexed.statements.filter(candidate=>canonicalStatement(candidate.text)===canonical);if(matches.length!==1)return void 0;const[match2]=matches;const lineAt=createSqlLineNumberResolver(source.sqlContent);return{name:source.metadata.name,sqlSha256:source.metadata.hash,statementIndex,lineStart:lineAt(match2.start),lineEnd:lineAt(Math.max(match2.end-1,match2.start))}}function findExactFailureLocation(queries,pendingSources){const querySet=new Set(queries);const matches=[];for(const source of pendingSources){for(const[index27,statement]of source.metadata.sql.entries()){if(!querySet.has(statement))continue;const location=statementLocation(source,statement,index27+1);if(location)matches.push(location)}}return matches.length===1?matches[0]:void 0}function retryableReason(sqlStates){for(const state2 of sqlStates){const exact=RETRYABLE_SQLSTATES.get(state2);if(exact)return exact;if(state2.startsWith("08"))return"database_connection_lost"}return void 0}function userReason(sqlStates){for(const state2 of sqlStates){const exact=USER_SQLSTATE_REASONS.get(state2);if(exact)return exact;if(/^(22|23|42)/u.test(state2)||state2==="P0001"){return`postgres_sqlstate_${state2.toLowerCase()}`}}return void 0}function platformReason(sqlStates){for(const state2 of sqlStates){const exact=PLATFORM_SQLSTATE_REASONS.get(state2);if(exact)return exact}return void 0}function buildMigrationTransactionRolledBackError(params){const facts=collectFailureFacts(params.cause);const platformFailure=platformReason(facts.sqlStates);if(platformFailure){return new MigrationTransactionRolledBackError({failureClass:"PLATFORM_ACTION_REQUIRED",reasonCode:platformFailure,planId:params.planId})}const transient=retryableReason(facts.sqlStates);if(transient){return new MigrationTransactionRolledBackError({failureClass:"RETRYABLE_INFRA",reasonCode:transient,planId:params.planId})}const migration=findExactFailureLocation(facts.queries,params.pendingSources);const userFailure=userReason(facts.sqlStates);if(userFailure){return new MigrationTransactionRolledBackError({failureClass:"USER_FIXABLE",reasonCode:userFailure,planId:params.planId,...migration?{migration}:{}})}if(facts.sqlStates.length===0){console.warn(`[migration] execution failure had no PostgreSQL SQLSTATE in the redacted cause chain codes=${facts.errorCodes.join(",")||"none"}`)}return new MigrationTransactionRolledBackError({failureClass:"UNCLASSIFIED",reasonCode:"execution_failure_unclassified",planId:params.planId})}var RETRYABLE_SQLSTATES,USER_SQLSTATE_REASONS,PLATFORM_SQLSTATE_REASONS,POST_EXECUTION_READ_RETRY_DELAYS_MS,MigrationTransactionRolledBackError;var init_migration_execution_outcome=__esm({"../platform/src/migration-execution-outcome.ts"(){"use strict";init_migration_sql_lexer();RETRYABLE_SQLSTATES=new Map([["40001","serialization_failure"],["40P01","deadlock_detected"],["55P03","lock_not_available"],["57014","statement_timeout_or_cancelled"],["53300","too_many_connections"],["53400","configuration_limit_exceeded"],["57P01","database_admin_shutdown"],["57P02","database_crash_shutdown"],["57P03","database_starting_up"]]);USER_SQLSTATE_REASONS=new Map([["22001","string_data_right_truncation"],["22P02","invalid_text_representation"],["25001","active_sql_transaction"],["23502","not_null_violation"],["23503","foreign_key_violation"],["23505","unique_violation"],["42601","syntax_error"],["42701","duplicate_column"],["42703","undefined_column"],["42P01","undefined_table"],["42P07","duplicate_table"]]);PLATFORM_SQLSTATE_REASONS=new Map([["42501","insufficient_privilege"],["0A000","feature_not_supported"],["28000","invalid_authorization_specification"],["28P01","invalid_password"]]);POST_EXECUTION_READ_RETRY_DELAYS_MS=[0,25,100,250];MigrationTransactionRolledBackError=class extends Error{code="MIGRATION_TRANSACTION_ROLLED_BACK";failureClass;reasonCode;planId;migration;constructor(params){super("MIGRATION_TRANSACTION_ROLLED_BACK: the PostgreSQL transaction was rolled back");this.name="MigrationTransactionRolledBackError";this.failureClass=params.failureClass;this.reasonCode=params.reasonCode;this.planId=params.planId;this.migration=params.migration}}}});function base(error62,correlationId){return{code:error62.code,phase:"EXECUTE",databaseState:"ROLLED_BACK",correlationId}}function buildRolledBackDiagnostic(params){const{error:error62,correlationId,migration}=params;if(error62.failureClass==="RETRYABLE_INFRA"){return retryableInfraDiagnostic({...base(error62,correlationId),retryPolicy:"AFTER_DELAY",retryCondition:"Retry the same immutable bundle after the temporary PostgreSQL condition clears.",retryAfterSeconds:5,reason:{code:error62.reasonCode,summary:"The migration transaction was rolled back after a temporary database failure.",detail:"PostgreSQL confirmed that the transaction and its journal writes did not commit. No source edit is recommended."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}if(error62.failureClass==="USER_FIXABLE"){const hasExactLocation=migration!==void 0;const repairHint=USER_REASON_REPAIR_HINTS.get(error62.reasonCode);const suggestedFixes=[{id:"repair-pending-migration",title:hasExactLocation?"Repair the exact unapplied migration statement":"Inspect the pending migration candidates",detail:[hasExactLocation?"Update the schema source or this unapplied statement, review the generated diff, and create a fresh immutable plan.":"Run db:check to list the pending migrations, locate the statement matching this PostgreSQL reason, then update only unapplied source and create a fresh plan.",repairHint].filter(Boolean).join(" "),target:"PENDING_MIGRATION",confidence:hasExactLocation?"HIGH":"MEDIUM"}];return userFixableDiagnostic({...base(error62,correlationId),retryCondition:"Fix only the exact unapplied statement, then create and check a fresh plan.",...migration?{migration}:{},reason:{code:error62.reasonCode,summary:hasExactLocation?"PostgreSQL rejected an exact pending migration statement and rolled back the transaction.":"PostgreSQL rejected a pending migration, but the exact source span was not unique.",detail:hasExactLocation?"Review the identified statement against the current schema and data. The failed transaction did not commit any migration or journal change.":"Use the stable PostgreSQL reason and the pending list from db:check to identify the customer-owned statement. The transaction and journal did not commit."},suggestedFixes,forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"REDACTED_LITERALS"}})}if(error62.failureClass==="PLATFORM_ACTION_REQUIRED"){return retryableInfraDiagnostic({...base(error62,correlationId),retryPolicy:"AFTER_DELAY",retryAfterSeconds:30,retryCondition:"View the operation receipt and retry only after the Platform DDL permission or runner health has recovered.",reason:{code:error62.reasonCode,summary:"PostgreSQL rolled back because the managed DDL execution boundary was unavailable.",detail:"The transaction and journal did not commit. This is not fixed by editing applied migrations or the journal; use the receipt status before another attempt."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}return platformActionDiagnostic({...base(error62,correlationId),nextAction:"INSPECT_STATE",retryCondition:"Check the operation receipt status before any new mutation request. Do not retry blindly.",reason:{code:error62.reasonCode,summary:"The transaction rolled back, but its cause could not be classified automatically.",detail:"PostgreSQL did not return a recognized error code for this failure. The transaction and journal did not commit. Do not edit applied migrations or the journal."},suggestedFixes:[],forbiddenActions:[...params.forbiddenActions],redaction:{serverReturnedRawSql:false,localExcerpt:"NONE"}})}var USER_REASON_REPAIR_HINTS;var init_migration_rollback_diagnostic=__esm({"../platform/src/migration-rollback-diagnostic.ts"(){"use strict";init_dist();USER_REASON_REPAIR_HINTS=new Map([["invalid_text_representation","For a value that does not match its column type, change the column DEFAULT or inserted literal in gencow/schema.ts to a value valid for the declared type (for example, a whole number for an integer column), then run db:generate to replace only this unapplied migration."],["string_data_right_truncation","For a value longer than its column allows, shorten the literal or change the column length in gencow/schema.ts, then run db:generate to replace only this unapplied migration."]])}});function toJournalRow(row){const id=row.id;const hash9=row.hash;const createdAt=row.created_at;const name=row.name;if(typeof id!=="number"||!Number.isSafeInteger(id)||id<1||typeof hash9!=="string"||hash9.length===0||typeof createdAt!=="string"&&typeof createdAt!=="number"&&typeof createdAt!=="bigint"||name!==null&&(typeof name!=="string"||name.length===0)){throw new MigrationJournalReadError("a journal row has an invalid id, name, hash, or timestamp")}return{id,hash:hash9,createdAt:String(createdAt),name}}async function readDrizzleMigrationJournal(params){if(!params.snapshot.journalTableExists)return[];const rows8=await params.sql.unsafe(`
8984
8984
  SELECT id, hash, created_at::text AS created_at, name
8985
8985
  FROM "drizzle"."__drizzle_migrations"
8986
8986
  ORDER BY id